/*
 * @Descripttion: HJ
 * @Company: 思宏科技
 * @version: v1.0
 * @Author: HJ
 * @Date: 2021-03-19 14:56:17
 * @LastEditors: huangl
 * @LastEditTime: 2022-05-25 18:16:45
 */
const {
  fhGetStoreBanners,
  fhGetDishes,
  fhGetStoreInfo,
  fhGetReductions,
  fhGetStoreSignboard,
  fhGetReduceDelivery,
  fhGetSku
} = require('../../../api/store/index')
const { getShoppingCart, setShoppingCart } = require('../../../utils/index')
const {
  constructorDishUuid,
  publishShoppingCart,
  controlNumber
} = require('../../_utils/dish')
const { globalData, bus } = getApp()
const pageOptions = {
  // 页面数据
  data: {
    isFirstOnShow: true, // 是否为首次执行onShow
    // 页面是否加载完
    loadEnd: false,
    // 隐藏骨架屏
    hideSkeleton: false,
    // 底部滑动区域的高度
    mainHeight: 0,
    // 菜品滑动栏的高度
    dishScrollHeight: 0,
    // 自定义导航栏的高度
    navHeight: 0,
    // 门店的信息
    storeInfo: {},
    // 中间的菜单
    menus: [
      {
        text: '菜品',
        id: 'CAIPIN'
      }
    ],
    // 当前选中的菜单
    currMenu: 'CAIPIN',
    // 当前选中的菜单索引
    currMenuIndex: 0,
    // 轮播图
    banners: [],
    // 菜品列表
    foodDtoList: [],
    // 折扣菜品列表
    recommendFoodList: [],
    // 当前高亮的分类
    currCate: '',
    // 需要滑动到的菜品分类
    scrollToCate: '',
    // 购物车中的额外信息
    cartExtraInfo: {},
    // 分类数量相关
    cateNums: {},
    // 门店招牌
    signboard: {},
    // 配送费减免
    reduceDelivery: [],
    // 是否开始下拉刷新
    refresher: false,
    // 判断页面卸载时是否要清空购物车
    isClearCarts:false
  },
  // 页面载入时
  onLoad(e) {
    this.init(e)
  },
  onShow(){
    this.isClearCarts = false
  },
  // 页面初始化
  init(e) {
    let { merchantId, storeId, from, foodId, foodInfo } = e
    if (from === 'share') {
      if (!merchantId || !storeId) {
        wx.reLaunch({
          url: '/pages/public/public'
        })
        return
      }
      // 其他地方会使用，所以要存一遍
      wx.setStorageSync('merchantid', merchantId)
      wx.setStorageSync('storeid', storeId)
    } else {
      merchantId = wx.getStorageSync('merchantid')
      storeId = wx.getStorageSync('storeid')
    }

    this.merchantId = merchantId
    this.storeId = storeId
    this.from = from
    this.tempPreferentialFoodId = foodId
    this.tempFoodInfo = foodInfo
    this.tempFoodId = foodId

    wx.nextTick(() => this.getDatas())

    // 订阅购物车信道
    bus.on('cateChannel', this.handleCateNum.bind(this))
    // 购物车是否展示
    bus.on('onShoppingCartDisplay', this.handleCartDisplay.bind(this))
    // 清空购物车
    bus.on('onClearCart', this.handlerClearCart.bind(this))
    // 监听未选必选菜品
    bus.on('onToMustBuy', this.clickCate.bind(this))
    // 监听菜品的分类进入到顶部，联动左侧的菜单栏
    // this._observer = this.createIntersectionObserver({ observeAll: true });
    this.setData({
      navHeight: globalData.navBarHeight
    })
  },
  // 页面准备好时
  onReady() {
    this.storeInfoCard = this.selectComponent('#store-info-card')
    this.evaluation = this.selectComponent('#evaluation')
    this.dishCart = this.selectComponent('#dish-cart')
    this.navigationBar = this.selectComponent('#nav-bar')
    this.navigationBar.setOpacity(200, 200)
  },
  // 页面隐藏时
  onHide() {
    this.setGlobalData()
    this.isClearCarts = true
  },
  // 页面卸载时
  onUnload() {
    if(!this.isClearCarts){
      this.setGlobalData()
    }
  },
  // 下拉页面时
  onPullDownRefresh() {
    this.getDatas()
  },
  // 分享时，注：onShareAppMessage不能为async异步函数，会导致不能及时取得返回值，使得分享设置无效
  onShareAppMessage() {
    const title = '医便民'
    const path = `/store/pages/lunch/index?merchantId=${this.merchantId}&storeId=${this.storeId}&from=share`
    const imageUrl = ''

    return {
      title,
      path,
      imageUrl
    }
  },
  // 自定义事件写在下面
  initData(options) {
    const { storeInfo } = options
    const { storeOperatingStatus } = storeInfo
    this.detectCate()
    storeOperatingStatus !== 2 && this.initCartData()
    this.setData({
      refresher: false,
      hideSkeleton: true,
      isFirstOnShow: false
    })
  },
  // 初始化购物车
  initCartData() {
    this.cartKey = `cart_${this.merchantId}_${this.storeId}`
    const dishes = getShoppingCart(this.cartKey) || []
    if (dishes.length < 1) return
    dishes.forEach(i => {
      const key = constructorDishUuid(i, i.attributeText || '')
      publishShoppingCart(key, i, i.number)
    })
  },
  // 设置底部滑动区域的高度
  async setScrollHeight() {
    try {
      const res = await wx.$queryStyles('#main-box')
      const { height } = res
      this.isFirstSetHeight = true
      this.setData({
        mainHeight: height,
        dishScrollHeight: height
      })
    } catch (e) {}
  },
  // 设置菜品滑动区域的高度
  async setDishScrollHeight(isCart) {
    try {
      const { mainHeight } = this.data
      let height = 0
      if (isCart) {
        const res = await wx.$queryStyles('#dish-cart')
        height = res.height || 0
      }
      this.setData({
        dishScrollHeight: mainHeight - height
      })
    } catch (e) {
      console.error('setDishScrollHeight error', e)
    }
  },
  // 点击切换菜单
  switchMenu({ currentTarget: { dataset } }) {
    const { id, index } = dataset
    if (id) {
      this.setData({ currMenu: id, currMenuIndex: index })
      this.affterControlCartShow(id)
    }
  },
  // 滑动切换菜单
  swiperChange({ detail }) {
    const { menus } = this.data
    const { current } = detail
    const currMenu = menus[current].id
    this.affterControlCartShow(currMenu)
    this.setData({
      currMenu
    })
  },
  // 切换菜单后控制购物车是否显示
  affterControlCartShow(currMenu) {
    const { cartDishes } = this.dishCart.data

    const show =
      currMenu === 'CAIPIN' ? Object.keys(cartDishes).length > 0 : false

    bus.emit('onShoppingCartDisplay', { show })
  },
  // 下拉刷新
  refresherEvent() {
    this.setData(
      {
        refresher: true
      },
      () => {
        this.getDatas()
      }
    )
  },
  // 获取首页的所有数据
  async getDatas() {
    this.setData({
      loadEnd: false,
      hideSkeleton: false
    })

    try {
      const { discountActBaseInfoRsp } = await this.getDishes()
      const storeInfo = await this.getStoreInfo()
      await this.getStoreBanners()
      const { reductions } = await this.fhGetReductions()
      await this.getStoreSignboard()
      const { reduceDelivery } = await this.getReduceDelivery()

      const { deliveryPrice, storeOperatingStatus, startSalePrice } = storeInfo

      if (this.from === 'preferential' && storeOperatingStatus !== 2) {
        const tempInfo = wx.$urlDecode(this.tempFoodInfo)
        const { foodSkuId } = tempInfo
        this.tempPreferentialFoodSkuId = foodSkuId
        this.bannerDetail(this.tempFoodId, [tempInfo])
      }

      // 平台优惠券
      let platformCouponInfo = wx.$getGlobalData('platformCouponInfo') || {}
      platformCouponInfo = {
        ...platformCouponInfo,
        currMerchantId: this.merchantId
      }
      // 所有活动
      const actives = {
        overflowReduction: reductions,
        discountInfo: discountActBaseInfoRsp,
        reduceDelivery,
        platformCouponInfo
      }
      const cartExtraInfo = {
        deliveryPrice,
        reductions,
        storeOperatingStatus,
        startSalePrice,
        tempPreferentialFoodSkuId: this.tempPreferentialFoodSkuId || null
      }
      this.setData({
        cartExtraInfo,
        actives
      })

      const { isFirstOnShow } = this.data
      if (isFirstOnShow) {
        this.initData({ storeInfo })
      } else {
        this.setData({
          refresher: false,
          hideSkeleton: true
        })
      }
    } catch (e) {
      wx.stopPullDownRefresh()
      this.setData({
        loadEnd: true,
        refresher: false,
        hideSkeleton: true
      })
      console.error('axios error:', e)
    }
  },
  // 获取所有菜品
  getDishes() {
    return new Promise(async (resolve, reject) => {
      try {
        const {
          results: { foodDtoList, recommendFoodList, discountActBaseInfoRsp }
        } = await fhGetDishes()
        getApp().globalData.discountInfo = discountActBaseInfoRsp
        this.setData({
          foodDtoList,
          recommendFoodList
        })

        const mandatory = foodDtoList
          .filter(i => i.categoryType === 2)
          .map(i => i.categoryId)
        wx.$setGlobalData('mandatory', mandatory)

        resolve({ discountActBaseInfoRsp })
      } catch (e) {
        console.error('debug axios', e)
        reject(e)
      }
    })
  },
  // 获取门店信息
  getStoreInfo() {
    return new Promise(async (resolve, reject) => {
      try {
        const latitude = wx.getStorageSync('latitude')
        const longitude = wx.getStorageSync('longitude')
        // 处理门店信息
        const { results: storeInfo } = await fhGetStoreInfo({
          latitude,
          longitude
        })
        this.setData(
          {
            storeInfo,
            loadEnd: true
          },
          () => {
            this.setScrollHeight()
          }
        )
        resolve(storeInfo)
      } catch (e) {
        console.error('debug axios', e)
        reject(e)
      }
    })
  },
  // 轮播图
  async getStoreBanners() {
    try {
      // 处理轮播图
      const { results: banners } = await fhGetStoreBanners()
      this.setData({
        banners
      })
    } catch (e) {
      console.error('debug axios', e)
    }
  },
  // 满减活动
  fhGetReductions() {
    return new Promise(async (resolve, reject) => {
      try {
        // 处理满减活动
        const { results: reductions } = await fhGetReductions()
        this.setData({
          overflowReduction: reductions
        })
        resolve({ reductions })
      } catch (e) {
        console.error('debug axios', e)
        reject(e)
      }
    })
  },
  // 门店顶部背景图
  async getStoreSignboard() {
    try {
      const merchantId = this.merchantId
      // 门店背景图
      let { results: tempSignboard } = await fhGetStoreSignboard({
        merchantId
      })
      const { imageUrl, upStatus } = tempSignboard || {}
      const signboard = {
        imageUrl:
          upStatus && imageUrl
            ? imageUrl
            : 'https://ybm-public.oss-cn-beijing.aliyuncs.com/image/zpbackground.jpg'
      }
      this.setData({
        signboard
      })
    } catch (e) {
      console.error('debug axios', e)
    }
  },
  // 配送费减免
  getReduceDelivery() {
    return new Promise(async (resolve, reject) => {
      try {
        // 配送费减免
        const { results: reduceDelivery } = await fhGetReduceDelivery()
        this.setData({
          reduceDelivery
        })
        resolve({ reduceDelivery })
      } catch (e) {
        console.error('debug axios', e)
        reject(e)
      }
    })
  },
  // 分类是否进入检测区域
  detectCate() {
    if (!this.hadReactObserver) {
      const intersectionObserver = this.createIntersectionObserver({
        observeAll: true
      }).relativeTo('#detect-box')

      intersectionObserver.observe('.dish-cate', res => {
        if (this.clickCateIng) return
        const { currCate } = this.data
        const { intersectionRatio, dataset } = res
        const { cateId } = dataset
        const key = `cate-${cateId}`
        if (intersectionRatio > 0 && currCate !== key) {
          this.setData({
            currCate: key
          })
        }
      })
    }

    this.hadReactObserver = true
  },
  // 点击左侧菜单分类
  clickCate({ currentTarget: { dataset } }) {
    const { currCate } = this.data
    const { cateId } = dataset
    const key = `cate-${cateId}`
    const dishKey = `dish-cate-${cateId}`
    if (key !== currCate) {
      this.clickCateTimer && clearTimeout(this.clickCateTimer)
      this.clickCateIng = true
      this.setData(
        {
          currCate: key,
          scrollToCate: dishKey
        },
        () => {
          this.clickCateTimer = setTimeout(() => {
            this.clickCateIng = false
          }, 800)
        }
      )
    }
  },
  // 处理分类相关信道消息
  handleCateNum({ key, number: rawNumber, storeFoodId }) {
    const { cateNums } = this.data
    const cateFoods = cateNums[key] || {}
    let number = 0
    cateFoods[storeFoodId] = rawNumber
    for (let i in cateFoods) {
      if (i === 'number') continue
      number += cateFoods[i]
    }
    cateFoods.number = number

    this.setData({
      [`cateNums.${key}`]: cateFoods
    })
  },
  // 清空购物车回调
  handlerClearCart() {
    this.setData({
      cateNums: {}
    })
  },
  // 处理购物车的展示和隐藏
  handleCartDisplay({ show }) {
    setTimeout(() => {
      this.setScrollHeight()
    }, 400)
  },
  // 点击轮播图
  clickBanner({ currentTarget: { dataset } }) {
    const { image, id, type, foodId, foodInfo } = dataset
    type === 2 &&
      wx.navigateTo({
        url: `/package/bannerfood/bannerfood?img=${image}&bannerid=${id}&uidata=${JSON.stringify(
          {}
        )}`
      })

    type === 1 && this.bannerDetail(foodId, foodInfo)
  },
  // 轮播图展示菜品详情
  async bannerDetail(id, foodInfo = []) {
    try {
      const { results } = await fhGetSku(id)
      let { sku = [], attribute = [] } = results || {}
      let flag = false
      let tempKey = null

      if (this.tempPreferentialFoodSkuId) {
        sku = this.preferential(sku, foodInfo)
        if (attribute && attribute.length < 1) {
          tempKey = constructorDishUuid(sku[0], '')
          flag = true
        }
        this.from = null
      }

      // 计算所有sku的总库存
      const allStock = sku.map(i => i.stock || 0).reduce((acc, cv) => acc + cv)
      const sellerOut = allStock < 1

      if (sku[0]) {
        const detail = {
          ...results,
          ...foodInfo[0],
          ...sku[0],
          storeFoodSkuDtoList: sku,
          sellerOut,
          allStock
        }
        flag
          ? (() => {
              controlNumber(
                {
                  detail: {
                    ...detail,
                    number: 0
                  },
                  key: tempKey
                },
                {
                  isAdd: true
                }
              )

              wx.nextTick(() => {
                this.dishCart.onUnfold()
              })
            })()
          : bus.emit('showDishDetail', { show: true, detail })
      }
    } catch (e) {
      console.error(e)
    }
  },
  // 跳转到搜索页
  navToSearch() {
    wx.navigateTo({
      url: `/package/dishsearch/dishsearch?uidata=${JSON.stringify({})}`
    })
  },
  // 设置本地购物车
  setGlobalData() {
    if (!this.dishCart) return

    const { cartDishes } = this.dishCart.data

    const res = []
    for (let i in cartDishes) {
      const { number, attributeText, normalNumber } = cartDishes[i]
      cartDishes[i].num = number
      cartDishes[i].commonNum = normalNumber
      cartDishes[i].arraylisting = (attributeText || '').split(',')

      res.push(cartDishes[i])
    }

    setShoppingCart(this.cartKey, res)
    wx.$setGlobalData('boughtDiscountDishes', {})
    wx.$setGlobalData('discountInfo', {})
    wx.setStorageSync('drainage', null)
  },
  // 特惠套餐的处理
  preferential(sku, foodInfo) {
    let res = null
    for (let i = 0; i < sku.length; i++) {
      const { id } = sku[i]
      if (id === this.tempPreferentialFoodSkuId) {
        const tempSku = sku.splice(i, 1)[0]
        const { discount, foodName } = foodInfo[0]
        if (tempSku)
          res = [
            {
              ...tempSku,
              ...foodInfo[0],
              name: foodName,
              discountPrice: discount,
              categoryId: -2
            }
          ]
        break
      }
    }
    return res
  }
}

Page(pageOptions)
