import {
  get,
  post
} from '../../utils/http'
const app = getApp()

Page({
  /**
   * 页面的初始数据
   */
  data: {
    current: 0,
    list: [],
    total: 0,
    page: 1,
    pay_methon: 1,
    payNow: false,
    showImg: '',
    showLandScape: false,
    orderStr: ['未付款', '待使用', '进行中', '已结算', '已取消'],
  },

  onCloseLandscape: function () {
    this.setData({
      showLandScape: false
    })
  },

  pay_methonw() {
    this.setData({
      pay_methon: 1
    })
  },

  pay_methonc() {
    this.setData({
      pay_methon: 2
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.current) {
      this.setData({
        current: options.current
      })
    }
    let lat1 = app.address.latitude
    let lng1 = app.address.longitude
    this.setData({
      lat1: lat1,
      lng1: lng1,
    })
  },

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

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

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

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

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

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.page * 10 < this.data.total) {
      this.getOrder(++this.data.page)
    }
  },

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

  /**
   * 切换tabs
   */
  onTabsChange(e) {
    let current = e.currentTarget.dataset.id
    if (current == this.data.current) {
      return
    }
    this.setData({
        current,
        page: 1
      },
      () => {
        this.getOrder()
      }
    )
  },

  /**
   * 取消订单
   */
  onCancelOrder(e) {
    let that = this
    wx.showModal({
      title: '提示',
      content: '是否取消当前预约',
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定')
          post(
            'v2/api/order/cancel', {
              id: e.currentTarget.dataset.id
            },
            (res) => {
              wx.showToast({
                title: res.msg,
                icon: 'success',
                duration: 2000
              })
              that.getOrder(1)
            }
          )
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },

  oneMore(e) {
    let current = e.currentTarget.dataset.id
    let price = e.currentTarget.dataset.price
    this.getOrderData(current, price)
  },

  /**
   * 获取订单详情
   */
  getOrderData(current, price) {
    get('v2/api/order/info', {
      id: current
    }, (res) => {
      let orderDetails = res.data.project_list
      for (let i = 0; i < orderDetails.length; i++) {
        if (orderDetails[i].product_name) {
          orderDetails[i].selectMaterial = {}
          orderDetails[i].selectMaterial.name = orderDetails[i].product_name
          orderDetails[i].selectMaterial.id = orderDetails[i].product_id
        }
      }

      console.log(orderDetails)
      wx.redirectTo({
        url: '../reserveCar/reserveCar?data=' + JSON.stringify(orderDetails) + '&&money=' + price + '&&type=project',
      })


    })
  },

  // 点击立即支付
  payNow: function (e) {
    let id = e.currentTarget.dataset.id
  },


  // 点击了美导师
  beautyImg: function (e) {
    let img = e.currentTarget.dataset.img
    this.setData({
      showImg: img,
      showLandScape: true
    })
  },


  onPay: function (e) {
    this.setData({
      order_id: e.currentTarget.dataset.id,
      payMoney: e.currentTarget.dataset.money,
      payNow: true
    })
  },

  /**
   * 支付
   */
  payNow() {
    let that = this
    that.methonPayOrder()
  },

  onClosePay() {
    this.setData({
      payNow: false
    })
  },

  /**
   * 去支付
   */
  methonPayOrder() {
    let that = this
    post(
      'api/pay/project', {
        order_id: this.data.order_id,
        pay_way: this.data.pay_methon == 1 ? 'weixin' : 'amount',
      },
      (res) => {

        that.setData({
          payNow: false
        })

        if (that.data.pay_methon == 2) {
          setTimeout(() => {
            that.setData({
              current: 1
            }, () => {
              that.getOrder(1)
              that.getAmount()
            })
          }, 1000)
          get('api/message/ids', {}, (res) => {
            let ids = res.data.ids
            that.onSubmitCh(ids)
          })
          return
        }

        wx.requestPayment({
          timeStamp: res.data.pay_data.timeStamp,
          nonceStr: res.data.pay_data.nonceStr,
          package: res.data.pay_data.package,
          signType: res.data.pay_data.signType,
          paySign: res.data.pay_data.paySign,
          success(res) {
            if (res.errMsg == 'requestPayment:ok') {
              wx.showToast({
                title: '支付成功',
                icon: 'success'
              })
              setTimeout(() => {
                that.setData({
                  current: 1
                }, () => {
                  that.getOrder(1)
                })
              }, 1000)
              get('api/message/ids', {}, (res) => {
                let ids = res.data.ids
                wx.requestSubscribeMessage({
                  tmplIds: ids,
                  success(res) {
                    console.log(res)
                    that.messageAgree(ids, e.currentTarget.dataset.id)
                  },
                  fail(rej) {
                    console.log(rej)
                    that.messageAgree(ids)
                    wx.showToast({
                      title: JSON.stringify(rej),
                      icon: 'error'
                    })
                  }
                })
              })
            }
          },
          fail(res) {
            wx.showToast({
              title: '支付失败',
              icon: 'error'
            })
          }
        })
      }
    )
  },

  onSubmitCh(ids) {
    let that = this
    wx.showModal({
      title: '提示',
      content: '支付成功! 是否进行消息提醒',
      success: function (res) {
        if (res.confirm) {
          that.onSubmitTrue(ids)
        } else if (res.cancel) {
          that.messageAgree(ids, this.data.order_id)
        }
      }
    });
  },

  /**
   * 获取我的储值
   * api/user
   */
  getAmount() {
    get('api/user/amount', {}, (res) => {
      if (res.data) {
        this.setData({
          inserllAmount: res.data.amount
        })
      }
    })
  },


  onSubmitTrue(ids) {
    let that = this
    wx.requestSubscribeMessage({
      tmplIds: ids,
      success(res) {
        console.log(res)
        that.messageAgree(ids, this.data.order_id)
      },
      fail(rej) {
        console.log(rej)
        that.messageAgree(ids, this.data.order_id)
        wx.showToast({
          title: JSON.stringify(rej),
          icon: 'error'
        })
      }
    })
  },

  /**
   * 获取订单列表
   * api/order
   * 订单分类，1已预约，2待使用，3进行中，4已结算，5已取消
   */
  getOrder(_page) {
    let {
      list,
      current,
      page
    } = this.data
    get(
      'v2/api/order/list', {
        type: Number(current) + 1,
        page: _page || page,
        limit: 10
      },
      (res) => {
        if (_page == 1 || page == 1) {
          list = []
          this.data.page = 1
        }
        list.push(...res.data.list)
        this.setData({
          list,
          total: res.data.total
        })
      }
    )
  },

  /**
   * 用户允许消息通知
   * /api/message/agree
   */
  messageAgree(ids, order_id) {
    post(
      'api/message/agree', {
        order_id,
        ids
      },
      () => {}
    )
  }
})