// pages/welfareMall/historical/historical.js
import WelfareMall from '../../../api/welfareMall'
import order from '../../../api/order'
import storeGoods from '../../../api/storeGoods'
import Activity from '../../../api/activity';
const cache = require('../../../utils/cache.js');
import {
  parseTime
} from '../../../utils/util'
import base from "../../../utils/base";
import {
  getMobileCache,
  getPhoneNumber as getPhoneNumberSync,
  getColor
} from '../../../utils/user'

const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    page: 1,
    pageSize: 10,
    tpage: 1,
    tpageSize: 10,

    lock: false,
    noResult: false,
    noMore: false,
    tnoResult: false,
    tnoMore: false,
    mobileTop: 'TONY WU',
    orderList: [],
    torderList: [],
    config: {},
    currentData: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {

  },

  handleCancelOrder(e) {
    let orderSn = e.currentTarget.dataset.ord;
    console.log("取消订单")
    let that = this;
    wx.showModal({
      title: '',
      content: '是否确定取消订单？',
      success: function (sm) {
        if (sm.confirm) {
          console.log("确定了")
          order.cancelOrder({
            orderSn: orderSn,
            mobile: cache.getMobile(),
          }).then(res => {
            if (res.code == 200) {
              that.getTOrderList()
            }
          }).catch(_ => { })

        } else if (sm.cancel) {

        }
      }
    })
  },
  //立即支付
  handelToPay(e) {
    let orderSn = e.currentTarget.dataset.ord;
    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("支付失败")
      }
    })
  },
  // 申请退款
  goTorefund(e) {
    let sn = e.currentTarget.dataset.sn;


    wx.navigateTo({
      url: '/pages/groupmeallist/refund/refund?sn=' + sn,
    })




  },

  // goTorefundList(){
  //   wx.navigateTo({
  //     url: '/pages/groupmeallist/refundRecord/refundRecord',
  //   })
  // },
  // 团餐订单
  async getTOrderList() {

    try {

      let _self = this;
      let listRes = await order.getOrderList({
        mobile: getMobileCache(),
        page: this.data.tpage,
        pageSize: this.data.tpageSize,

      });


      if (listRes.code == 200) {
        let list = listRes.data;

        if (base.isEmpty(list) || list.length == 0) {
          if (this.data.page == 1) {
            this.setData({
              tnoResult: true
            })
          } else {
            this.setData({
              tnoMore: true
            })
          }
          return
        }

        list.map((item, index) => {
          item.showPrice = (parseFloat(item.payPrice) / 100).toFixed(2);
        })
        console.log("准备重新塞值了")
        console.log(list)
        _self.setData({
          torderList: _self.data.torderList.concat(...list)
        })
        console.log("重新塞值了")
        console.log(list)
      }
    } catch (error) {
      console.log("订单报错");
      console.log(error);
    }
  },
  // 订单数据
  getOrderList: function () {
    WelfareMall.getOrderList({
      page: this.data.page,
      pageSize: this.data.pageSize,
      mobile: getMobileCache(),
    }).then(res => {
      if (res.code == 200) {
        this.userOrderListView(res.data)
      }
      this.data.lock = false
    }).catch(_ => {
      console.log(_)
      this.data.lock = false
    })
  },

  userOrderListView: function (data) {
    if (!Array.isArray(data) || data.length == 0) {
      console.log("订单列表数据为空");
      if (this.data.page == 1) {
        this.setData({
          mobileTop: getMobileCache(),
          noResult: true
        })
      } else {
        this.setData({
          mobileTop: getMobileCache(),
          noMore: true
        })
      }
      return
    }
    // data.forEach(v => {
    //     let payeTime = v.payedAt
    //     v.payedAt = parseTime(payeTime, "{y}.{m}.{d} {h}:{i}:{s}")
    // })

    this.data.orderList = this.data.orderList.concat(...data)
    this.setData({
      mobileTop: getMobileCache(),
      orderList: this.data.orderList
    })
  },

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

  },

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

    // 重置页码
    this.setData({
      tpage: 1,
      tpageSize: 10,

    })

    this.getTOrderList();
    let info = await getColor();
    this.setData({
      config: info.config
    })
    console.log(info)
  },



  /**
   * 跳转订单详情
   * @param {*} e 
   */
  orderDetail(e) {

    this.setData({
      torderList: []
    })

    let ordersn = e.currentTarget.dataset.sn;
    let refund = e.currentTarget.dataset.refund;

    if (refund != null) {
      wx.navigateTo({
        url: '/pages/groupmeallist/myOrder/myOrder?sn=' + ordersn,
      })


    } else {
      wx.navigateTo({
        url: '/pages/groupmeallist/orderDetail/orderDetail?sn=' + ordersn,
      })

    }

  },

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

  },

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

  },

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

  },

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

  },

  getCompletion(e) {
    const url = "../order/orderCompletion?ordersn=" + e.currentTarget.dataset.ordersn
    wx.navigateTo({
      url
    })
  },

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

  },
  //点击切换，滑块index赋值
  checkCurrent: function (e) {
    const that = this;

    if (that.data.currentData === e.target.dataset.current) {
      return false;
    } else {

      that.setData({
        currentData: e.target.dataset.current
      })
    }
  },

  //获取当前滑块的index
  bindchange: function (e) {
    const that = this;
    that.setData({
      currentData: e.detail.current
    })
  },
  bottomefficientList() {
    if (this.data.lock || this.data.noMore) {
      return
    }
    this.data.lock = true
    this.data.page++
    this.getOrderList();

  },
  bottomefficientListbyOrder() {
    let _self = this;
    console.log("上拉刷新")
    _self.setData({
      tpage: _self.data.tpage + 1
    })
    _self.getTOrderList()
  },

  goToOrderDetail() {
    wx.navigateTo({
      url: '/pages/groupmeallist/orderDetail/orderDetail',
    })


  }
})