// pages/groupmeallist/orderDetail/orderDetail.js
import order from '../../../api/order'
const cache = require('../../../utils/cache.js');
import Activity from '../../../api/activity';
const app = getApp()
import storeGoods from '../../../api/storeGoods'
import base from "../../../utils/base";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    orderGoodList: [{}, {}, {}, {}],
    showAllSku: false,
    orderInfo: {},
    orderSn: '',
    orderGoodList:[], //spu-sku商品信息
  },
  //全部显示和收起
  handleFlodExtend() {
    this.setData({
      showAllSku: !this.data.showAllSku
    })
  },
  // 取消订单
  cancelOrder() {
    let orderSn = this.data.orderSn

    let _self = this

    wx.showModal({
      title: '提示',
      content: '确认取消订单？',
      confirmColor: '#AFD250',
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定')

          order.cancelOrder({
            orderSn: orderSn,
            mobile: cache.getMobile(),
          }).then(res => {
            if (res.code == 200) {
              console.log('进入 刷新页面')
              _self.reloadPage(orderSn);
            }
          }).catch(_ => {})
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })

  },

// 点击复制
copywxtap: function (event) {
  // var wxChat = event.currentTarget.dataset.wechatid //接收wxml传过来的数据
  wx.showToast({
    title: '复制成功',
  })

// 下方为微信开发文档中的复制 API
  wx.setClipboardData({
    data: this.data.orderSn, //复制的数据
    success: function (res) {
      wx.getClipboardData({
        success: function (res) {
          console.log(res.data) //打印赋值的数据
        }
      })
    }
  })
},
 /**
     * 打电话
     */
    callMobile(e) {
      let phone = e.currentTarget.dataset.mobile;
      wx.makePhoneCall({
          phoneNumber: phone 
      })
  },

  // 申请退款
  goTorefund() {
    wx.navigateTo({
      url: '/pages/groupmeallist/refund/refund?sn='+this.data.orderSn,
    })




  },

  //立即支付
  handelToPay(e) {
    let orderSn = this.data.orderSn;
    console.log(orderSn)

    storeGoods.getPayParams({
      orderSn: orderSn,
      payCode: "HSAY-SHARE",
      openId: Activity.getOpenId(),
      isOrderPayment: true,
      orderInfoPath: "/pages/orderDetail/orderDetail?sn=" + orderSn,
      productDetailPath: "../storeGoods/storeGoods",
    }).then(res => {
      if (res.code == 200) {
        this.rousePayment(res.data, this.data.orderInfo)
      }
    }).catch(_ => {
      console.log(_)
    })
  },
  rousePayment(payParam, order) {
    let _self = this;
    wx.requestOrderPayment({
      timeStamp: payParam.wxPrePay.timeStamp,
      package: payParam.wxPrePay.pack,
      nonceStr: payParam.wxPrePay.nonceStr,
      signType: payParam.wxPrePay.signType,
      paySign: payParam.wxPrePay.paySign,
      orderInfo: payParam.orderInfo,
      success: function (res) {
        //支付成功，跳转领取成功页面
        OrderApi.getPayStatus(order.orderSn);
        app.showToast("支付成功")
        order.state = 2
        order.stateText = "已支付"
        _self.setData({
          orderInfo: order
        })
      },
      fail: function (res) {
        app.showToast("支付失败")
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.sn) {
      this.reloadPage(options.sn)
    }
  },

  reloadPage(orderSn) {
    this.setData({
      orderSn
    })

    this.getOrderdetail();
  },
  /**
   * 获取订单详情
   */
  async getOrderdetail() {
    let _self = this;
    try {
      let orderRes = await order.getOrderDetail({
        orderSn: _self.data.orderSn,
        mobile: cache.getMobile()
      });
      if (orderRes.code == 200 && orderRes.msg == "success") {
        let orderInfo = orderRes.data;
        orderInfo.originPrice = (parseFloat(orderInfo.payPrice) / 100).toFixed(2)
        _self.setData({
          orderInfo: orderInfo,
        })
        //组建spu sku
        _self.createOrderGoodList(orderInfo.orderGoodsList)
      }
    } catch (error) {
      console.log(error);
    }
  },


     /**
     * 组建spu sku
     * @param {*} list 
     */
    createOrderGoodList(list) {

      console.log("进入详情")
      console.log(list)
      let _self = this;
      if(list.length==0) {
          return;
      }
      let orderGoodList = [];
      for(let a=0;a<list.length;a++) { //最外层
          //某一个商品种类
          let goodList = list[a];
          //sku-list
          let orderGoodsSkuList = goodList.orderGoodsSkuList;
          for(let b=0;b<orderGoodsSkuList.length;b++) {
              let orderGood = {};
              orderGood.productName = goodList.productName;
              let orderGoodsSku = orderGoodsSkuList[b];
              let text = '';
            if(orderGoodsSku.comboSkuList !=null && orderGoodsSku.comboSkuList.length>0)
              {
                  console.log("进入套餐拼接")
                  text = "套餐:"
                  let productName = ''
                  let specValue = []
                  let num =''
                  orderGoodsSku.comboSkuList.forEach(function(comboSkuList, index){
                      comboSkuList.skuList.forEach(function(skuList,skuindex){
                          productName = skuList.productName
                          num = skuList.num
                          if(skuList.specList != null){
                          let specList = JSON.parse(skuList.specList);
                          if (base.isArray(specList)) {
                              specList.forEach(function(specList,skuindex){

                                  specValue.push(specList.specValue +" X"+num) 

                              })
                          }
                      }else{
                          specValue.push(productName +" X"+num) 
                      }
                      })
                  }
                  )
                  specValue = specValue.join('、') || ""
              text = text +"("+specValue+")"
           
              }
              orderGood.num = orderGoodsSkuList[b].num;
              orderGood.allFee = base.fenToYuan(orderGoodsSkuList[b].price * orderGoodsSkuList[b].num)
              orderGood.skuText = text
              orderGoodList.push(orderGood)
          }
      }
      _self.setData({
          orderGoodList:orderGoodList
      })

      console.log(this.data.orderGoodList)
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  // 详情和收起
  changeCollapseOrDetail: function (e) {
    let idx = e.currentTarget.dataset.idx;
    var that = this;
    that.data.orderGoodList[idx].show = !that.data.orderGoodList[idx].show
    that.setData({
      orderGoodList: that.data.orderGoodList
    });
    console.log("购物车详情");
    console.log(that.data.orderGoodList);
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

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

  },

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

  },

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

  },

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

  },

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

  }
})