// nova-tourism/pages/my/my-order/index.js
let Parse = getApp().Parse;
const company = getApp().globalData.company
const uid = Parse.User.current()?.id
const dateF = require("../../../../utils/date")
const req = require('../../../../utils/request')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentTab: 0, //订单状态-页面（处理中0，进行中1，已完成2）
    roomList: [],
    show: false,
    showid: null,
    statusMap: {
      100: '已支付',
      200: '已入住',
      300: '续住',
      400: '已退房',
      500: '申请退款',
      601: '退款审核通过',
      602: '退款已驳回',
      700: '退款成功',
      800: '已完成',
      101: '已取消支付',
      102: '已完申请退房成',
      103: '退房成功',
      104: '退房被驳回',
      105: '未支付',
    },
    statusMap_shop: {
      '100': '待支付',
      '200': '已支付',
      '300': '已发货',
      '400': '已收货',
      '500': '申请退款',
      '601': '退款申请通过',
      '602': '退款被驳回',
      '700': '退款成功',
      '800': '订单完成',
    },
    roomTabMap: {
      0: "(100,500,601,602)", //已支付,申请退款,退款审核通过,退款已驳回
      1: "(200,102,104)", //已入住,申请退房,退房被驳回
      2: "(400,700,800,103)", //已退房,退款成功,已完成,退房成功
    },
    goodTabMap: {
      0: "('200','500','601','602')", //已支付,申请退款,退款审核通过,退款已驳回
      1: "('300')", //已发货
      2: "('400','700','800')", //已收货,退款成功,订单完成
    },
    order: [], //订单列表
  },
  onClose() {
    this.setData({
      show: false,
    });
  },
  ONShow(e) {
    let {
      oid
    } = e.currentTarget.dataset
    this.setData({
      showid: oid,
      show: true,
    }); // 设置弹窗显示
  },
  //订单完成
  async ordercom(e) {
    console.log(e.currentTarget.dataset.item.objectId);
    let objectId = e.currentTarget.dataset.item.objectId
    let newOrder = new Parse.Query('RoomOrder');
    newOrder.equalTo('company', company);
    newOrder.equalTo('objectId', objectId);
    newOrder.notEqualTo('isDeleted', true);
    let order = await newOrder.first();
    console.log(order);
    order.set('status', 102)
    try {
      let saveDate = await order.save();
      console.log('保存成功');
      this.setData({
        showid: null
      })
      this.getOrder()
    } catch (error) {
      console.error("保存数据时出现错误:", error);
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      currentTab: Number(options.active)
    })
  },
  async refersh() {
    this.getOrder()
  },
  /**获取订单 */
  async getOrder() {
    let {
      order,
      currentTab,
      roomTabMap,
      goodTabMap
    } = this.data
    let rosql = `AND ro."status" IN ${roomTabMap[currentTab]}`
    let gosql = `AND o."status" IN ${goodTabMap[currentTab]}`
    let sql = `WITH "order" AS(
    SELECT t1."objectId",t1."createdAt",t1."startTime",t1."endTime",t1."status",t1."totalPrice",sg."name",ss."storeName" AS "table",sg."image",sg."tag"::jsonb AS "tags",(t1."spec"::jsonb->'spec')::text AS "spec",(t1."spec"::jsonb->'list')::text AS "list",'good' AS "ot"
    FROM (
      SELECT o."objectId",o."createdAt",o."status"::text,o."totalPrice"::text,o."startTime",o."endTime",o."store",
      jsonb_array_elements(o."targetObject")::json->>'objectId' AS "gid",spec.value AS "spec"
      FROM "Order" o,
      jsonb_each(o."specMap") AS spec (key, value)
      WHERE o."company"='${company}'
      AND o."isDeleted" IS NOT TRUE
      AND o."user"='${uid}'
      AND o."type"='scenery'
      ${gosql}
      AND o."isPay" IS TRUE
    )t1
    LEFT JOIN "ShopGoods" sg ON sg."objectId" = t1."gid"
    LEFT JOIN "ShopStore" ss ON ss."objectId" = t1."store"
  ),
  "room_order" AS(
    SELECT ro."objectId",ro."createdAt",ro."startTime",ro."endTime",
    ro."status"::text,ro."price"::text AS "totalPrice",r."name",store."storeName" AS "table",
    r."images"->> 0 AS "image",r."tags"::jsonb AS "tags",''::text AS "spec",''::text AS "list",'room' AS "ot"
    FROM "RoomOrder" ro
    LEFT JOIN "ShopRoom" r ON r."objectId"=ro."room" 
    LEFT JOIN "ShopStore" store ON store."objectId"=r."shop"
    WHERE ro."company"='${company}'
    AND ro."isDeleted" IS NOT TRUE
    AND ro."user"='${uid}'
    AND ro."isPay" IS TRUE
    ${rosql}
  ),
  "tog" AS (
    SELECT * FROM "order"
    UNION ALL
    SELECT * FROM "room_order"
  )
  SELECT * FROM "tog" 
  ORDER BY "tog"."createdAt" DESC 
  LIMIT 20 OFFSET ${order?.length||0}`
    let d = await req.customSQL(sql) || []
    d?.map(item => {
      if (item.list) {
        item.list = JSON.parse(item.list || '[]') || []
      }
      if (item.startTime && item.endTime) {
        item.fromto = `${dateF.formatTime('YYYY年mm月dd日',item.startTime)}入住 - ${dateF.formatTime('YYYY年mm月dd日',item.endTime)}离店`
      }
      return item
    })
    console.log(d)

    this.setData({
      order: [...order, ...(d || [])]
    })
  },
  /**切换状态 */
  async switchTab(e) {
    const index = e.currentTarget.dataset.index;
    await this.setData({
      currentTab: index,
      order: []
    });
    this.getOrder()
  },
  /**已支付订单100-退款 */
  async checkout100(e) {
    console.log(e)
    let {
      oid
    } = e.currentTarget.dataset
    let query = new Parse.Query('RoomOrder')
    let order = await query.get(oid)
    order.set('status', 500)
    await order.save()
    await this.setData({
      order: [],
      show: false,
    });
    this.getOrder()
  },
/**商品订单 - 退款详情 */
refundGift(e){

},
  /**商品订单-确认收货 */
  receiving(e) {
    console.log(e)
    let {
      oid
    } = e.currentTarget.dataset
    wx.showModal({
      content: '确认收货吗？',
      success:async (res)=> {
        if (res.confirm) {
          wx.showLoading({
            title: '加载中...',
          })
          let query = new Parse.Query('Order')
          let order = await query.get(oid)
          order.set('status', '400')
          await order.save()
          await this.setData({
            order: [],
            show: false,
          });
          await this.getOrder()
          wx.hideLoading()
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })

  },

  tourl(e) {
    let url = e.currentTarget.dataset.url
    wx.navigateTo({
      url: `${url}`,
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getOrder()

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.getOrder()
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})