/*
 * @Descripttion: HJ
 * @Company: 思宏科技
 * @version: v1.0
 * @Author: HJ
 * @Date: 2021-03-24 18:07:34
 * @LastEditors: WorkerChen z874512298@163.com
 * @LastEditTime: 2022-05-11 09:11:50
 */
const { bus, Tips } = getApp()
const _REPELACE_KEY = '+'

// 控制菜品数量
export const controlNumber = (data, option = {}) => {
  if (!data) return
  console.log(data,'这是商品的信息')
  const { ifBroadcast = true, isAdd = true } = option

  let { detail, key } = data
  const { stock, startNum, foodType, storeFoodId,dailyStock } = detail
  let { number } = detail

  // 1. 每个商品都有起购份数, 默认为1
  const addNum = number === 0 || (!isAdd && number === startNum) ? startNum : 1
  number += addNum * (isAdd ? 1 : -1)

  if (number <= -1) {
    updateMandatoryIds({ categoryId, storeFoodId }, 'delete')
    return 0
  }

  if (foodType === 7) {
    if (number > 0) wx.$setGlobalData('preferentialFoods', { [key]: detail })
    else delete getApp().globalData.preferentialFoods[key]
  }

  if (number > dailyStock) {
    Tips(`商品当日库存不足，请您选择其它商品下单`)
    console.log(number)
    number = dailyStock
    return number
  }

  // 如果需要广播的话再计算相应需要的内容
  ifBroadcast && publishShoppingCart(key, detail, number, option)

  return number
}

// 构建菜品的key
export const constructorDishUuid = (sku, attribute = '') => {
  let { foodName, name, categoryId } = sku
  let attributeKey = ''

  try {
    attribute = JSON.parse(attribute)
  } catch (e) {}
  if (Array.isArray(attribute) && attribute.length > 0) {
    attribute.forEach(i => {
      const { key, value } = i
      if (Array.isArray(value) && value.length > 0) {
        attributeKey += `${key}_${value[0]}_`
      }
    })
  } else {
    attributeKey = attribute || ''
  }

  foodName = foodName.replace(/\./g, _REPELACE_KEY)
  name = name.replace(/\./g, _REPELACE_KEY)
  attributeKey = attributeKey.replace(/\./g, _REPELACE_KEY)

  return `${categoryId + ''}_${foodName}_${name}_${attributeKey}`
}

// 更新折扣菜品的存储
const updateGlobalDiscountDish = (key, value) => {
  let boughtDiscountDishes = wx.$getGlobalData('boughtDiscountDishes') || {}
  boughtDiscountDishes[key] = value
  wx.$setGlobalData('boughtDiscountDishes', boughtDiscountDishes)
}

// 处理折扣商品的提示
const handlerDiscountDishes = (key, detail, number, option = {}) => {
  const { discountInfo = {}, boughtDiscountDishes = {} } = getApp().globalData
  const { limitStatus, limitNum } = discountInfo
  const { limitBuyNumber } = detail
  const { isAdd = true, type } = option
  let discountNumber = 0
  let normalNumber = number
  const detailFlag = type === 'dish_detail'

  // 1. 后台如果设置每单只允许购买 N 个折扣商品的话，需要做好提示
  if (limitStatus) {
    // 获取购物车
    const cart = wx.$getGlobalData('cartDishes') || {}
    // 购物车中当前菜品的相关属性
    const {
      discountNumber: currDiscountNumber = discountNumber,
      normalNumber: currNormalNumber = normalNumber,
      limitBuyNumber: currLimitBuyNumber
    } = cart[key] || detail

    // 计算数量
    let allDiscountNumber = 0
    let nextDiscountDish = null

    for (let i in boughtDiscountDishes) {
      const {
        discountNumber,
        limitBuyNumber,
        normalNumber
      } = boughtDiscountDishes[i]
      allDiscountNumber += discountNumber
      if (!isAdd) {
        const laveDiscountNumber = limitBuyNumber - discountNumber
        // 1. 选中的下一个折扣菜品的数量是否有剩余的空间可以将普通菜品替换成折扣菜品
        // 2. 选中的折扣菜品本身的限购数是否允许将普通菜品替换成折扣菜品
        // 3. 正在减少的菜品需要优先减去普通菜品，所以当普通菜品数量为 0 的时候才开始计算
        // limitBuyNumber 为 0 表示当前菜品不限购
        if (
          i !== key &&
          currNormalNumber === 0 &&
          normalNumber > 0 &&
          (limitBuyNumber === 0 || laveDiscountNumber > 0) &&
          !nextDiscountDish
        ) {
          nextDiscountDish = { key: i, value: boughtDiscountDishes[i] }
        }
      }
    }

    // 当前可以购买的折扣商品的数量，去掉当前菜品的部分
    const canBuyDiscountNumber =
      limitNum - allDiscountNumber + currDiscountNumber

    if (canBuyDiscountNumber >= 0) {
      const tempLimitNumber =
        canBuyDiscountNumber > limitBuyNumber && limitBuyNumber !== 0
          ? limitBuyNumber
          : canBuyDiscountNumber

      normalNumber = number >= tempLimitNumber ? number - tempLimitNumber : 0
      discountNumber = number >= tempLimitNumber ? tempLimitNumber : number
    }

    // 当前折扣商品的数量减少，并且订单中折扣商品的限购剩余数量大于0
    // nextDiscountDish 的作用是
    // 1. 方便判断除了当前减少的折扣菜品之外，购物车中是否还存在其他折扣菜品
    // 2. 可以直接使用 nextDiscountDish 更新购物车中的折扣商品
    if (!isAdd && canBuyDiscountNumber > 0 && nextDiscountDish) {
      let { value: tempDish, key } = nextDiscountDish
      let {
        discountNumber,
        normalNumber,
        discountPrice,
        price,
        packagePrice
      } = tempDish
      normalNumber -= 1
      discountNumber += 1
      const totalPrice = discountPrice * discountNumber + price * normalNumber
      const totalDiscountPrice = discountPrice * discountNumber
      const totalPackagePrice = (packagePrice || 0) * number

      tempDish = {
        ...tempDish,
        normalNumber,
        discountNumber,
        totalPrice,
        showTotalPrice: totalPrice.toFixed(2),
        showTotalDiscountPrice: totalDiscountPrice.toFixed(2),
        totalPackagePrice
      }
      // 更新购物车中的菜品
      bus.emit('updateCartDish', {
        key,
        value: tempDish
      })
      // 将当前的菜品数据添加到全局中
      updateGlobalDiscountDish(key, tempDish)
    }

    if (isAdd) {
      // 1. 可以购买的折扣菜品数量大于商品本身的限购数量的时候，提示使用的是原本菜品的限购份数
      if (currLimitBuyNumber > 0 && canBuyDiscountNumber > currLimitBuyNumber) {
        const tempFlag = detailFlag
          ? currLimitBuyNumber <= number
          : currLimitBuyNumber + 1 === number
        if (tempFlag) {
          Tips(
            `折扣菜品限购${currLimitBuyNumber}份，超过${currLimitBuyNumber}份恢复原价`
          )
        }
      } else if (
        detailFlag
          ? number >= canBuyDiscountNumber
          : allDiscountNumber + 1 === limitNum
      ) {
        Tips(`每单的折扣菜品限购${limitNum}份，超过${limitNum}份恢复原价`)
      }
    }

    // 将当前的菜品数据添加到全局中
    updateGlobalDiscountDish(
      key,
      Object.assign({}, detail, {
        number,
        discountNumber,
        normalNumber
      })
    )
  }
  // 2. 折扣商品超出限购份数就要提示用户
  else {
    discountNumber = number
    normalNumber = 0
    // 限购
    if (limitBuyNumber > 0) {
      normalNumber = number >= limitBuyNumber ? number - limitBuyNumber : 0
      discountNumber = number >= limitBuyNumber ? limitBuyNumber : number
      // 超出限购份数提示
      if (isAdd && limitBuyNumber + 1 === number) {
        Tips(`折扣菜品限购${limitBuyNumber}份，超过${limitBuyNumber}份恢复原价`)
      }
    }

    updateGlobalDiscountDish(key, {
      ...detail,
      number,
      discountNumber,
      normalNumber
    })
  }

  return {
    discountNumber,
    normalNumber
  }
}

// 菜品广播
export const publishShoppingCart = (key, data, number, option = {}) => {
  let detail = data
  const {
    discountPrice,
    price,
    packagePrice,
    categoryId,
    storeFoodId,
    foodType
  } = detail

  let { discountNumber = 0, normalNumber = number } =
    foodType === 2 ? handlerDiscountDishes(key, detail, number, option) : {}
  if (foodType === 7) {
    discountNumber = number
    normalNumber = 0
  }

  const totalPrice = discountPrice * discountNumber + price * normalNumber
  const totalPackagePrice = (packagePrice || 0) * number

  const totalOriginalPrice = price * number

  detail = Object.assign({}, detail, {
    // 普通菜品的实际总价
    totalPrice: totalPrice,
    // 原始价格
    totalOriginalPrice: totalOriginalPrice,
    showTotalPrice: totalPrice.toFixed(2),
    showTotalOriginalPrice: totalOriginalPrice.toFixed(2),
    totalPackagePrice,
    discountNumber,
    normalNumber
  })

  updateMandatoryIds(
    { categoryId, storeFoodId },
    number <= 0 ? 'delete' : 'add'
  )

  bus.emit('cateChannel', { key: categoryId, number, storeFoodId })
  bus.emit('shoppingCartChannel', { key, data: { number, detail } })
}

// 更新已选分类列表
export const updateMandatoryIds = (
  { categoryId, storeFoodId },
  type = 'add'
) => {
  console.log(wx.$getGlobalData('selectedCategory'))
  let selectedCategory = wx.$getGlobalData('selectedCategory') || new Map()
  console.log(selectedCategory)
  let categoryIdFoods = selectedCategory.get(categoryId)
  if (!categoryIdFoods) {
    categoryIdFoods = new Set()
  }
  categoryIdFoods[type](storeFoodId)

  if (type === 'delete' && categoryIdFoods.size === 0) {
    selectedCategory.delete(categoryId)
  } else {
    selectedCategory.set(categoryId, categoryIdFoods)
  }

  wx.$setGlobalData('selectedCategory', selectedCategory)
}
