// pages/goodsOrderConfirm/goodsOrderConfirm.js
import {
  get,
  post
} from '../../utils/http'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    selectMakeupList: [], //商品列表
    couponList: [], //优惠券列表
    selectCouponList: [], //选中的优惠券
    showMoneyGood: 0, //原价
    selectCouponPrice: 0, //券后价格
    couponPrice: 0, //总优惠券金额
    inserllAmount: 0,
    pay_methon: 1,
    store_name: "",
    storeId: wx.getStorageSync('store_id'),
    page: 1,
    limit: 20,
    visible: false,
    payNow: false,
    currentCoupon: -1,
    coupon_id: '',
    orderId: '',
    projectData: null, // 跳转商品数据
    productId: null, // 产品id
    isShow: null, // 产品详情订单标识
    source: '', // 产品类型
    isDirectOrder: false, //直接下单
    listNum: 0, //订单产品总数
    discountList: [], //折扣列表
    discountSet: 0, //折扣扣除金额
    discount_total: 0, //折扣后总金额
    discount_id: '', //折扣id
    goods_ids: [], //商品id
    type: '', //直接购买还是购物车跳转
    CardDiscount: '', //次卡购买获取美妆折扣
    activity_list: [], //活动折扣列表
    activity_discount: '', //活动折扣优惠后的金额
    activity_level: false, //是否有活动折扣
    activity_select_money: '', //活动折扣优惠的金额
    exchangeList: [], //加购产品列表
    exchangePrice: '', //选中加购产品后的价格
    exchangeSelect: false, //是否选中加购产品
    exchangeInfo: '', //需要加购多少商品的价格信息
    toExchangePrice: '', //选中加购产品的总价格
    level: '', //用户充值折扣等级 (0是未拥有等级)
    levelList: {
      1: '0.98',
      4: '0.95',
      7: '0.90',
    }, //折扣列表
    levelPrice: '', //充值等级折扣优惠价格
    toLevelPrice: '', //充值折扣扣除金额
    notSalePrice: 0, //不是秒杀产品的总价
    salePrice: 0, //秒杀产品总价
    meet_discount: 0 //满足什么折扣 0无折扣 1品牌 2充值余额折扣
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 获取跳转过来商品的id
    this.setData({
      goods_ids: options.goods_ids,
      type: options.type
    })
    let isDirectOrder = false
    if (options.isDirectOrder) {
      isDirectOrder = true
    }
    this.setData({
      productId: options.productId,
      isShow: options.isShow,
      source: options.source,
      isDirectOrder: isDirectOrder,
    })
    if (this.data.isShow) {
      this.getProductInfo()
    } else {
      return
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    if (this.data.isDirectOrder) {
      this.onConfirm()
    } else {
      this.needAddGood()
    }
    this.getCoupon()
    if (this.data.isDirectOrder) {
      this.getActivityDiscount()
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 获取加购列表
    this.getExchangeInfo()
    this.setData({
      storeId: wx.getStorageSync('store_id'),
    })
  },
  // 计算品牌折扣 和 充值折扣中的最优折扣
  calculateDiscount() {
    // 如果充值等级为0折扣金额也为0
    if (this.data.level == 0) {
      this.setData({
        toLevelPrice: 0
      })
    }
    console.log(this.data.discountSet, this.data.toLevelPrice, 33333);
    if (this.data.discountSet == 0 && this.data.toLevelPrice == 0) {
      this.setData({
        meet_discount: 0
      })
      return
    }
    // 如果品牌折扣优惠大就用品牌
    if (Number(this.data.discountSet) > Number(this.data.toLevelPrice) || Number(this.data.discountSet) == Number(this.data.toLevelPrice)) {
      this.setData({
        level: 0,
        meet_discount: 1
      })
    } else {
      this.setData({
        ['discountList.discount_money']: 0,
        meet_discount: 2
      })
    }
  },

  // 获取用户充值折扣等级
  getLevel(sale) {
    console.log(sale);
    get('/v2/api/user/discount_level', {}, (res) => {
      if (res.code == 200) {
        if (res.data == 0 || sale == 1) {
          this.setData({
            level: 0
          })
          return
        }
        let getValue = (item, val) => {
          return item[val]
        }
        this.setData({
          // 优惠的等级
          level: Number(getValue(this.data.levelList, res.data)),
        })
        this.setData({
          // 优惠的折扣 （等级*10）
          tolevel: (this.data.level * 10).toFixed(1)
        })
      }
      // 计算充值折扣
      this.rechargeDiscount()
    })
  },
  // 计算充值折扣
  rechargeDiscount() {
    // 计算折扣
    this.setData({
      // 优惠完的价格
      levelPrice: (this.data.notSalePrice * this.data.level + Number(this.data.salePrice) + Number(this.data.toExchangePrice) || Number(0)).toFixed(2),
    })
    this.setData({
      // 优惠了多少
      toLevelPrice: (this.data.selectCouponPrice - this.data.levelPrice + Number(this.data.toExchangePrice) || Number(0)).toFixed(2)
    })
  },
  // 获取分类需要加购多少商品的价格
  getExchangeInfo() {
    post('v2/api/car/plus_project', {
      store_id: this.data.storeId || wx.getStorageSync('store_id'),
      goods_id: this.data.isDirectOrder ? this.data.goods_ids : '',
      type: this.data.isDirectOrder ? 2 : 1
    }, (res) => {
      if (res.code == 200) {
        this.setData({
          exchangeInfo: res.data
        })
        this.getExchangeList(res.data.category_plus_id)
      }
    })
  },
  // 获取加购列表
  getExchangeList(id) {
    post('/v2/api/car/plus_list', {
      store_id: this.data.storeId || wx.getStorageSync('store_id'),
      category_plus_id: id || '',
      type: this.data.isDirectOrder ? 2 : 1,
      goods_id: this.data.goods_ids || ''
    }, (res) => {
      if (res.code == 200) {
        res.data.list.forEach(item => {
          item.status = false
        })
        this.setData({
          exchangeList: res.data.list
        })
      }
    })
  },
  // 获取10月活动商品折扣
  getActivityDiscount(data) {
    let activity_goods_ids = []
    let activity_num = []
    if (!this.data.isDirectOrder) {
      data.forEach(item => {
        activity_goods_ids.push(item.goods_id)
        activity_num.push(item.num)
      })
    }
    post('/v2/api/car/activity_discount', {
      goods_ids: this.data.isDirectOrder ? this.data.goods_ids : activity_goods_ids.toString(),
      nums: this.data.isDirectOrder ? 1 : activity_num.toString(),
      store_id: this.data.storeId || wx.getStorageSync('store_id')
    }, (res) => {
      if (res.code == 200) {
        this.setData({
          activity_list: res.data,
          activity_discount: res.data.discount_money
        })
        let discount = '' //计算是否有折扣
        let activity_price = '' //计算最终付钱
        res.data.discount_list.forEach(item => {
          activity_price = Number(activity_price) + Number(item.price)
          discount = Number(discount) + Number(item.discount)
        })
        if (discount > 0) {
          this.setData({
            activity_level: true,
            activity_discount: activity_price.toFixed(2),
            activity_select_money: (Number(this.data.showMoneyGood) - Number(activity_price)).toFixed(2)
          })
        }
      }
    })
  },
  // 获取产品最低折扣
  getDiscount(goods_ids, type) {
    post('v2/api/car/discount', {
      store_id: this.data.storeId,
      goods_ids: goods_ids,
      type: type
    }, (res) => {
      if (res.code == 200) {
        this.setData({
          discountList: res.data,
          discount_id: res.data.id,
          discountSet: res.data.discount_money,
        })
        // 计算总金额
        this.countDiscount()
        // 计算品牌折扣和充值折扣最低折扣
        this.calculateDiscount()
      }
    })
  },
  // 计算折扣价格
  countDiscount() {
    let discountList = this.data.discountList
    let discount_total = this.data.discount_total
    discount_total = Number(this.data.showMoneyGood) - Number(discountList.discount_money) + Number(this.data.toExchangePrice)
    this.setData({
      discount_total: discount_total.toFixed(2)
    })
  },
  // 判断订单里的秒杀产品统计
  salePrice(list) {
    let notSalePrice = '' //非秒杀产品总价格
    let salePrice = '' // 秒杀产品总价格
    let sale = 1
    list.forEach(item => {
      if (item.sale == 0) {
        sale = 0
        return
      }
    })
    list.forEach(item => {
      if (item.sale == 0) {
        notSalePrice = Number(notSalePrice) + Number(item.price) * Number(item.num)
      } else {
        salePrice = Number(salePrice) + Number(item.price) * Number(item.num)
      }
    })
    this.setData({
      notSalePrice: notSalePrice,
      salePrice: salePrice
    })
    // 获取用户折扣等级
    this.getLevel(sale)
  },
  needAddGood() {
    let params = {
      store_id: this.data.storeId,
      page: this.data.page,
      limit: this.data.limit
    }
    get('v2/api/car/list', params, (res) => {
      if (res.code == 200) {
        let selectProductCarData = []
        selectProductCarData = selectProductCarData.concat(res.data.list)
        this.setData({
          selectMakeupList: selectProductCarData,
          showMoneyGood: res.data.total_money,
          selectCouponPrice: this.data.isShow ? this.data.projectData.is_member == 1 ? this.data.projectData.member_price : this.data.projectData.price : res.data.total_money,
          store_name: res.data.store_name,
          exchangePrice: res.data.total_money,
        })
        // 判断订单里的秒杀产品统计
        this.salePrice(res.data.list)
        // 获取活动折扣
        this.getActivityDiscount(selectProductCarData)
        // 计算充值折扣
        // this.rechargeDiscount()
        // 获取最低折扣
        this.getDiscount(this.data.goods_ids, this.data.type)
        // 计算产品总数量
        let num = 0
        selectProductCarData.map(item => {
          num += item.num
        })
        this.setData({
          listNum: num
        })
        if (this.data.selectMakeupList < res.data.count) {
          this.setData({
            page: this.data.page + 1
          })
          this.needAddGood()
        }
      }
    })
  },
  onConfirm() {
    let params = {
      goods_ids: this.data.productId,
      store_id: this.data.storeId,
      type: 2
    }
    post('v2/api/goods_order/confirm', params, (res) => {
      if (res.code == 200) {
        let selectProductCarData = []
        selectProductCarData = selectProductCarData.concat(res.data.list)
        this.setData({
          selectMakeupList: selectProductCarData,
          showMoneyGood: res.data.total_price,
          selectCouponPrice: this.data.isShow ? this.data.projectData.is_member == 1 ? this.data.projectData.member_price : this.data.projectData.price : res.data.total_money,
          store_name: res.data.store_name,
          exchangePrice: res.data.total_price
        })
        // 计算充值折扣
        // this.rechargeDiscount()
        // 获取最低折扣
        this.getDiscount(this.data.goods_ids, this.data.type)
      }
    })
  },
  onClosePay() {
    this.setData({
      payNow: false
    })
  },
  pay_methonw() {
    this.setData({
      pay_methon: 1
    })
  },

  pay_methonc() {
    this.setData({
      pay_methon: 2
    })
  },
  /**
   * 获取我的储值
   * api/user
   */
  getAmount() {
    get('api/user/amount', {}, (res) => {
      if (res.data) {
        this.setData({
          inserllAmount: res.data.amount
        })
      }
    })
  },
  getCoupon() {
    post('v2/api/car/coupon', {
      page: 1,
      limit: 50,
      store_id: this.storeId
    }, res => {
      if (res.code == 200) {
        res.data.list.forEach(item => {
          item["checkStatus"] = false
        })
        this.setData({
          couponList: res.data.list
        })
      }
    })
  },
  // 提交订单
  onCardgoodsPay() {
    // 计算充值折扣
    this.rechargeDiscount()
    let goods_ids = [],
      coupon_id = []
    this.data.selectMakeupList.forEach(res => {
      if (this.data.isDirectOrder) {
        goods_ids.push(res.id)
      } else {
        goods_ids.push(res.goods_id)
      }
    })
    this.data.selectCouponList.forEach(res => {
      coupon_id.push(res.id)
    })
    // 筛选添加换购产品
    let plus = []
    this.data.exchangeList.forEach(item => {
      let obj = {}
      if (item.status) {
        obj.plus_type = item.type
        obj.plus_id = item.id
        obj.plus_goods_id = item.plus_goods_id
        plus.push(obj)
      }
    })
    let discount_money = 0
    if(this.data.discountList.balance_discount>this.data.discountList.discount_money){
      discount_money = this.data.discountList.balance_discount
    }else{
      discount_money = this.data.discountList.discount_money
    }
    console.log(plus);
    let params = {
      goods_ids: this.data.isshow ? this.data.projectData : goods_ids.toString(),
      store_id: this.data.storeId,
      coupon_id: coupon_id.toString(),
      type: this.data.isShow ? 2 : 1,
      discount_id: this.data.discount_id || '',
      discount_money: discount_money,
      plus,
      meet_discount: this.data.meet_discount
    }
    post('v2/api/car/closing', params, res => {
      if (res.code == 200) {
        if (res.data.pay_status == 1) {
          wx.showToast({
            title: '支付成功',
            icon: 'success'
          })
          // 只有项目购买，需要订阅消息
          wx.reLaunch({
            url: `/pages/paySuccess/paySuccess?current=1&source=goods&order_id=${res.data.order_id}`
          })
        } else {
          this.setData({
            payNow: true,
            orderId: res.data.order_id
          })
          this.getAmount()
        }
      }
    })
  },
  onCouponOpen() {
    this.setData({
      visible: true
    })
  },
  onCancelCoupon() {
    this.setData({
      visible: false
    })
  },
  onCouponChange(e) {
    this.setData({
      currentCoupon: e.currentTarget.dataset.index,
    })
    this.data.couponList.forEach((res, index) => {
      let currentCouponItem = `couponList[${index}].checkStatus`
      if (e.currentTarget.dataset.index == index && e.detail.checkStatus) {
        this.setData({
          [currentCouponItem]: e.detail.checkStatus
        })
      } else {
        this.setData({
          [currentCouponItem]: false
        })
      }
    })


  },
  onConfirmCoupon() {
    let coupon_id = '',
      selectCouponList = [],
      selectCouponPrice = Number(this.data.showMoneyGood),
      couponPrice = 0
    this.data.couponList.forEach(res => {
      if (res.checkStatus) {
        selectCouponList.push(res)
        if (res.coupon_type == 3) {
          couponPrice = selectCouponPrice
          selectCouponPrice = 0
        } else {
          selectCouponPrice = selectCouponPrice - Number(res.price)
          couponPrice = couponPrice + Number(res.price)
        }
      }
    })
    if (this.data.currentCoupon != '' && this.data.couponList[this.data.currentCoupon].checkStatus) {
      coupon_id = this.data.couponList[this.data.currentCoupon].id
    }
    if (selectCouponPrice < 0) {
      selectCouponPrice = 0
    }
    this.setData({
      coupon_id: coupon_id,
      visible: false,
      selectCouponList: selectCouponList,
      selectCouponPrice: selectCouponPrice,
      couponPrice: couponPrice
    })
  },
  /**
   * 订单支付
   */
  payOrder() {
    let that = this
    let uri = 'v2/api/order/goods/pay'
    post(
      uri, {
        pay_way: this.data.pay_methon == 1 ? 'weixin' : 'amount',
        order_id: this.data.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('支付失败')
          }
        })
      }
    )
  },
  /**
   * 跳转订单列表
   */
  goToOrder(text) {
    let that = this
    wx.showToast({
      title: text,
      icon: text == '支付成功' ? 'success' : 'error'
    })
    if (text == '支付成功') {
      // 只有项目购买，需要订阅消息
      wx.reLaunch({
        url: `/pages/paySuccess/paySuccess?current=1&source=${this.data.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
    } else {
      let failUrl = `/pages/goods/orderList/orderList?current=0`
      setTimeout(() => {
        wx.reLaunch({
          url: failUrl
        })
      }, 1000)
    }
  },
  // 获取产品详情
  getProductInfo() {
    get(
      '/api/product/info', {
        store_id: wx.getStorageSync('store_id'),
        product_id: this.data.productId,
        type: 3
      },
      (res) => {
        this.setData({
          projectData: res.data,
          sale: res.data.sale,
          notSalePrice: res.data.price,
          selectCouponPrice:res.data.price
        })
        // 获取用户折扣等级
        this.getLevel(res.data.sale)
      },
    )
  },
  // 获取购买次卡享受的折扣
  getCardDiscount() {
    get('', {}, (res) => {
      this.setData({
        CardDiscount: ''
      })
    })
  },
  // 选中加购产品
  selectExchange(e) {
    let index = e.currentTarget.dataset.index
    let sum = 0
    // 修改加购产品选中状态
    this.setData({
      [`exchangeList[${index}].status`]: this.data.exchangeList[index].status ? false : true
    })
    //选中加购产品价格 
    this.data.exchangeList[index].status ? sum = Number(this.data.exchangeList[index].price) : sum = Number(-this.data.exchangeList[index].price)
    // 是否选择加购产品
    let exchangeSelect = false
    this.data.exchangeList.forEach(item => {
      if (item.status) {
        exchangeSelect = true
      }
    })
    let exchangePrice = Number(this.data.exchangePrice) + Number(sum)
    this.setData({
      exchangeSelect: exchangeSelect,
      exchangePrice: exchangePrice.toFixed(2),
      toExchangePrice: Number(this.data.toExchangePrice) + Number(sum)
    })
    // 计算总金额折扣
    this.countDiscount()
  },
})