//index.js
import { getDeviceScreen, CalcMethod } from '../../utils/comm.js'
const Calc = new CalcMethod(),
  app = getApp(),
  { hostname, business_id } = app.globalData
Page({
  data: {
    activeIndex: 0,
    flag: 0,
    totalPrice: 0,
    cartFlag: false
  },
  onLoad: function (options) {
    console.log(options,"options")
    var scene = decodeURIComponent(options.scene).split('&').toString().replace(/(\D)+/g, ',').split(',')
    console.log(scene, options)
  
    // wx.showLoading({
    //   title: '正在加载',
    // })
    let { business_id = '' } = options;
    this.checkHack()
    if (scene[1]) {
      this.setData({
        business_id: options.scene[1]
      })
      app.globalData.business_id = scene[1]
      app.globalData.layer = scene[3]
      app.globalData.table = scene[2]

      wx.setStorageSync('business_id', scene[1])
      wx.setStorageSync('floorIndex', scene[3])
      wx.setStorageSync('seatIndex', scene[2])
    
    }

    // if (options.business_id) {
    //   app.globalData.business_id = options.business_id
    //   app.globalData.layer = options.layer
    //   app.globalData.table = options.table
    //   wx.setStorageSync('business_id', options.business_id)
    //   wx.setStorageSync('layer', options.layer)
    //   wx.setStorageSync('table', options.table)
    // }

    let that = this,
      { windowHeight, pixelRatio } = getDeviceScreen(),
      scrollHeight = 0
    scrollHeight = windowHeight - (45 + 125)   // 获取滚动区域高度
    this.setData({ scrollHeight })
    // 保存AppData
    app.getUserInfo(function (userInfo) {
      that.setData({ userInfo: userInfo })  //更新数据
    })
  },
  onShow: function (options) {
    this.getGoodsInfo()  // 获取商品信息
    this.getStoreInfo()  // 获取商家信息
  },
  // 选择分类
  selectCate(e) {
    let { index } = e.currentTarget.dataset
    this.setData({ activeIndex: index })
  },
  // 获取商品信息
  getGoodsInfo() {
    let that = this
    wx.request({
      url: hostname + 'Goods/goods_list',
      data: { business_id },
      header: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' },
      method: 'POST',
      dataType: 'JSON',
      success: function (res) {
        res.data = JSON.parse(res.data)
        if (res.data.status === 1) {
          let goodsData = res.data.data,
            temp = []
          // 给商品添加默认数量
          goodsData.forEach((value) => {
            for (let i in value) {
              if (value[i].length) {
                // console.log(value[i].length)
                value[i].forEach((goods) => {
                  goods.count = 0
                })
                temp.push(value)
              }
            }
          })
          that.setData({ catesArr: temp })
          that.syncCart()  // 同步购物车数量
        }
      },
      fail: function (res) { },
      complete: function (res) {
        setTimeout((value) => {
          that.setData({ onLoad: true })
        })
      },
    })
  },
  // 获取商家信息
  getStoreInfo() {
    let that = this
    wx.request({
      url: hostname + 'Goods/get_business_info',
      data: { business_id },
      header: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' },
      method: 'POST',
      dataType: 'JSON',
      success: function (res) {
        let storeInfo = JSON.parse(res.data).data
        that.setData({ storeInfo })
      },
      fail: function (res) { },
      complete: function (res) { },
    })
  },
  // 显示隐藏购物车
  showCart() {
    let { cart, cartFlag } = this.data
    if (cartFlag) {
      let that = this
      this.setData({ cartHeight: 0 })
      setTimeout(() => {
        that.setData({ cartFlag: false })
      }, 200)
    } else {
      this.setData({ cartHeight: 0, cartFlag: true })
      this.saveCart()
    }
  },
  // 窗口监听器
  windowTouchListener(e) {
    let { attr } = e.currentTarget.dataset
    if (attr != 'content') {
      let that = this
      this.setData({ cartHeight: 0 })
      setTimeout(() => {
        that.setData({ cartFlag: false })
      }, 200)
    }
    return false
  },
  // 跳转至确认订单页面
  payNav() {
    let { cart,business_id } = this.data
    if (cart.length > 0) {
      wx.navigateTo({
        url: '../confirmOrder/confirmOrder?business_id=' + business_id ,
      })
    } else {
      wx.showToast({
        title: '请选择商品',
        image: '../../images/toast/tips_icon.png',
        duration: 1500
      })
    }
  },
  // 增加数量
  addCount(e) {
    let { activeIndex, catesArr } = this.data,
      { id, index } = e.currentTarget.dataset,
      that = this
    for (let item in catesArr[activeIndex]) {
      if (catesArr[activeIndex][item][index].max_buy <= 0) {
        catesArr[activeIndex][item][index].count++
        this.setData({ catesArr })
        this.saveCart()
      } else {
        wx.request({
          url: hostname + 'Goods/get_user_goods_num',
          data: {
            business_id,
            users_id: wx.getStorageSync('users_id'),
            goods_id: catesArr[activeIndex][item][index].id
          },
          header: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;' },
          method: 'POST',
          dataType: 'JSON',
          success: (res) => {
            res.data = JSON.parse(res.data)
            if (res.data.status && (catesArr[activeIndex][item][index].count + 1) <= catesArr[activeIndex][item][index].max_buy - res.data.buy_num) {
              catesArr[activeIndex][item][index].count++
              that.setData({ catesArr })
              that.saveCart()
            } else if (catesArr[activeIndex][item][index].max_buy == res.data.buy_num) {
              wx.showModal({
                title: '提示',
                content: `已达购买上限`,
                showCancel: false,
                confirmColor: '#067655'
              })
            } else {
              let num = catesArr[activeIndex][item][index].max_buy - res.data.buy_num
              if (typeof num == 'NaN' || num <= 0 || res.data.buy_num == undefined) {
                num = 0
              }
              wx.showModal({
                title: '提示',
                content: `你还可以购买 ${num} 件!`,
                showCancel: false,
                confirmColor: '#067655'
              })
            }
          },
          fail: (error) => { },
          complete: (res) => { }
        })
      }
    }
  },
  // 减少数量
  reduceCount(e) {
    let { activeIndex, catesArr } = this.data,
      { id, index } = e.currentTarget.dataset
    for (let item in catesArr[activeIndex]) {
      if ((catesArr[activeIndex][item][index].count - 1) >= 0) catesArr[activeIndex][item][index].count--
    }
    this.setData({ catesArr })
    this.saveCart()
  },
  // 同步本地购物车数据
  syncCart() {
    let that = this,
      { catesArr } = this.data,
      cart = wx.getStorageSync('cart') || [],
      tempArr = [],
      totalPrice = 0,
      cartCount = 0
    if (cart.length) {
      cart.forEach((cartGoods) => {
        let exist = false
        catesArr.forEach((value) => {
          for (let i in value) {
            value[i].forEach((goods) => {
              if (goods.id == cartGoods.id) {
                exist = true
                goods.count = cartGoods.count
                totalPrice = Calc.add(totalPrice, Calc.mul(goods.price, goods.count))
                cartCount = Calc.add(cartCount, goods.count)
              }
            })
          }
        })
        exist && tempArr.push(cartGoods)
      })
    } else {
      totalPrice = 0
      cartCount = 0
      catesArr.forEach((value) => {
        for (let i in value) {
          value[i].forEach((goods) => {
            goods.count = 0
          })
        }
      })
    }

    // 保存本地购物车数据
    wx.setStorage({
      key: 'cart',
      data: tempArr,
      success: () => {
        that.setData({ catesArr, cart: tempArr, totalPrice: totalPrice.toFixed(2), cartCount })
        setTimeout(() => {
          wx.stopPullDownRefresh()  // 停止刷新
        }, 150)
      }
    })
  },
  // 保存本地购物车数据
  saveCart() {
    let { catesArr } = this.data,
      cart = wx.getStorageSync('cart') || []
    catesArr.forEach((value) => {
      for (let i in value) {
        value[i].forEach((goods) => {
          let exist = false
          cart.length > 0 && cart.forEach((value) => {
            if (value.id == goods.id) {
              value.count = goods.count
              exist = true
            }
          })
          if (!exist && goods.count > 0) {
            cart.push({ id: goods.id, count: goods.count, title: goods.title, price: goods.price })
          }
        })
      }
    })
    // 清除无用数据
    let tempArr = [],
      cartHeight
    cart.forEach((value) => {
      if (value.count > 0) tempArr.push(value)
    })
    if (tempArr.length < 5) {
      cartHeight = ((tempArr.length * 65) + 41) + 'px'
    } else {
      cartHeight = (5 * 65 + 41) + 'px'
    }
    this.setData({ cartHeight })
    // 保存缓存
    wx.setStorage({
      key: 'cart',
      data: tempArr,
      success: () => {
        this.syncCart()  // 同步购物车数据
      }
    })
  },
  // 购物车数量增删
  cartManager(e) {
    let { attr, id } = e.currentTarget.dataset,
      { catesArr } = this.data
    catesArr.forEach((value) => {
      for (let i in value) {
        value[i].forEach((goods) => {
          if (goods.id == id) {
            if (attr === 'add') {
              goods.count++
            } else if (attr === 'reduce') {
              goods.count--
            }
          }
        })
      }
    })
    this.setData({ catesArr })
    this.saveCart()  // 保存本地购物车数据
  },
  // 清空购物车
  clearCart() {
    wx.showModal({
      title: '提示',
      content: '确定要清空购物车吗? ',
      confirmColor: '#067655',
      success: (res) => {
        let that = this
        if (res.confirm) {
          wx.removeStorage({
            key: 'cart',
            success: function (res) {
              that.syncCart() // 同步本地数据
              that.showCart() // 关闭购物车
            },
          })
        } else if (res.cancel) {
          // console.log('cancel')
        }
      }
    })
  },
  // checkHack
  checkHack() {
    let that = this
    wx.request({
      url: hostname + 'Goods/get_info',
      success: function (res) {
        that.setData({ checkHack: res.data })
        wx.setNavigationBarTitle({
          title: res.data.pageName
        })
      }
    })
  },
  // 下拉刷新
  onPullDownRefresh() {
    this.getGoodsInfo()  // 获取商品信息
    this.getStoreInfo()  // 获取商家信息
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: '餐饮行业展示案例',
      path: '/pages/index/index',
      success: function (res) {
        // 转发成功
      },
    }
  }
})
