const {
  fhGetStoreInfo
} = require('../../../api/store/index')
const {
  fhGetWeekDays,
  fhGetMeals
} = require('../../../api/week/index')
const {
  fhGetCartAll,
  fhDeleteCartAll
} = require('../../../api/cart/index')
const {
  conversion,
  getShoppingCart
} = require('../../../utils/week-index')
const {
  publishShoppingCart
} = require('../../_utils/week-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: 'RIQI'
      }
    ],
    // 当前选中的菜单
    currMenu: 'RIQI',
    // 当前选中的菜单索引
    currMenuIndex: 0,
    // 日期列表
    dateList: [],
    // 当前高亮的星期和日期
    currWeek: '',
    currDay: '',
    // 所有餐次
    mealList: [],
    // 当天可选餐次
    currMealList: [],
    // 当周所有餐次餐品列表
    allFoodList: [],
    // 当前日期所有餐次餐品列表
    currFoodList: [],
    // 菜品总数
    showTotalFood: 0,
    // 餐次总数
    showTotalMeal: 0,
    // 天总数
    showTotalDay: 0,
    // 餐品总价
    showTotalPrice: 0,
    // 购物车中的额外信息
    cartExtraInfo: {},
    // 分类数量相关
    cateNums: {},
    // 门店招牌
    signboard: {},
    // 是否开始下拉刷新
    refresher: false
  },
  // 页面载入时
  onLoad(e) {
    this.init(e)
  },
  // 页面初始化
  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))

    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() {
  },
  // 页面卸载时
  onUnload() {
  },
  // 下拉页面时
  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()
    // storeType !== 2 && this.initCartData()
    this.setData({
      refresher: false,
      hideSkeleton: true,
      isFirstOnShow: false
    })
  },
  // 初始化购物车
  async initCartData() {
    let showTotalFood = 0
    let showTotalMeal = 0
    let showTotalDay = 0
    let showTotalPrice = 0
    const memberId = wx.getStorageSync("memberId")
    const { results } = await fhGetCartAll(memberId)
    // if (results.length < 1) return
    results.forEach(dateItem => {
      showTotalDay++
      dateItem.shitangWeekMealsDtoList.forEach(mealItem => {
        showTotalMeal++
        mealItem.foodDtoList.forEach(foodItem => {
          // const key = foodItem.cartFoodCategoryName
          foodItem = conversion(foodItem.cartFoodDto)
          // publishShoppingCart(key, foodItem, foodItem.number)
          showTotalFood += foodItem.number
          showTotalPrice += foodItem.price * foodItem.number + (foodItem.packagePrice || 0) * foodItem.number
        })
      })
    })
    this.setData({
      allFoodList: results,
      showTotalFood,
      showTotalMeal,
      showTotalDay,
      showTotalPrice: showTotalPrice.toFixed(2)
    })
    return results
  },
  // 设置底部滑动区域的高度
  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)
    }
  },
  // 下拉刷新
  refresherEvent() {
    this.setData(
      {
        refresher: true
      },
      () => {
        this.getDatas()
      }
    )
  },
  // 获取首页的所有数据
  async getDatas() {
    this.setData({
      loadEnd: false,
      hideSkeleton: false
    })

    try {
      const storeInfo = await this.getStoreInfo()
      await this.initCartData()
      await this.getMeals()
      await this.getWeekDays()
      this.setActivedDate()

      const { deliveryPrice, storeOperatingStatus, startSalePrice } = storeInfo

      const cartExtraInfo = {
        deliveryPrice,
        storeOperatingStatus,
        startSalePrice
      }
      this.setData({
        cartExtraInfo
      })

      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)
    }
  },
  // 获取一周日期
  getWeekDays() {
    return new Promise(async (resolve, reject) => {
      try {
        const { results } = await fhGetWeekDays()
        const dateList = results.map(item => {
          let number = 0
          const currFoodList = this.getCurrFoodList(item.day)
          if (currFoodList.length) {
            currFoodList.map(currItem => {
              currItem.map(currFoodItem => {
                currFoodItem.foodDtoList.map(currMealFoodItem => {
                  return number += currMealFoodItem.cartFoodDto.cartNum
                })
              })
            })
          }
          const { forwardDays } = this.data.storeInfo
          const disabled = this.getDisabledDate(item.day, forwardDays)
          return {
            day: item.day,
            week: item.week,
            number,
            disabled
          }
        })
        console.log(dateList)
        this.setData({
          dateList
        })
        resolve({ results })
      } catch (e) {
        console.error('debug axios', e)
        reject(e)
      }
    })
  },
  getDisabledDate(day, forwardDays) {
    let currentDate = new Date()
    currentDate = new Date(currentDate.toLocaleDateString())
    let itemDate = new Date(day)
    itemDate = new Date(itemDate.toLocaleDateString())
    const num = (itemDate.getTime() - currentDate.getTime()) / (1000 * 60 * 60 * 24)
    return num < forwardDays
  },
  setActivedDate() {
    const activeDate = this.data.dateList.find(item => !item.disabled)
    const event = { currentTarget: { dataset: activeDate } }
    this.clickCate(event)
  },
  // 获取所有餐次
  getMeals() {
    return new Promise(async (resolve, reject) => {
      try {
        const { results } = await fhGetMeals()
        this.setData({
          mealList: results
        })
        resolve({ results })
      } catch (e) {
        console.error('debug axios', e)
        reject(e)
      }
    })
  },
  getCurrMealList() {
    const { forwardDays, forwardHours } = this.data.storeInfo
    const currentTime = new Date()
    const dateStr = currentTime.toLocaleDateString()
    const currentDate = new Date(dateStr)
    const currDate = new Date(this.data.currDay.replace(/-/g, '/'))
    let currMealList = []
    if (forwardDays === 0 && currDate.getTime() === currentDate.getTime()) {
      currMealList = this.data.mealList.filter(item => {
        const startDiningTime = new Date(`${dateStr} ${item.startDiningTime}`)
        startDiningTime.setHours(startDiningTime.getHours() - forwardHours)
        return currentTime.getTime() < startDiningTime.getTime()
      })
    } else {
      currMealList = this.data.mealList
    }
    this.setData({
      currMealList
    })
  },
  // 获取门店信息
  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)
      }
    })
  },
  // 分类是否进入检测区域
  detectCate() {
    if (!this.hadReactObserver) {
      const intersectionObserver = this.createIntersectionObserver({
        observeAll: true
      }).relativeTo('#detect-box')

      intersectionObserver.observe('.cates-item', async res => {
        if (this.clickCateIng) return
        // await this.initCartData()
        const { currDay } = this.data
        const { intersectionRatio, dataset } = res
        const { week, day } = dataset
        const key = day
        if (intersectionRatio > 0 && currDay !== key) {
          this.setData({
            currWeek: week,
            currDay: key,
            currFoodList: this.getCurrFoodList(key)
          })
        }
      })
    }

    this.hadReactObserver = true
  },
  // 点击左侧菜单分类
  clickCate({ currentTarget: { dataset } }) {
    const { week, day, disabled } = dataset
    if (disabled) {
      return
    }
    const { currDay } = this.data
    const key = day
    if (key !== currDay) {
      this.clickCateTimer && clearTimeout(this.clickCateTimer)
      this.clickCateIng = true
      this.setData(
        {
          currWeek: week,
          currDay: key,
          currFoodList: this.getCurrFoodList(key)
        },
        () => {
          this.clickCateTimer = setTimeout(() => {
            this.clickCateIng = false
          }, 800)
        }
      )
      this.getCurrMealList()
    }
  },
  getCurrFoodList(day) {
    return this.data.allFoodList.filter(dayFoodList => dayFoodList.date === day).map(mealFoodList => mealFoodList.shitangWeekMealsDtoList)
  },
  // 去结算
  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/week-affirm/affirm?storeid=' +
        storeid +
        '&currentflag=1' +
        '&addressflag=1'
    })
  },
  // 处理分类相关信道消息
  // 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
  //   })
  // },
  // 清空购物车回调
  async handlerClearCart() {
    // const memberId = wx.getStorageSync("memberId")
    // await fhDeleteCartAll(memberId)
    this.setData({
      cateNums: {}
    })
  },
  // 处理购物车的展示和隐藏
  // handleCartDisplay({ show }) {
  //   setTimeout(() => {
  //     this.setScrollHeight()
  //   }, 400)
  // },
  // 跳转到菜品页
  jumpWeekLunch({ detail: { value } }) {
    wx.navigateTo({
      url: `/store/pages/week-lunch/index?day=${this.data.currDay}&mealsId=${this.data.currMealList[value].id}`
    })
  }
}

Page(pageOptions)
