//index.js
import { getDeviceScreen, CalcMethod } from '../../utils/comm.js'
const Calc = new CalcMethod(),
  app = getApp(),
  { hostname } = app.globalData
Page({
  data: {
    activeIndex: 0,
    flag: 0,
    totalPrice: 0,
    cartFlag: false
  },
  onLoad: function (options) {
    console.log(options)

    this.checkHack()
    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 })
    // 传到授权登录接口
    var u_openid = options.u_openid;
    console.log(options)
    app.getUserInfo(function (cb, userInfo) {
      that.setData({
        userInfo: userInfo,
      })
    }, u_openid)
    // 保存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
    var business_id = app.globalData.business_id
    console.log(business_id)
    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) {
                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

    var business_id = app.globalData.business_id;
    console.log(business_id)
    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() {

    var business_id = app.globalData.business_id

    let { cart } = this.data
    if (cart.length > 0) {
      wx.navigateTo({
        url: '../confirm_appointment/confirm_appointment?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 {
        var business_id = app.globalData.business_id
        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) {
        }
      }
    })
  },
  // 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 (res) {
    var userid = wx.getStorageSync('openId')
    // var userid = 1

    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
    }
    return {
      title: app.globalData.share_title,
      path: '/pages/index/index?u_openid=' + userid,
      success: function (res) {
        var pages = getCurrentPages()    //获取加载的页面
        var currentPage = pages[pages.length - 1]    //获取当前页面的对象
        //点击分享传进userid 截取userid 从onload拿到
        var url = currentPage.route + '?u_openid=' + userid;  //当前页面url
        console.log(url, '/pages/index/index?u_openid=' + userid);
      },
      fail: function (res) {
        // 转发失败
      },
    }
  },
  //查看订单
  view_order: function () {
    console.log(app.globalData.business_id)
    wx.navigateTo({
      url: '../../Suborder/Suborder?business_id=' + app.globalData.business_id,
    })
  }
})
