// pages/voucher/voucher.js
const api = require('../../api/index')
const pay = require('../../utils/pay')
const  Decimal = require('../../utils/decimal');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    myVoucherList:[],
  myVoucherTotal:0,
  discount:0,
  chooseVoucher:[],
  useScopes:null,
  totalPrice:0,
  voucherList:[],
  buyVoucher:[],
  payMoney:0,
  all:null,
  other:{
    activityId:null,
  }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if(options.all){
      this.setData(
        {
          all:options.all
        }
      )
      this.queryPersonVoucher()
    }
    const eventChannel = this.getOpenerEventChannel()
    var that = this
    eventChannel.on('acceptDataFromPay', function(data) {
      that.setData(
        {
          chooseVoucher:data.chooseVoucher,
          useScopes:data.useScopes,
          totalPrice:data.totalPrice
        }
      )
      that.queryPersonVoucher(1)
    })
    //获取可购买的优惠券
    this.queryVoucher()
    
  },

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

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },
  //获取可购买的优惠券
  queryVoucher(){
    api.queryVoucher().then(res=>{
      if(res.code == 200){
        this.setData(
          {
            voucherList:res.data.data
          }
        )
      }
    })
  },
  //查询个人优惠券
  queryPersonVoucher(sign){
    var params = {
      // useScopes:(this.data.useScopes == null || this.data.useScopes.length == 0)?null:[this.data.useScopes],
      ifExpiration:false,
    }
    api.queryPersonVoucher(params).then(res=>{
      if(res.code == 200){
        var data = res.data.data
        this.dataHandling(data)

        // var data2 = data.filter(item=>{
        //   if(item.threshold <= Number(this.data.totalPrice) || this.data.all){
        //     item.useScopesText = this.getUseScopeText(item.useScopes)
        //     return item
        //   }
        // })
        // this.setData(
        //   {
        //     myVoucherList:data2,
        //     myVoucherTotal:data2.length
        //   }
        // )
        if(sign == 1 && this.data.chooseVoucher){
          this.changeChooseVoucher(
            {
              detail:this.data.chooseVoucher
            }
          )
        }
      }
    })
  },
  //数据处理
  dataHandling(data){
    var usable = []
    var disabled = []
    if(this.data.all){
      for(var i = 0;i<data.length;i++){
        var item = data[i]
        item.useScopesText = this.getUseScopeText(item.useScopes)
      }
      this.setData(
        {
          myVoucherList:data,
          myVoucherTotal:data.length,
          disabled:[],
          disabledTotal:0
        }
      )
      return
    }
    for(var i = 0;i<data.length;i++){
      var item = data[i]
      item.useScopesText = this.getUseScopeText(item.useScopes)
      //是否过期
      if(new Date(item.expirationTime)<new Date().getTime()){
        item.disabledReson = '该券已过期'
        item.ifExpiration = true
        disabled.push(item)
      }
      //是否在使用范围内
      else if(item.useScopes.indexOf(Number(this.data.useScopes))== -1){
        item.disabledReson = '仅限' + item.useScopesText + '可使用'
        disabled.push(item)
      }
      //是否在门槛之内
      else if(item.threshold > this.data.totalPrice){
        item.disabledReson = '未达到使用门槛'
        disabled.push(item)
      }
      //可以使用
      else{
        usable.push(item)
      }
    }
    this.setData(
      {
        myVoucherList:usable,
        myVoucherTotal:usable.length,
        disabled:disabled,
        disabledTotal:disabled.length
      }
    )
  },
  //显示使用范围
  showUseScopes(e){
    var {usescopes} = e.currentTarget.dataset
    var useScopesText = this.getUseScopeText(usescopes)
    wx.showModal({
      title: '使用范围',
      content: useScopesText,
      showCancel:false,
      confirmText:'我知道了',
      complete: (res) => {
        if (res.confirm) {
          
        }
      }
    })
  },
  //获取可使用范围的文本信息
  getUseScopeText(useScopes){
    if(!useScopes || useScopes.length == 0){
      return ''
    }
    var obj = {
      '-1':'开通会员',
      '0':'购买券',
      '1':'专利解读',
      '2':'维权工单',
      '3':'申诉工单',
      '4':'申请工单',
    }
    var data = []
    useScopes.forEach(item => {
      var str = obj[item]
      if(str){
        data.push(str)
      }
    });
    return data.join('、')
  },
  //修改选择需要使用的优惠券
  changeChooseVoucher(e){
    var data = e.detail
    var arr = this.data.myVoucherList.filter(item=>{
      return data.indexOf(item.id+'')!=-1
    })
    var discount = 0
    arr.forEach(item=>{
      if(item.type == 1){
        // discount = Number(this.data.totalPrice) * (1 - Number(item.amount))
        var num = Decimal.sub([1,item.amount])
        discount = Decimal.mul([this.data.totalPrice,num])
      }else{
        // discount += Number(item.amount)
        discount = Decimal.add([discount,item.amount])
      }
      
    })
    this.setData({
      chooseVoucher: data,
      discount:discount
    });
  },
  //确认选择
  submit(){
    const eventChannel = this.getOpenerEventChannel()
    eventChannel.emit('acceptDataFromVoucher', {chooseVoucher: this.data.chooseVoucher,discountPrice:this.data.discount});
    wx.navigateBack()
  },
  //修改选择需要购买的优惠券
  changeBuyVoucher(e){
    var data = e.detail
    // var arr = this.data.voucherList.filter(item=>{
    //   return data.indexOf(item.id+'')!=-1
    // })
    // var payMoney = 0
    // arr.forEach(item=>{
    //   if(item.buyNumber){
    //     var money1 = Decimal.mul([item.sellingPrice,item.buyNumber])
    //     payMoney = Decimal.add([payMoney,money1])
    //     // payMoney += Number(item.sellingPrice) * Number(item.buyNumber)
    //   }else{
    //     // payMoney += Number(item.sellingPrice)
    //     payMoney = Decimal.add([payMoney,item.sellingPrice])
    //   }
      
    // })
    this.setData({
      buyVoucher: data,
      // payMoney:payMoney
    });
    this.getOrderDetail()
  },
  //修改数量
  changeNumber(e){
    var {index} = e.currentTarget.dataset
    var value = e.detail
    // var item = this.data.voucherList[index]
    // if(this.data.buyVoucher.indexOf(item.id+'')!=-1){
    //   var payMoney = this.data.payMoney
    //   if(item.buyNumber){
    //     if(item.buyNumber < value){
    //       // payMoney  =Number(payMoney) + Number(item.sellingPrice)
    //       payMoney = Decimal.add([payMoney,item.sellingPrice])
    //     }else if(item.buyNumber > value){
    //       // payMoney  =Number(payMoney) - Number(item.sellingPrice)
    //       payMoney = Decimal.sub([payMoney,item.sellingPrice])
    //     }
    //   }else{
    //     // payMoney = Number(payMoney) + Number(item.sellingPrice)
    //     payMoney = Decimal.add([payMoney,item.sellingPrice])
    //   }
    //   this.setData(
    //     {
    //       payMoney:payMoney
    //     }
    //   )
    // }
    this.setData(
      {
        ["voucherList["+index+"].buyNumber"]:value
      }
    )
    this.getOrderDetail()
  },
  //获取订单详情
  getOrderDetail(){
    var goods = []
    this.data.voucherList.forEach(item=>{
      if(this.data.buyVoucher.indexOf(item.id+'')!=-1){
        var obj = {
          id:item.id,
          name:item.name,
          price:item.sellingPrice,
          num:item.buyNumber || 1
        }
        goods.push(obj)
      }
    })
    var params ={
      title:'购买券',
      goodType:'0',
      goods:goods,
      personVoucherIds:[],
      activityId:this.data.other.activityId
    }
    api.getOrderDetail(params).then(res=>{
      if(res.code == 200){
        this.setData(
          {
            ["other.orderMessage"]:res.data.orderMessage,
            ["other.Activities"]:res.data.Activities,
            ["other.activityId"]:res.data.Activities.id,
            payMoney:res.data.orderMessage.finalPrice,
            ["other.discount"]:res.data.orderMessage.discount,
            ["other.price"]:res.data.orderMessage.price,
            // ["other.discountPrice"]:Decimal.sub([res.data.orderMessage.price,res.data.orderMessage.finalPrice]),
          }
        )
      }
    })
  },
  //支付
  pay(){
    if(!this.data.buyVoucher || this.data.buyVoucher.length == 0){
      api.notify(
        {
          type:'warning',
          message:'请先选择需要购买的券',
          // top:wx.getStorageSync('height')
        }
      )
      return
    }
    var goods = []
    this.data.voucherList.forEach(item=>{
      if(this.data.buyVoucher.indexOf(item.id+'')!=-1){
        var obj = {
          id:item.id,
          name:item.name,
          price:item.sellingPrice,
          num:item.buyNumber || 1
        }
        goods.push(obj)
      }
    })
    var data ={
      title:'购买券',
      type:'0',
      goods:goods,
      servicePrice:0.00,
      price:this.data.payMoney,
      discount:this.data.other.discount,
      activityId:this.data.other.activityId
    }
    pay.openPay(data)
  },
  //成功支付
  successPay(e){
    this.queryPersonVoucher()
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

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

  },

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

  },

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

  },

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

  }
})