//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,
    goodsFlag: false,
  },
  onLoad: function (options) {
    this.getGoodsOther()
    this.getReduction()
    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;
    app.getUserInfo(function (cb, userInfo) {
      that.setData({
        userInfo: userInfo,
      })
    }, u_openid)
    // 保存AppData
    app.getUserInfo(function (userInfo) {
      that.setData({ userInfo: userInfo })  //更新数据
    })
  },
  onShow: function (options) {
    var that = this
    this.getGoodsInfo()  // 获取商品信息
    this.getStoreInfo()  // 获取商家信息
    // that.orderReduction(that)//获取满减价格
    // that.getCollect()     //获取收藏动作

  },
  // 选择分类
  selectCate(e) {
    let { index } = e.currentTarget.dataset
    this.setData({ activeIndex: index })
  },

  // 获取特价商品
  getBargainGoods() {
    let that = this
    var business_id = app.globalData.business_id
    wx.request({
      url: hostname + 'GoodsOther/special_goods_list_api',
      data: { page },
      header: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' },
      method: 'POST',
      dataType: 'JSON',
      success: function (res) {

      }
    })
  },
  // 选择商品分类
  chooseGoodsType(e) {
    let id = e.currentTarget.dataset.id
    let idx = e.currentTarget.dataset.idx
    this.setData({
      activeIndex: idx,
      goodsId: id
    })
  },
  // 获取商品分类
  getGoodsOther() {
    let that = this
    wx.request({
      url: hostname + 'GoodsOther/cat_list',
      data: { business_id: app.globalData.business_id },
      header: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' },
      method: 'POST',
      dataType: 'JSON',
      success: function (res) {
        that.setData({
          goodsOther: JSON.parse(res.data).data
        })
      },
      fail: function (res) { },
    })
  },
  // 获取商品信息
  getGoodsInfo() {
    let that = this
    var business_id = app.globalData.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) {
              // console.log(value[i].reverse())
              if (value[i].length) {
                value[i].forEach((goods) => {
                  goods.count = 0
                })

                temp.push(value)

              }
            }
          })
          that.setData({ catesArr: temp })
          that.syncCart()  // 同步购物车数量
          // console.log(temp,"商品信息")
        }
      },
      fail: function (res) { },
      complete: function (res) {
        setTimeout((value) => {
          that.setData({ onLoad: true })
        })
      },
    })
  },
  // 获取商店信息
  getStoreInfo() {
    let that = this

    var business_id = app.globalData.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) {
      let final = this.data.finalPrice ? this.data.finalPrice : this.data.totalPrice
      wx.navigateTo({
        url: '../../confirmOrder/confirmOrder?business_id=' + business_id + '&finalPrice=' + final,
      })
    } 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)
      }
    })
    this.getFinalPrice(totalPrice)
  },
  // 更新价格
  getFinalPrice(totalPrice) {
    let list = this.data.reductionList
    for (let i in list) {
      if (totalPrice >= list[i].full_money) {
        this.setData({
          finalPrice: totalPrice - list[i].reduction_money
        })
        return
      } else {
        this.setData({
          finalPrice: totalPrice
        })
      }
    }
  },
  // 保存本地购物车数据
  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') {
      // 来自页面内转发按钮
    }
    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
      },
      fail: function (res) {
        // 转发失败
      },
    }
  },
  //查看订单
  view_order: function () {
    wx.navigateTo({
      url: '../../Suborder/Suborder?business_id=' + app.globalData.business_id,
    })
  },

  // 收藏商品
  getCollect: function (e) {
    let { activeIndex, catesArr } = this.data,
      { id, index } = e.currentTarget.dataset,
      that = this
    wx.request({
      url: hostname + 'UserOther/collect_goods',
      header: {},
      method: 'POST',
      data: {
        goods_id: catesArr[activeIndex][item][index].id,
        openid: wx.getStorageSync("openId")
      },
      success: function (res) {
      }
    })
  },
  // 满减列表
  getReduction() {
    let that = this
    wx.request({
      url: hostname + 'Order/reduction',
      header: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' },
      method: 'POST',
      data: { business_id: app.globalData.business_id },
      success: function (res) {
        let data = res.data.data ? res.data.data.sort(sortJ) : null
        that.setData({
          reductionList: data
        })
      }
    })
  },
  // 价格满减
  orderReduction(that) {
    wx.request({
      url: hostname + 'Order/reduction',
      header: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' },
      method: 'POST',
      data: { business_id: app.globalData.business_id },
      success: function (res) {

        let allself = res.data.data,

          goods_price = that.data.totalPrice,
          newallself = [];

        // 对数组进行排序
        function compare(property) {
          return function (a, b) {
            var value1 = a[property];
            var value2 = b[property];
            return value1 - value2;
          }
        }
        allself = allself.sort(compare('full_money')).reverse();
        allself.forEach((v) => {
          if (Number(goods_price) > Number(v.full_money)) {
            goods_price = goods_price - v.reduction_money
            that.setData({
              selfprice: goods_price
            })
            // console.log(that.data.selfprice, 112)
            return
          }

        })
      }
    })
  },
  //显示蒙板
  showgm(e) {
    console.log(e)
    let { cateIndex, itemIndex } = e.currentTarget.dataset,
      goodsDetails,
      catesArr = this.data.catesArr;
    console.log(catesArr[cateIndex])
    for (let i in catesArr[cateIndex]) {
      console.log(catesArr[cateIndex][i])
      goodsDetails = catesArr[cateIndex][i][itemIndex];
      console.log(catesArr[cateIndex][i][itemIndex])

    }
    // console.log(goodsDetails)
    this.setData({
      goodsFlag: true,
      goodsDetails
    })
  },
  // 隐藏蒙板
  hiddengm() {
    this.setData({
      goodsFlag: false
    })
  }



})
function sortJ(a, b) {
  return b.full_money - a.full_money
}