// component/skuPopup/skuPopup.js
// import { ReportModel } from '../../utils/reportModel'
const wxService = require('../../utils/wxService')
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    disableNum: { // 不能改变的数量
      type: Number,
      observer: '_disableNumChange',
      value: 0
    },
    productName: {
      type: String,
      value: ''
    },
    exchangePrice: {
      type: Number,
      value: 0
    },
    isAllowArrive: {
      type: Number,
      value: 0
    },
    isNoticeStatus: {
      type: Boolean
      // value: false
    },
    integralRole: {
      type: Number,
      value: 0
    },
    priceNoChange: {
      type: Boolean,
      value: false
    },
    showPrice: { // 指定显示的价格
      type: Number,
      observer: '_showPriceChange',
      value: 0
    },
    quantityAverage: {
      type: String,
      value: '0'
    },
    btnText: {
      type: String,
      value: '确定'
    },
    imageDomain: {
      type: String,
      value: ''
    },
    specNames: { // 所有规格名
      type: Object,
      value: []
    },
    specValues: { // 所有规格值
      type: Object,
      value: []
    },
    proNum: { // 初始化的数量
      type: Number,
      value: 1
    },
    goodType: { // 虚拟
      type: Number,
      value: 1
    },
    initSku: { // 初始化的sku
      type: Object,
      value: null
    },
    skuInfos: { // 所有sku信息
      type: Object,
      value: [],
      observer: '_skuInfosChange'
    },
    indexImg: { // 商品主图
      type: String,
      value: ''
    },
    show: { // 显示标识
      type: Boolean,
      value: false
    }
  },

  attached () {
    let price = this.data.showPrice
    if (!price) {
      if (this.data.curSku.promotion_price) {
        price = this._setExchangePrice(this.data.curSku.promotion_price)
      }
    }
    console.log(this.data)
    this.setData({
      price
    })
  },

  /**
   * 组件的初始数据
   */
  data: {
    skuInfoDatas: [], // 重新组装的规格json数据
    curSpec: [], // 当前选中的规格值
    curSku: {}, // 当前选中的sku信息
    price: 0, // 页面上展示的价格
    skuText: '',
    skuStock: 0,
    btnText: '确定', // 确定 缺货 缺货订阅
    isOutStock: false, // 背景色
    clickDataStock: 0
  },

  detached: function () {
    this._disableNumChange = null
    this._showPriceChange = null
    this._skuInfosChange = null
  },

  /**
   * 组件的方法列表
   */
  methods: {
    _skuInfosChange () {
      var curSpec = []
      if (this.data.initSku) {
        console.log(this.data.initSku)
        curSpec = this.data.initSku.spec.split('###')
      }
      this.setData({
        skuInfoDatas: [], // 重新组装的规格json数据
        curSpec: curSpec, // 当前选中的规格值
        curSku: {}, // 当前选中的sku信息
        skuText: '',
        skuStock: 0
      })
      this._setCurSku()
    },
    _showPriceChange (newV, oldV) {
      if (newV !== oldV) {
        this.setData({
          showPrice: newV,
          price: newV
        })
      }
    },
    confirm: function () {
      for (var i = 0; i < this.data.curSpec.length; i++) {
        if (!this.data.curSpec[i]) {
          wx.showToast({
            title: '请选择规格',
            icon: 'none'
          })
          return false
        }
      }
      this.triggerEvent('skuselect', {
        selectSku: this.data.curSku,
        counts: this.data.proNum,
        isAllowArrive: this.data.isAllowArrive,
        clickDataStock: this.data.clickDataStock
      })
    },
    inputNum: function (e) { // 输入数量
      var newNum = e.detail.value
      if (newNum === '' || newNum === '0') {
        newNum = 1
      } else {
        newNum = parseInt(newNum)
        if (this.data.quantityAverage == '0') {
          if (newNum > this.data.curSku.inventory_num) {
            newNum = this.data.curSku.inventory_num
            wx.showToast({
              title: '不能超过库存',
              icon: 'none'
            })
          }
        } else {
          if (newNum > this.data.quantityAverage) {
            newNum = this.data.quantityAverage
            wx.showToast({
              title: '每人限购' + this.data.quantityAverage + '件',
              icon: 'none'
            })
          }
        }
      }
      this.setData({
        proNum: newNum
      })
    },
    minusNum: function () { // 减少数量
      var proNum = this.data.proNum
      if (proNum > 1) {
        proNum--
      } else {
        wx.showToast({
          title: '数量不能为0',
          icon: 'none'
        })
      }
      this.setData({
        proNum: proNum
      })
    },
    addNum: function () { // 增加数量
      let proNum = this.data.proNum
      const curSku = this.data.curSku
      if (this.data.quantityAverage == '0') {
        if (proNum < this.data.curSku.inventory_num) {
          proNum++
        } else {
          wx.showToast({
            title: '不能超过库存',
            icon: 'none'
          })
        }
      } else {
        if (proNum < this.data.quantityAverage) {
          proNum++
        } else {
          wx.showToast({
            title: '每人限购' + this.data.quantityAverage + '件',
            icon: 'none'
          })
        }
      }
      console.log(this.data)
      let reportModel = new ReportModel('add_to_cart')
      reportModel.setProps({
        sku: {
          sku_id: curSku.sku_code,
          sku_name: this.data.productName,
          original_price: parseFloat(curSku.price / 100).toFixed(2)
        },
        sku_price: parseFloat(curSku.price / 100).toFixed(2),
        action_type: proNum ? 'append_to_cart' : 'first_add_to_cart'
      })
      wxService.report(reportModel)

      this.setData({
        proNum: proNum
      })
    },
    hidePopup: function () { // 隐藏弹出框
      this.setData({
        show: false
      })
    },
    selectSku: function (event) { // 点击规格值，设置选中状态
      var clickData = event.target.dataset
      var curSpec = this.data.curSpec
      if (!clickData.disable) {
        curSpec[clickData.index] = clickData.name
        this.setData({
          curSpec: curSpec
        }, this._setCurSku())
      } else {
        return false
      }
      // 有库存
      let btnText = '确定'
      let isOutStock = false
      // 没库存
      if (!clickData.stock) {
        isOutStock = true
        btnText = this.data.isNoticeStatus ? '您已订阅成功' : '商品暂时缺货,订阅到货通知'
      }
      this.setData({
        btnText, isOutStock, clickDataStock: clickData.stock
      })
    },

    _disableNumChange (newV, oldV) {
      if (newV !== oldV) {
        this.setData({
          disableNum: newV
        })
      }
    },

    _setExchangePrice (price) {
      let exprice = price
      if (this.data.exchangePrice > 0) {
        let exchangePrice = this.data.exchangePrice// 积分数
        let bwtPrice = ((exchangePrice * this.data.integralRole - price) / 100)// 差额
        exprice = bwtPrice < 0 ? ((exchangePrice) + '积分+￥' + Math.abs(bwtPrice)) : (exchangePrice + '积分')
      }
      return exprice
    },

    _setCurSku: function () { // 显示选中的sku信息
      if (!this.data.skuInfos) {
        return false
      }
      var proNum = this.data.proNum

      var curSpec = this.data.curSpec

      var skuInfoDatas = []
      if (curSpec.length === 0) {
        curSpec.length = this.data.specNames.length
      }
      // 根据当前选中的规格，设置其他每一个规格项的库存数
      for (var i = 0; i < this.properties.specNames.length; i++) {
        var specJson = {
          specName: this.properties.specNames[i],
          specValue: []
        }
        for (var j = 0; j < this.properties.specValues[i].length; j++) {
          var tempStock = 0
          for (var k = 0; k < this.properties.skuInfos.length; k++) {
            var skuNameArray = this.properties.skuInfos[k].spec.split('###')
            if (skuNameArray[i] === this.properties.specValues[i][j]) {
              var flag = true
              for (var z = 0; z < skuNameArray.length; z++) {
                if (curSpec[z] && i !== z && curSpec[z] !== skuNameArray[z]) {
                  flag = false
                }
              }
              if (flag) {
                tempStock += this.properties.skuInfos[k].inventory_num
              }
            }
          }
          specJson.specValue.push({
            skuName: this.properties.specValues[i][j],
            skuStock: tempStock
          })
        }
        skuInfoDatas.push(specJson)
      }
      // 根据当前选中的规格，设置头部的规格信息
      var skuText = []
      if (curSpec.join('') === '') {
        skuText = ['请选择规格']
      } else {
        for (let i = 0; i < curSpec.length; i++) {
          if (!curSpec[i]) {
            skuText.push('请选择' + this.data.specNames[i])
          } else {
            skuText.push(curSpec[i])
          }
        }
      }
      var skuStock = 0
      var curSkus = this.data.skuInfos.filter(function (item) {
        var flag = true
        for (let i = 0; i < curSpec.length; i++) {
          if (curSpec[i] && curSpec[i] !== item.spec.split('###')[i]) {
            flag = false
          }
        }
        if (flag) {
          skuStock += item.inventory_num
        }
        return flag
      })
      var curSku = curSkus[0]
      if (proNum > curSku.inventory_num) { // 选择数量超过库存时将数量修改为库存数
        proNum = curSku.inventory_num
      }
      if (proNum == 0) {
        proNum = 1
      }
      let price = curSku.promotion_price

      price = this._setExchangePrice(price)

      let updateData = {
        curSpec: curSpec,
        curSku: curSku,
        skuStock: skuStock,
        skuText: skuText,
        skuInfoDatas: skuInfoDatas,
        proNum: proNum
      }
      if (!this.data.priceNoChange) {
        updateData.price = price// 拼团规格没有价格信息
      }
      this.setData(updateData)
    }
  }
})
