import {
  get,
  post
} from '../../utils/http'
import {
  PROJECT_TYPE
} from '../../utils/global'
var WxParse = require('../../components/local/wxParse/wxParse.js')
Page({
  /**
   * 页面的初始数据
   */
  data: {
    visible: false,
    visibleLandscape: false,
    detail: null,
    productDetail: null, // 项目耗材下单 - 产品信息
    projectOrderData: null, // 项目耗材下单 - 绑定的订单信息
    couponList: [],
    currentCoupon: -1,
    currentChangeCoupon: null,
    memberDiscountStatus: -1, // 是否可使用会员折扣  0 不是会员  1 是会员
    memberStatus: -1, // 是否为会员  0 不是会员  1 是会员
    recommendMemberCard: null, // 推荐开通的会员卡
    array: ['使用', '不使用'],
    memberCardCurrentDiscount: -1, // 是否可以使用会员抵扣，0使用，1不使用，-1不可选择
    source: 'project', // project, product, goods
    projectProducts: [], // 指定项目的耗材推荐产品（升级产品）
    selectProductId: 0, // 选择的项目耗材id
    selectProductIndex: -1, // 选择的项目耗材下标
    selectCardId: 0, // 选择的会员卡ID
    moneyData: {}, // 金额数据
    orderId: 0,
    wxParseMemberRules: false, // 是否已解析
    pay_methon: 1,
    payNow: false,
    switchPay: 'product',
    inFirstIn: false,
    card_sum: 0, //次卡分配总数量
    cardDetail: [], //固定次卡分配信息列表
    Ac_cardDetail: [], //非固定次卡分配信息列表
    card_type: null, //是否可以分配次数
    finshCardDetail: {}, //分配完成的产品列表
    all_cardDetail: [], //获取分配全部信息
    selectExchange: 0, //是否选中加购产品
    exchangePrice: '', //选中后的价格
    cardExchangeList: '', //加购产品列表
    cardExchangeId: '', //加购产品id
    toExchangePrice:'', //加购产品总价格
    level: '', //用户充值折扣等级 (0是未拥有等级)
    levelList: {
      1: '0.98',
      4: '0.95',
      7: '0.90',
    }, //折扣列表
    levelPrice: '', //充值等级折扣优惠价格
  },

  knowSubmit: function () {
    this.setData({
      inFirstIn: false
    })
  },

  noneEnoughPeople() {

  },

  pay_methonw() {
    this.setData({
      pay_methon: 1
    })
  },
  // 获取用户充值折扣等级
  getLevel() {
    get('/v2/api/user/discount_level', {}, (res) => {
      if (res.code == 200) {
        if (res.data == 0) {
          this.setData({
            level: 0
          })
          return
        }
        let getValue = (item, val) => {
          return item[val]
        }
        this.setData({
          level: Number(getValue(this.data.levelList, res.data))
        })
        this.setData({
          tolevel: (this.data.level * 10).toFixed(1)
        })
      }
    })
  },
  pay_methonc() {
    this.setData({
      pay_methon: 2
    })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 获取用户折扣等级
    this.getLevel()
    // console.log(options, 'options');
    this.getCardExchangeList(options.storeId, JSON.parse(options.data).id)
    let source = options.source || 'project'
    let productData = options.productData || null
    if (productData) {
      productData = JSON.parse(productData)
    }
    let userInfo = getApp().globalData.userInfo
    this.setData({
      exchangePrice: JSON.parse(options.data).price,
      detail: JSON.parse(options.data),
      productDetail: productData,
      timeData: JSON.parse(options.timeData),
      deviceData: JSON.parse(options.deviceData),
      selectProductId: productData && productData.id ? productData.id : 0, // 复用了项目下单的耗材推荐产品
      projectOrderData: options.projectOrderData ?
        JSON.parse(options.projectOrderData) : null,
      source: source,
      memberStatus: userInfo.is_vip || 0,
      storeId: options.storeId
    })
    // 产品类型 数据类型，1项目，2项目耗材，3美妆产品，4卡券产品分类， 默认1
    if (source == 'project') {
      // 项目
      this.getDiscount()
    } else if (source == 'product') {
      // 项目耗材
      this.getDiscount()
    } else if (['goods'].indexOf(source) > -1) {
      // 美妆产品
      this.getGoodsDiscount()
    } else if (source == 'cardgoods') {
      // 卡券产品
      this.getCardgoodsDiscount()
    } else if (source == 'product_with_project_order') {
      // 项目-升级产品(项目耗材)
      this.getProductWithProjectOrderDiscount()
    } else if (source == 'secondaryCard') {
      // 次卡
      // 发起请求获取次卡分配产品
      this.getCardProjectInfo()
    } else {
      // 默认为项目
      this.getDiscount()
    }
  },

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

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getAmount()
    let version4 = wx.getStorageSync('version4')
    if (!version4 || version4 != 1) {
      this.setData({
        inFirstIn: true
      })
      wx.setStorageSync('version4', 1)
    }
  },

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

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

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

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

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

  /**
   * 复制订单号
   */
  onCopyOrderNum(e) {
    wx.setClipboardData({
      data: e.currentTarget.dataset.num || '',
      success(res) {
        console.log(res)
      }
    })
  },

  /**
   * 打开优惠券
   */
  onCouponOpen() {
    if (
      this.data.couponList.length > 0 &&
      this.data.memberCardCurrentDiscount != 0
    ) {
      this.setData({
        visible: true
      })
    }
  },

  /**
   * 选择优惠券
   */
  onCouponChange(e) {
    let couponIndex = e.detail.checkStatus ? e.currentTarget.dataset.index : -1
    // 优惠券和会员卡互斥逻辑
    this.setData({
        currentCoupon: couponIndex,
        currentChangeCoupon: couponIndex == -1 ? null : this.data.couponList[couponIndex],
        memberCardCurrentDiscount: couponIndex != -1 ? -1 : this.data.memberCardCurrentDiscount // 会员卡与优惠券互斥逻辑
      },
      () => {
        this.calculateOrderPayMoney()
      }
    )
  },

  /**
   * 关闭弹框
   */
  onClose() {
    this.setData({
      visible: false
    })
  },

  onCancelCoupon() {
    this.setData({
      visible: false
    })
  },
  onConfirmCoupon() {
    let currentChangeCoupon = this.data.couponList[this.data.currentCoupon]
    this.setData({
        visible: false,
        currentChangeCoupon
      },
      () => {
        this.calculateOrderPayMoney()
      }
    )
  },

  /**
   * 订单支付
   */
  payOrder(orderId) {
    let that = this
    let uri = 'api/pay/project'
    if (that.data.source == 'goods') {
      uri = 'api/pay/goods'
    } else if (that.data.source == 'cardgoods') {
      uri = 'api/pay/cardgoods'
    } else if (that.data.source == 'secondaryCard') {
      uri = 'v2/api/order/card/pay'
    }
    post(
      uri, {
        pay_way: this.data.pay_methon == 1 ? 'weixin' : 'amount',
        order_id: orderId
      },
      (res) => {
        that.setData({
          payNow: false
        })

        if (that.data.pay_methon == 2) {
          that.goToOrder('支付成功')
          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') {
              that.goToOrder('支付成功')
            }
          },
          fail(res) {
            that.goToOrder('支付失败')
          }
        })
      }
    )
  },

  /**
   * 订单支付 - 升级产品支付
   */
  payProductOrder(orderId) {
    let that = this
    post(
      'api/pay/product', {
        pay_way: this.data.pay_methon == 1 ? 'weixin' : 'amount',
        order_id: orderId
      },
      (res) => {

        that.setData({
          payNow: false
        })

        if (that.data.pay_methon == 2) {
          that.goToOrder('支付成功')
          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') {
              that.goToOrder('支付成功')
            }
          },
          fail(res) {
            that.goToOrder('支付失败')
          }
        })
      }
    )
  },

  onPay: function () {
    this.setData({
      payNow: true,
      switchPay: 'project',
    })
  },

  payNow() {
    switch (this.data.switchPay) {
      case 'project':
        this.payNowProduct()
        break;
      case 'product':
        this.onProductPayNow()
        break;
      case 'goods':
        this.onGoodsPayNow()
        break
      case 'cardgoods':
        this.onCardgoodsPayNow()
        break
      case 'secondaryCard':
        this.onSecondaryCardPayNow()
        break
      default:
        break;
    }
  },

  /**
   * 支付
   */
  payNowProduct() {
    let that = this
    this.checkFirst()
      .then((res) => {
        this.addOrder().then((res) => {
          console.log(res)
          that.setData({
            orderId: res.order_id
          }, () => {
            that.methonPayOrder(res.order_id)
          })
        })
      })
      .catch((rej) => {
        that.setData({
          payNow: false
        })
        wx.navigateTo({
          url: '/pages/disclaimer/disclaimer'
        })
      })
  },

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

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

        that.setData({
          payNow: false
        })

        if (that.data.pay_methon == 2) {
          that.goToOrder('支付成功')
          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') {
              that.goToOrder('支付成功')
            }
          },
          fail(res) {
            that.goToOrder('支付失败')
          }
        })
      }
    )
  },

  onGoodsPay() {
    this.setData({
      payNow: true,
      switchPay: 'goods'
    })
  },

  /**
   * 美妆产品-订单
   */
  onGoodsPayNow() {
    let {
      detail,
      currentChangeCoupon,
      memberCardCurrentDiscount,
      selectCardId
    } = this.data
    let discount_type
    let that = this
    if (memberCardCurrentDiscount == 0) {
      discount_type = 1
    } else if (currentChangeCoupon) {
      discount_type = 2
    } else {
      discount_type = 0
    }
    post(
      'api/goods/buy', {
        goods_id: detail.id,
        coupon_id: currentChangeCoupon ? currentChangeCoupon.id : '',
        store_id: detail.store_id,
        card_id: selectCardId,
        discount_type
      },
      (res) => {
        let orderId = res.data.order_id
        let payStatus = res.data.pay_status //订单状态，1已支付，0未支付，需要调用支付接口
        this.setData({
          orderId: orderId
        }, () => {
          if (payStatus == 1) {
            that.goToOrder('支付成功')
            return
          }
          that.payOrder(orderId)
        })
      }
    )
  },

  onCardgoodsPay() {
    this.setData({
      payNow: true,
      switchPay: 'cardgoods'
    })
  },

  /**
   * 购买-卡券产品【下单】
   */
  onCardgoodsPayNow() {
    let {
      detail,
      currentChangeCoupon,
      memberCardCurrentDiscount,
      selectCardId
    } = this.data
    let discount_type
    let that = this
    if (memberCardCurrentDiscount == 0) {
      discount_type = 1
    } else if (currentChangeCoupon) {
      discount_type = 2
    } else {
      discount_type = 0
    }
    post(
      'api/cardgoods/buy', {
        goods_id: detail.id,
        coupon_id: currentChangeCoupon ? currentChangeCoupon.id : '',
        store_id: detail.store_id,
        card_id: selectCardId,
        discount_type
      },
      (res) => {
        let orderId = res.data.order_id
        let payStatus = res.data.pay_status //订单状态，1已支付，0未支付，需要调用支付接口
        this.setData({
          orderId: orderId
        }, () => {
          if (payStatus == 1) {
            that.goToOrder('支付成功')
            return
          }
          that.payOrder(orderId)
        })
      }
    )
  },

  onSecondaryCardPay() {
    // 计算充值折扣
    this.setData({
      levelPrice: (this.data.detail.price * this.data.level+Number(this.data.toExchangePrice)).toFixed(2)
    })
    this.setData({
      toLevelPrice: (this.data.detail.price - this.data.levelPrice+Number(this.data.toExchangePrice)).toFixed(2)
    })
    // 判断是否有次卡分配
    if (this.data.card_type == 2) {
      // 判断分配次数是否分配完毕
      let num = 0
      this.data.Ac_cardDetail.map(item => {
        num += item.total_time
      })
      this.setData({
        card_sum: num
      })
      // 如果没有分配完毕就提示
      if (this.data.card_sum != 0) {
        wx.showToast({
          title: '您还有剩余次数',
          icon: 'error'
        })
        return
      }
      // 筛选分配后的数据
      let group = []
      this.data.Ac_cardDetail.map(item => {
        let vote = {}
        vote.id = item.id
        let project_list = []
        vote.project_list = project_list
        item.project_list.map(item1 => {
          let vote1 = {}
          if (item1.time != 0) {
            vote1.project_id = item1.project_id
            vote1.time = item1.time
            project_list.push(vote1)
          }
        })
        group.push(vote)
      })
      this.setData({
        finshCardDetail: group
      })
    }
    this.setData({
      payNow: true,
      switchPay: 'secondaryCard'
    })
  },

  /**
   * 次卡下单
   */
  onSecondaryCardPayNow() {
    console.log({
      group: '',
      id: this.data.all_cardDetail.id,
      store_id: this.data.all_cardDetail.store_id,
      group_type: this.data.card_type,
      plus_id: this.data.cardExchangeId
    });
    let {
      detail
    } = this.data
    let that = this
    post(
      // 判断是否有次卡分配
      'v2/api/order/card/add',
      this.data.card_type == 2 ? {
        group: this.data.finshCardDetail,
        store_id: this.data.all_cardDetail.store_id,
        id: this.data.all_cardDetail.id,
        group_type: this.data.card_type,
      } : {
        group: '',
        id: this.data.all_cardDetail.id,
        store_id: this.data.all_cardDetail.store_id,
        group_type: this.data.card_type,
        plus_id: this.data.cardExchangeId
      },
      (res) => {
        console.log(res);
        let orderId = res.data.order_id
        let payStatus = res.data.pay_status //订单状态，1已支付，0未支付，需要调用支付接口
        // 因为要订阅消息，不能在回调函数里调用该方法所以修改
        this.setData({
          orderId: orderId
        })
        if (payStatus == 1) {
          that.goToOrder('支付成功')
          return
        }
        that.payOrder(orderId)
        // this.setData({
        //   orderId: orderId
        // }, () => {
        //   if (payStatus == 1) {
        //     that.goToOrder('支付成功')
        //     return
        //   }
        //   that.payOrder(orderId)
        // })
      }
    )
  },

  /**
   * 确认订单
   */
  getOrderInfo(order_id) {
    get(
      'api/order/info', {
        order_id
      },
      (res) => {
        this.setData({
          detail: res.data
        })
        console.log(res)
      }
    )
  },

  /**
   * 获取预约订单折扣
   * api/order/get_discount
   */
  getDiscount() {
    let {
      memberCardCurrentDiscount,
      source
    } = this.data
    get(
      'api/order/get_discount', {
        project_id: this.data.detail.id,
        order_day: this.data.timeData.order_day,
        order_time_id: this.data.timeData.time_id
      },
      (res) => {
        // 是否可以使用会员抵扣，member_status:1 可以抵扣，0不能抵扣
        if (res.data.member_status == 1) {
          memberCardCurrentDiscount = 0 // 是否可以使用会员抵扣，0使用，1不使用，-1不可选择
        }
        this.setData({
            couponList: res.data.coupon_list, // type: 类型，1抵扣券，2满减券，3全额券
            memberDiscountStatus: res.data.member_status, // 是否可以使用会员抵扣，1可以抵扣，0不能抵扣
            recommendMemberCard: res.data.member_card, // 推荐开通的会员卡
            memberCardCurrentDiscount,
            currentPayMoney: this.data.detail.price
          },
          () => {
            this.calculateOrderPayMoney()
          }
        )
      }
    )
    // 项目确认订单 - 获取指定项目的升级产品
    if (source == 'project') {
      this.getProjectProducts()
    }
  },

  /**
   * 选择会员抵扣
   */
  bindPickerChange(e) {
    let {
      memberCardCurrentDiscount,
      currentCoupon,
      currentChangeCoupon
    } =
    this.data
    this.setData({
        memberCardCurrentDiscount: e.detail.value,
        currentCoupon: memberCardCurrentDiscount == 0 ? -1 : currentCoupon,
        currentChangeCoupon: memberCardCurrentDiscount == 0 ? null : currentChangeCoupon
      },
      () => {
        this.calculateOrderPayMoney()
      }
    )
  },


  onSubmitCh(ids, source) {
    let that = this
    wx.showModal({
      title: '提示',
      content: '支付成功! 是否进行消息提醒',
      success: function (res) {
        if (res.confirm) {
          that.onSubmitTrue(ids, source)
        } else if (res.cancel) {
          that.messageAgree(ids)
          setTimeout(() => {
            wx.reLaunch({
              // url: '/pages/order/order?current=1'
              url: `/pages/paySuccess/paySuccess?current=1&source=${source}&order_id=${that.data.orderId}`
            })
          }, 1000)
        }
      }
    });
  },

  onSubmitTrue(ids, source) {
    console.log("source")
    console.log(source)
    let that = this
    wx.requestSubscribeMessage({
      tmplIds: ids,
      success(res) {
        console.log(res)
        that.messageAgree(ids)
        wx.reLaunch({
          // url: '/pages/order/order?current=1'
          url: `/pages/paySuccess/paySuccess?current=1&source=${source}&order_id=${that.data.orderId}`
        })
      },
      fail(rej) {
        console.log(rej)
        that.messageAgree(ids)
        wx.showToast({
          title: JSON.stringify(rej),
          icon: 'error'
        })
        setTimeout(() => {
          wx.reLaunch({
            // url: '/pages/order/order?current=1'
            url: `/pages/paySuccess/paySuccess?current=1&source=${source}&order_id=${that.data.orderId}`
          })
        }, 1000)
      }
    })
  },

  /**
   * 获取我的储值
   * api/user
   */
  getAmount() {
    get('api/user/amount', {}, (res) => {
      if (res.data) {
        this.setData({
          inserllAmount: res.data.amount
        })
      }
    })
  },
  /**
   * 跳转订单列表
   */
  goToOrder(text) {
    let that = this
    let {
      source
    } = this.data
    // 此处按照接口定义，当选择项目耗材，且无项目时，下单用的是project
    if (source == 'product') {
      source = 'project'
    }
    wx.showToast({
      title: text,
      icon: text == '支付成功' ? 'success' : 'error'
    })
    if (text == '支付成功') {
      // 只有项目购买，需要订阅消息
      if (source != 'project') {
        wx.reLaunch({
          url: `/pages/paySuccess/paySuccess?current=1&source=${source}&order_id=${that.data.orderId}`
        })
        // 获取下发权限
        wx.requestSubscribeMessage({
          tmplIds: ['RNife3ZhTYYpUuT26ylGQj8W0v07IPo2TGe941iR3y8'],
          success(res) {
            console.log(res);
            let status = ''
            if (res['RNife3ZhTYYpUuT26ylGQj8W0v07IPo2TGe941iR3y8'] == 'reject') {
              status = 2
            } else {
              status = 1
            }
            get('/v2/api/activity/push', {
              type: 2,
              status,
            }, res => {})
          },
        })
        return
      }
      get('api/message/ids', {}, (res) => {
        let ids = res.data.ids
        if (that.data.pay_methon == 2) {
          that.onSubmitCh(ids, source)
          return
        }
        wx.requestSubscribeMessage({
          tmplIds: ids,
          success(res) {
            console.log(res)
            that.messageAgree(ids)
            wx.reLaunch({
              // url: '/pages/order/order?current=1'
              url: `/pages/paySuccess/paySuccess?current=1&source=${source}&order_id=${that.data.orderId}`
            })
          },
          fail(rej) {
            console.log(rej)
            that.messageAgree(ids)
            wx.showToast({
              title: JSON.stringify(rej),
              icon: 'error'
            })
            setTimeout(() => {
              wx.reLaunch({
                // url: '/pages/order/order?current=1'
                url: `/pages/paySuccess/paySuccess?current=1&source=${source}&order_id=${that.data.orderId}`
              })
            }, 1000)
          }
        })
      })
    } else {
      let failUrl = `/pages/order/order?current=0`
      if (['goods', 'cardgoods'].indexOf(source) > -1) {
        failUrl = `/pages/goods/orderList/orderList?current=0`
      }
      setTimeout(() => {
        wx.reLaunch({
          url: failUrl
          // url: `/pages/paySuccess/paySuccess?current=0&source=${source}&order_id=${that.data.orderId}`
        })
      }, 1000)
    }
  },

  /**
   * 是否首次购买
   */
  checkFirst() {
    return new Promise((resolve, reject) => {
      if (wx.getStorageSync('agree')) {
        resolve()
      } else {
        get('api/order/check_first', {}, (res) => {
          if (res.data.order_status == 1) {
            resolve()
          } else {
            reject()
          }
        })
      }
    })
  },

  /**
   * 提交订单
   * /api/order/add
   */
  addOrder() {
    let {
      deviceData,
      timeData,
      currentChangeCoupon,
      detail,
      memberCardCurrentDiscount,
      selectCardId,
      selectProductId
    } = this.data
    let discount_type
    let that = this
    return new Promise((resolve, reject) => {
      if (memberCardCurrentDiscount == 0) {
        discount_type = 1
      } else if (currentChangeCoupon) {
        discount_type = 2
      } else {
        discount_type = 0
      }
      post(
        'api/order/add', {
          project_id: detail.id,
          store_id: detail.store_id,
          device_id: deviceData ? deviceData.id : '',
          order_day: timeData ? timeData.order_day : '',
          order_time_id: timeData ? timeData.time_id : '',
          coupon_id: currentChangeCoupon ? currentChangeCoupon.id : '',
          discount_type,
          card_id: selectCardId,
          product_id: selectProductId,
          product_coupon_id: currentChangeCoupon ? currentChangeCoupon.id : ''
        },
        (res) => {
          console.log(res)
          that.setData({
            orderId: res.data.order_id
          })
          if (res.data.pay_status == 1) {
            that.goToOrder('支付成功')
          } else {
            resolve(res.data)
          }
        }
      )
    })
  },


  // 统一集合的地方
  onProductPay() {
    this.setData({
      payNow: true,
      switchPay: 'product',
    })
  },


  /**
   * 单独购买升级产品【下单】
   * /api/product/buy
   * 
   */
  onProductPayNow() {
    let {
      selectProductId,
      projectOrderData,
      memberCardCurrentDiscount,
      currentChangeCoupon
    } = this.data
    let discount_type
    let that = this
    if (memberCardCurrentDiscount == 0) {
      discount_type = 1
    } else if (currentChangeCoupon) {
      discount_type = 2
    } else {
      discount_type = 0
    }
    this.checkFirst()
      .then(() => {
        new Promise((resolve, reject) => {
          post(
            'api/product/buy', {
              product_id: selectProductId,
              order_id: projectOrderData.order_id,
              coupon_id: currentChangeCoupon ? currentChangeCoupon.id : '',
              discount_type
            },
            (res) => {
              console.log(res)
              that.setData({
                orderId: res.data.order_id
              })
              if (res.data.pay_status == 1) {
                that.goToOrder('支付成功')
              } else {
                that.payProductOrder(res.data.order_id)
              }
            }
          )
        })
      })
      .catch((rej) => {
        wx.navigateTo({
          url: '/pages/disclaimer/disclaimer'
        })
      })
  },

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


  /**
   * 点击打开会员卡弹框
   */
  onOpenLandscape() {
    let that = this
    if (that.data.wxParseMemberRules) {
      that.setData({
        visibleLandscape: true
      })
      return
    }
    this.getmemberRules()
      .then((memberRules) => {
        WxParse.wxParse('article', 'html', memberRules, that, 5)
        that.setData({
          visibleLandscape: true,
          wxParseMemberRules: true
        })
      })
      .catch(() => {})
  },

  /**
   * 点击关闭会员卡弹框
   */
  onCloseLandscape() {
    this.setData({
      visibleLandscape: false
    })
  },

  /**
   * 勾选会员卡
   */
  selectMemberCard(e) {
    let that = this
    this.setData({
        selectCardId: that.data.selectCardId ? 0 : e.currentTarget.dataset.id,
        memberCardCurrentDiscount: that.data.selectCardId ? -1 : 0,
        memberStatus: that.data.selectCardId ? -1 : 1,
        currentCoupon: that.data.selectCardId ? -1 : that.data.currentCoupon,
        currentChangeCoupon: that.data.selectCardId ?
          null : that.data.currentChangeCoupon
      },
      () => {
        that.calculateOrderPayMoney()
      }
    )
  },

  /**
   * 勾选升级产品
   */
  selectProjectProduct(e) {
    let {
      selectProductIndex
    } = this.data
    let productId = e.currentTarget.dataset.id
    let index = e.currentTarget.dataset.index
    this.setData({
        selectProductId: selectProductIndex == index ? 0 : productId,
        selectProductIndex: selectProductIndex == index ? -1 : index
      },
      () => {
        this.calculateOrderPayMoney()
      }
    )
  },

  /**
   * 获取指定项目的升级产品
   */
  getProjectProducts() {
    get('api/project/products', {
      project_id: this.data.detail.id
    }, (res) => {
      this.setData({
        projectProducts: res.data.list && res.data.list.length > 0 ? res.data.list : []
      })
    })
  },

  /**
   * 获取-美妆产品折扣
   */
  getGoodsDiscount() {
    let memberCardCurrentDiscount = this.data.memberCardCurrentDiscount
    get(
      'api/goods/get_discount', {
        goods_id: this.data.detail.id
      },
      (res) => {
        this.setData({
            couponList: res.data.coupon_list, // type: 类型，1抵扣券，2满减券，3全额券
            memberCardCurrentDiscount,
            currentPayMoney: this.data.detail.price
          },
          () => {
            this.calculateOrderPayMoney()
          }
        )
      }
    )
  },

  /**
   * 获取-卡券产品折扣
   */
  getCardgoodsDiscount() {
    let memberCardCurrentDiscount = this.data.memberCardCurrentDiscount
    get(
      'api/cardgoods/get_discount', {
        goods_id: this.data.detail.id
      },
      (res) => {
        this.setData({
            couponList: res.data.coupon_list, // type: 类型，1抵扣券，2满减券，3全额券，4卡券（效果和“全额券”一样）
            memberCardCurrentDiscount,
            currentPayMoney: this.data.detail.price
          },
          () => {
            this.calculateOrderPayMoney()
          }
        )
      }
    )
  },

  /**
   * 获取-项目升级产品的折扣信息
   */
  getProductWithProjectOrderDiscount() {
    let {
      selectProductId
    } = this.data
    get(
      'api/product/get_discount', {
        product_id: selectProductId
      },
      (res) => {
        this.setData({
            couponList: res.data.coupon_list // type: 类型，1抵扣券，2满减券，3全额券，4卡券（效果和“全额券”一样）
          },
          () => {
            this.calculateOrderPayMoney()
          }
        )
      }
    )
  },

  /**
   * 获取会员守则
   */
  getmemberRules() {
    let memberRules = getApp().globalData.memberRules
    return new Promise((resolve, reject) => {
      if (memberRules) {
        resolve(memberRules)
      } else {
        get(
          'api/agreement', {},
          (res) => {
            memberRules = res.data.member_rules
            memberRules = this.removeCss(memberRules)
            getApp().globalData.memberRules = memberRules
            resolve(memberRules)
          },
          () => {
            reject()
          }
        )
      }
    })
  },

  /**
   * 去除富文本图片默认样式
   */
  removeCss(content) {
    let reg = /(style|class)="[^"]+"/gi
    let img = /<img[^>]+>/gi
    let res
    if (img.test(content)) {
      res = content.match(img)
      for (let i = 0; i < res.length; i++) {
        content = content.replace(res[i], res[i].replace(reg, ''))
      }
    }
    // (/\<img/gi, '<img style="max-width:100%;height:auto;display:block;"')
    return content.replace(/\<img/gi, '<img class="richImg"  ')
  },

  /**
   *  计算汇总价格
   * memberCardCurrentDiscount 为1时会员卡可抵扣全额抵扣(项目)
   * 会员
   *  项目可以全额抵扣
   *  美妆产品、项目耗材 会员价
   *
   * @param detail 项目（美妆产品共用）
   * @param recommendMemberCard 推荐开通的会员卡
   * @param memberCardCurrentDiscount 是否可以使用会员抵扣，0使用，1不使用，-1不可选择
   * @param selectCardId  选中需要购买的会员卡ID
   * @param currentChangeCoupon 优惠券对象
   * @param productDetail 项目耗材下单时的耗材详情
   * @param projectProducts 项目下单推荐的项目耗材
   * @returns
   */
  calculateOrderPayMoney() {
    let {
      detail,
      selectCardId,
      source,
      memberStatus,
      recommendMemberCard,
      productDetail,
      memberCardCurrentDiscount,
      currentCoupon,
      currentChangeCoupon,
      projectProducts,
      selectProductIndex
    } = this.data
    let projectWithGoodsPrice = 0 // 项目价格 / 美妆产品价格 （项目是会员抵扣，美妆产品是会员价）
    let payMoney = 0 // 需要支付的价格
    let productPrice = 0 // 项目耗材价格
    let memberCardPrice = 0 // 会员卡卡费
    let couponMoney = 0 // 优惠券金额
    let memberDiscountMoney = 0 // 会员折扣金额（项目）
    let projectProductMoney = 0 // 项目下单推荐的项目耗材
    // 处理优惠券、会员卡折扣互斥逻辑（优先会员卡）
    if (memberCardCurrentDiscount == 0) {
      // 使用了会员卡折扣
      currentChangeCoupon = null
      currentCoupon = -1
      this.setData({
        currentCoupon,
        currentChangeCoupon
      })
    }
    if (currentCoupon != -1) {
      // 使用了优惠券
      memberCardCurrentDiscount = -1
      this.setData({
        memberCardCurrentDiscount
      })
    }
    // 项目耗材下单
    if (productDetail) {
      productPrice = parseFloat(productDetail.price ? productDetail.price : 0.0)
      if (productDetail.is_member) {
        productPrice = parseFloat(
          productDetail.member_price ? productDetail.member_price : 0.0
        )
      }
    }
    // 项目价格(美妆产品价格)
    projectWithGoodsPrice = detail.price ? parseFloat(detail.price) : 0
    // 已是会员 项目是会员抵扣，美妆产品是会员价
    if (memberStatus == 1 || detail.is_member == 1) {
      // 美妆产品，享受会员价
      projectWithGoodsPrice = detail.member_price ?
        parseFloat(detail.member_price) :
        0 // 项目价格(美妆产品价格)
      // 项目下单（project） + 耗材下单且购买一个项目（product） 显示原价，是否能用会员抵扣，交给用户选择
      if (source == 'project' || source == 'product') {
        projectWithGoodsPrice = detail.price ? parseFloat(detail.price) : 0
      }
    }
    // 如果是单独购买项目耗材，不要计算项目的金额
    if (source == 'product_with_project_order') {
      projectWithGoodsPrice = 0
    }
    // 项目下单时勾选了推荐的耗材
    if (selectProductIndex != -1) {
      let selectProductItem = projectProducts[selectProductIndex]
      projectProductMoney = selectProductItem ?
        memberStatus ?
        parseFloat(selectProductItem.member_price) :
        parseFloat(selectProductItem.price) :
        0
    }
    // 勾选了购买会员卡，计算会员卡费
    if (selectCardId) {
      memberCardPrice = recommendMemberCard.price ?
        parseFloat(recommendMemberCard.price) :
        0
    }
    // 是否可以使用会员抵扣，0使用，1不使用，-1不可选择
    if (memberCardCurrentDiscount == 0) {
      memberDiscountMoney = projectWithGoodsPrice
    }
    // 选择了优惠券
    if (currentChangeCoupon) {
      // 类型，1抵扣券，2满减券，3全额券，4卡券（效果和“全额券”一样）
      let couponType = currentChangeCoupon.type
      couponMoney = projectWithGoodsPrice // 全额抵扣券 、 卡券
      if (couponType == 1) {
        couponMoney = currentChangeCoupon.price ?
          parseFloat(currentChangeCoupon.price) :
          0
      } else if (couponType == 2) {
        couponMoney =
          currentChangeCoupon.full_price &&
          projectWithGoodsPrice >= parseFloat(currentChangeCoupon.full_price) ?
          parseFloat(currentChangeCoupon.price) :
          0
      }
    }
    // 要支付的金额 = 项目(美妆产品)价格 - 优惠券金额 - 会员卡优惠金额
    payMoney = projectWithGoodsPrice - couponMoney - memberDiscountMoney
    payMoney = payMoney > 0 ? payMoney : 0
    // 项目耗材价格(项目耗材单独下单)
    payMoney = payMoney + productPrice
    payMoney = payMoney > 0 ? payMoney : 0
    // 项目耗材价格（项目下单时勾选了推荐的耗材产品）
    payMoney = payMoney + projectProductMoney
    // 会员卡卡费 （卡费不参与折扣）
    payMoney = payMoney + memberCardPrice
    payMoney = payMoney > 0 ? payMoney : 0
    this.setData({
      moneyData: {
        payMoney: String(payMoney.toFixed(2)), // 需要支付的价格
        projectWithGoodsPrice: String(projectWithGoodsPrice.toFixed(2)), // 项目价格 / 美妆产品价格
        productPrice: String(productPrice.toFixed(2)), // 项目耗材价格
        memberCardPrice: String(memberCardPrice.toFixed(2)), // 会员卡卡费
        couponMoney: String(couponMoney.toFixed(2)), // 优惠券抵扣金额
        memberDiscountMoney: String(memberDiscountMoney.toFixed(2)), // 会员折扣金额（项目）
        projectProductMoney: String(projectProductMoney.toFixed(2)) // 项目下单推荐的项目耗材
      }
    })
    return payMoney
  },
  // 次卡详情点击减少
  onReduce(e) {
    let index = e.currentTarget.dataset.index
    // 根据id获取数组下标
    let indexId = e.currentTarget.dataset.id
    let num = this.data.Ac_cardDetail[indexId].project_list[index].time
    num = num - 1
    if (num < 0) {
      num = 0
      return
    }
    let dataNum = `Ac_cardDetail[${indexId}].project_list[${index}].time`
    let total = this.data.Ac_cardDetail[indexId].total_time
    total = total + 1
    let total_time = `Ac_cardDetail[${indexId}].total_time`
    this.setData({
      [dataNum]: num,
      [total_time]: total
    })
  },
  // 次卡详情点击添加
  onLationAdd(e) {
    let index = e.currentTarget.dataset.index
    // 根据id获取数组下标
    let indexId = e.currentTarget.dataset.id
    if (this.data.Ac_cardDetail[indexId].total_time == 0) {
      return
    }
    let num = this.data.Ac_cardDetail[indexId].project_list[index].time
    num = num + 1
    let dataNum = `Ac_cardDetail[${indexId}].project_list[${index}].time`
    let total = this.data.Ac_cardDetail[indexId].total_time
    total = total - 1
    let total_time = `Ac_cardDetail[${indexId}].total_time`
    this.setData({
      [dataNum]: num
    })
    this.setData({
      [total_time]: total
    })
  },
  //次卡分配产品详情获取
  getCardProjectInfo() {
    get('v2/api/card/project_list', {
        id: this.data.detail.id,
        store_id: this.data.storeId
      },
      (res) => {
        console.log(res, 'product');
        // 计算总分配次数（用来判断是否判断完毕）
        let a = 0
        // 给每一个可分配数组添加一个标识（便于产品数量加减）
        res.data.group.map(item => {
          item.Idindex = a++
        })
        this.setData({
          cardDetail: res.data.projects,
          card_type: res.data.type,
          Ac_cardDetail: res.data.group,
          all_cardDetail: res.data
        })
      }
    )
  },
  // 选中加购产品
  selectExchange(e) {
    let index = e.currentTarget.dataset.index
    let sum = Number(this.data.cardExchangeList[index].price) + Number(this.data.detail.price)
    let id = this.data.cardExchangeList[index].id
    this.setData({
      selectExchange: this.data.selectExchange == 0 ? 1 : 0
    })
    if(this.data.selectExchange==1){
      this.setData({
        toExchangePrice:this.data.cardExchangeList[index].price
      })
    }else{
      this.setData({
        toExchangePrice:0
      })
    }
    this.setData({
      exchangePrice: String(sum.toFixed(2)),
      cardExchangeId: id
    })
  },
  // 获取次卡可换购列表
  getCardExchangeList(storeId, id) {
    get('/v2/api/card/plus', {
      store_id: storeId,
      card_id: id
    }, (res) => {
      if (res.code == 200) {
        this.setData({
          cardExchangeList: res.data.list
        })
      }
    })
  }
})