/*
 * @Descripttion: HJ
 * @Company: 思宏科技
 * @version: v1.0
 * @Author: HJ
 * @Date: 2021-03-24 16:06:01
 * @LastEditors: WorkerChen z874512298@163.com
 * @LastEditTime: 2022-05-10 11:25:01
 */
const { controlNumber } = require('../../_utils/dish')
const { bus, watch } = getApp()
const componentOptions = {
  // 组件选项
  options: {
    multipleSlots: true
  },
  properties: {
    extraInfo: {
      type: Object,
      value: {},
      observer(v) {
        if (v) {
          const { deliveryPrice, storeOperatingStatus } = v
          const baseTotal = deliveryPrice || 0
          this.baseTotal = baseTotal
          this.setData({
            storeOperatingStatus: storeOperatingStatus || 1
          })
        }
      }
    }
  },
  // 组件数据
  data: {
    isPageHidden: false, // 页面是否处于隐藏状态
    // 是否展示购物车
    show: false,
    // 是否展开购物车详情
    expansion: false,
    // 购物车列表
    cartDishes: {},
    // 购物车信息
    cartInfo: {
      totalPrice: 0,
      totalNumber: 0
    },
    // 折扣信息相关
    discountInfo: {},
    // 门店信息
    storeOperatingStatus: 1
  },
  // 数据监听器
  observers: {
    'cartDishes.**'(v) {
      let total = this.baseTotal || 0
      let totalOriginal = 0
      let totalNumber = 0
      let totalPackagePrice = 0

      for (let i in v) {
        const {
          totalPrice,
          totalOriginalPrice,
          number,
          totalPackagePrice: tempPackagePrice = 0
        } = v[i]
        total += totalPrice + tempPackagePrice
        totalOriginal += totalOriginalPrice + tempPackagePrice
        totalPackagePrice += tempPackagePrice
        totalNumber += number
      }

      const tempPreferentialFoods = wx.$getGlobalData('preferentialFoods')
      let diff = 0
      let redu = 0
      let startSalePriceText = ''
      let reductionText = ''
      // 已经减去的金额
      let haveMinus = 0
      // 差X元
      let poor = 0
      // 可以减去
      let canSubtract = 0
      console.log(this.data.extraInfo)
      let { reductions, startSalePrice } = this.data.extraInfo
      startSalePrice = startSalePrice || 0
      if (Object.keys(tempPreferentialFoods).length < 1) {
        // 计算满减
        reductions = reductions || []
        const discountNumber = this.computedDiscountNumber() || 0
        if (discountNumber <= 0) {
          for (let i = 0; i < reductions.length; i++) {
            const { overflow, reduction } = reductions[i]
            if (total >= overflow) {
              redu = reduction
              const temp = reduction.toFixed(2)
              reductionText = `已减${temp}元`
              haveMinus = temp
            } else {
              const diff = (overflow - total).toFixed(2)
              canSubtract = reduction.toFixed(2)
              poor = diff
              reductionText +=
                (reductionText ? ',' : '') +
                `还差${diff}元,可以立减${canSubtract}元`

              break
            }
          }
          total -= redu
        }
      }
      // 计算起送价
      if (total < startSalePrice) {
        diff = (startSalePrice - total).toFixed(2)
        startSalePriceText = `差${diff}元起送`
      }
      // 计算是否选了必选
      const mandatory = wx.$getGlobalData('mandatory')
      if (mandatory && mandatory.length > 0) {
        const unSelectorId = this.checkedMustBuy()
        if (Array.isArray(unSelectorId) && unSelectorId.length > 0) {
          startSalePriceText = `未点必选分类`
          this.tempIds = unSelectorId
        }
      }

      wx.$setGlobalData('cartTotalNumber', totalNumber)
      const totalDiscountPrice = totalOriginal - total
      this.setData({
        'cartInfo.showTotalPrice': total.toFixed(2),
        'cartInfo.showTotalOriginalPrice': totalOriginal.toFixed(2),
        'cartInfo.totalDiscountPrice': totalDiscountPrice.toFixed(2),
        'cartInfo.totalNumber': totalNumber,
        'cartInfo.totalPackagePrice': totalPackagePrice.toFixed(2),
        'cartInfo.reductionText': reductionText,
        'cartInfo.reductionObj': {
          haveMinus,
          poor,
          canSubtract
        },
        'cartInfo.diff': diff || 0,
        'cartInfo.startSalePriceText': startSalePriceText
      })
    },
    show(v) {
      bus.emit('onShoppingCartDisplay', { show: v })
    }
  },
  // 组件方法
  methods: {
    init() {
      bus.on('shoppingCartChannel', this.handleShoppingCartData.bind(this))
      bus.on('updateCartDish', this.handlerUpdateDish.bind(this))
      bus.on('onShoppingCartDisplay', this.handlerCartShow.bind(this))
      // 由于请求会有时间差，所以使用监听后赋值的方法
      watch('discountInfo', this.handlerDiscountInfo.bind(this))
    },
    // 展开购物车
    onUnfold() {
      this.setData({
        expansion: true
      })
    },
    // 收起购物车详情
    onClose() {
      this.setData({
        expansion: false
      })
    },
    // 处理购物车信道的信息
    handleShoppingCartData(info) {
      let {
        key,
        data: { detail, number }
      } = info

      // 特殊处理
      if (number <= 0) {
        let { cartDishes, expansion } = this.data
        delete cartDishes[key]
        const flag = Object.keys(cartDishes).length > 0
        this.setData({
          cartDishes,
          show: flag,
          expansion: expansion && flag
        })
        return
      }

      detail.number = number
      this.setData(
        {
          [`cartDishes.${key}`]: detail,
          show: true
        },
        () => {
          wx.$setGlobalData('cartDishes', this.data.cartDishes)
        }
      )
    },
    // 数量加/减
    // 某一个菜品加
    controlNumber({ currentTarget: { dataset } }) {
      const { key, detail, isAdd } = dataset
      controlNumber({ key, detail }, { isAdd })
    },
    // 计算购物车中是否有折扣商品
    computedDiscountNumber() {
      let allDiscountNumber = 0
      const boughtDiscountDishes =
        wx.$getGlobalData('boughtDiscountDishes') || {}
      for (let i in boughtDiscountDishes) {
        const { discountNumber } = boughtDiscountDishes[i]
        allDiscountNumber += discountNumber
      }
      return allDiscountNumber
    },
    // 去购买
    toBuy() {
      const authFlag = wx.getStorageSync('anflag')
      if (authFlag) {
        wx.navigateTo({
          url: '/pages/authorization/authorization'
        })
        return
      }
      wx.setStorageSync('trueindex', 'fail')
      wx.setStorageSync('mentionlist', '')
      wx.setStorageSync('startSalePrice', 0)
      const storeid = wx.getStorageSync('storeid')

      wx.navigateTo({
        url:
          '/package/good/affirm/affirm?storeid=' +
          storeid +
          '&currentflag=1' +
          '&addressflag=1'
      })
    },
    // 处理折扣订单想相关的信息
    handlerDiscountInfo(discountInfo) {
      this.setData({
        discountInfo
      })
    },
    // 更新一个菜品
    handlerUpdateDish({ key, value }) {
      this.setData(
        {
          [`cartDishes.${key}`]: value
        },
        () => {
          getApp().globalData.cartDishes = this.data.cartDishes
        }
      )
    },
    // 清空购物车
    clearCart() {
      this.setData(
        {
          cartDishes: {},
          cartInfo: {
            totalPrice: 0,
            totalNumber: 0,
            totalPackagePrice: 0,
            reductionText: ''
          },
          show: false,
          expansion: false
        },
        () => {
          wx.$setGlobalData('cartTotalNumber', 0)
          wx.$setGlobalData('cartDishes', {})
          wx.$setGlobalData('boughtDiscountDishes', {})
          wx.$setGlobalData('selectedCategory', new Map())
          this.tempIds = []
          bus.emit('onClearCart')
        }
      )
    },
    // 处理显示
    handlerCartShow({ show }) {
      const { show: currShow } = this.data
      if (show !== currShow) this.setData({ show })
    },
    // 检查是否选了必选
    checkedMustBuy() {
      const mandatory = wx.$getGlobalData('mandatory') || []
      const selectedCategory =
        wx.$getGlobalData('selectedCategory') || new Set()
      const id = mandatory.filter(i => !selectedCategory.has(i))
      return id
    },
    // 处理未选必选分类
    handlerFailToBuy() {
      if (this.tempIds && this.tempIds.length > 0) {
        bus.emit('onToMustBuy', {
          currentTarget: { dataset: { cateId: this.tempIds[0] } }
        })
      }
    }
  },
  // 组件生命周期
  lifetimes: {
    attached() {
      this.init()
    }
  },
  definitionFilter() {},
  // 页面生命周期
  pageLifetimes: {
    // 页面被展示
    show() {
      const { isPageHidden } = this.data

      // show事件发生前，页面不是处于隐藏状态时
      if (!isPageHidden) {
        return
      }

      // 重新执行定时器等操作
    },
    // 页面被隐藏
    hide() {
      this.setData({
        isPageHidden: true
      })

      // 清除定时器等操作
    }
  }
}

Component(componentOptions)
