// pages/basket/basket.js
var http = require("../../utils/http.js");
var util = require("../../utils/util.js");
const Big = require("../../utils/big.min.js");

Page({

  /**
   * 页面的初始数据
   */
  data: {
    // picDomain: config.picDomain,
    shopCartOrders: [], //所有店铺的数据
    shopCartItemDiscounts: [],
    finalMoney: 0,
    totalMoney: 0,
    subtractMoney: 0,
    allChecked: true,
    hideModal: true, //模态框的状态  true-隐藏  false-显示
    hidePriModal: true, //金额明细模态框的状态  true-隐藏  false-显示
    animationData: {},
    prodDiscounts: [],
    discountid: -1,
    basketId: 0,
    toPayArray: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //加载购物车
    this.loadBasketData(null)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.setData({
      shopCartOrders: [],
    })
  },

  /**
   * 加载订单数据
   */
  loadBasketData(discountData) {
    var reqData = [];
    var shopCartIds = [];
    if (discountData) {
      reqData.push(discountData);
      this.data.shopCartOrders.forEach(shopCart => {
        shopCart.shopCartItemDiscounts.forEach(cItems => {
          cItems.shopCartItems.forEach(pItem => {
            if (pItem.checked) {
              shopCartIds.push(pItem.basketId);
            }
          })
        })
      })
    }
    //加载购物车
    var params = {
      url: "/p/shopCart/info",
      method: "POST",
      data: reqData,
      dontTrunLogin: true,
      callBack: res => {
        let img=''
        res.forEach(item=>{
          item.shopCartItemDiscounts.forEach(cart=>{
            cart.shopCartItems.map(e=>{
              img=e.pic.split(',')
              e.pic=img[0]
            })
          })
        })
        if (res.length > 0) {
          var shopCartOrders = res;
          if (shopCartIds.length == 0) { // 初始加载          
            this.setData({
              shopCartOrders: shopCartOrders,
            });
          } else { // 修改购物车
            var checkedLog = [] // 之前勾选的basketId数组
            this.data.shopCartOrders.forEach(shopCart => {
              shopCart.shopCartItemDiscounts.forEach(shopCartItemDiscount => {
                shopCartItemDiscount.shopCartItems.forEach(shopCartItem => {
                  if (shopCartItem.checked) {
                    checkedLog.push(shopCartItem.basketId)
                  }
                })
              })
            })
            shopCartOrders.forEach(newShopCart => {
              newShopCart.shopCartItemDiscounts.forEach(newShopCartItemDiscount => {
                newShopCartItemDiscount.shopCartItems.forEach(shopCartItem => {
                  if (checkedLog.includes(shopCartItem.basketId)) {
                    shopCartItem.checked = true
                  }
                })
              });
            })
            this.setData({
              shopCartOrders
            })
          }
        } else {
          this.setData({
            shopCartOrders: [],
          });
        }
        this.checkAllSelected()
        this.calTotalPrice(); //计算总价
      },
    };
    http.request(params);

    http.getCartCount(); //重新计算购物车总数量
  },


  /**
   * 去结算
   */
  toFirmOrder: function () {
    var shopCartOrders = this.data.shopCartOrders;
    var basketIds = [];
    let arr =[]
    shopCartOrders.forEach(shopCart => {
      var shopCartItemDiscounts = shopCart.shopCartItemDiscounts;
      shopCartItemDiscounts.forEach(shopCartItemDiscount => {
        shopCartItemDiscount.shopCartItems.forEach(shopCartItem => {
          if (shopCartItem.checked) {
            arr.push({...shopCartItem})
            basketIds.push(shopCartItem.basketId)
          }
        })
      })
    })
    if (!basketIds.length) {
      wx.showToast({
        title: '请选择商品',
        icon: "none"
      })
      return
    }
    const result =arr.every(item => item.shopId === arr[0].shopId);
    console.log(result);
    if (result==false) {
      wx.showToast({
        title: '多个门店不可同时结算~',
        icon: "none"
      })
      return
    }
    wx.setStorageSync("basketIds", JSON.stringify(basketIds));
    wx.navigateTo({
      url: '/pages/submit-order/submit-order?orderEntry=0',
    })
  },

  /**
   * 全选
   */
  onSelAll: function () {
    var allChecked = this.data.allChecked;
    allChecked = !allChecked; //改变状态
    var shopCartOrders = this.data.shopCartOrders;
    if (allChecked) {
      this.setData({
        toPayArray: shopCartOrders
      })
    } else {
      this.setData({
        toPayArray: []
      })
    }
    shopCartOrders.forEach(shopCart => {
      shopCart.checked = allChecked;
      var shopCartItemDiscounts = shopCart.shopCartItemDiscounts;

      for (var i = 0; i < shopCartItemDiscounts.length; i++) {
        var cItems = shopCartItemDiscounts[i].shopCartItems;
        for (var j = 0; j < cItems.length; j++) {
          cItems[j].checked = allChecked;
        }
      }

    })

    this.setData({
      allChecked: allChecked,
      shopCartOrders: shopCartOrders
    });
    this.calTotalPrice(); //计算总价
  },

  /**
   * 每一项的选择事件
   */
  onSelectedItem: function (e) {
    var index = e.currentTarget.dataset.index; // 获取data- 传进来的index
    var scindex = e.currentTarget.dataset.scindex;
    var topindex = e.currentTarget.dataset.topindex;

    var shopCartOrders = this.data.shopCartOrders;
    var shopCartItemDiscounts = shopCartOrders[topindex].shopCartItemDiscounts; // 获取购物车列表
    var checked = shopCartItemDiscounts[scindex].shopCartItems[index].checked; // 获取当前商品的选中状态
    shopCartItemDiscounts[scindex].shopCartItems[index].checked = !checked; // 改变状态
    this.setData({
      shopCartOrders: shopCartOrders
    });
    this.checkAllSelected(); //检查全选状态
    this.calTotalPrice(); //计算总价
  },

  /**
   * 每一个店铺的选择
   */
  onSelectedShopItem: function (e) {
    let arr=[]
    var topindex = e.currentTarget.dataset.topindex;
    var shopCartOrders = this.data.shopCartOrders;
    var checked = shopCartOrders[topindex].checked; // 获取当前商品的选中状态
    shopCartOrders[topindex].checked = !checked; // 改变状态
    if (shopCartOrders[topindex].checked) {
      arr.push({...e})
      this.setData({
        toPayArray:arr
      })
    }else{
      this.setData({
        toPayArray:[]
      })
    }
    shopCartOrders[topindex].shopCartItemDiscounts.forEach(shopCartItem => {
      var cItems = shopCartItem.shopCartItems;
      for (var j = 0; j < cItems.length; j++) {
        cItems[j].checked = !checked;
      }
    })
    this.setData({
      shopCartOrders: shopCartOrders
    });
    this.checkAllSelected(); //检查全选状态
    this.calTotalPrice(); //计算总价
  },

  /**
   * 检查全选状态
   */
  checkAllSelected: function () {
    var allChecked = true;
    var shopCartOrders = this.data.shopCartOrders;
    var flag = false;
    shopCartOrders.forEach(shopCart => {
      var shopChecked = true;
      var shopCartItemDiscounts = shopCart.shopCartItemDiscounts;
      for (var i = 0; i < shopCartItemDiscounts.length; i++) {
        var cItems = shopCartItemDiscounts[i].shopCartItems;
        for (var j = 0; j < cItems.length; j++) {
          if (!cItems[j].checked) {
            shopChecked = false;
            allChecked = false;
            flag = true;
            break;
          }
        }
        if (flag) {
          break;
        }
      }
      shopCart.checked = shopChecked;
    })
    this.setData({
      allChecked: allChecked,
      shopCartOrders: shopCartOrders
    });
  },

  /**
   * 计算购物车总额
   */
  calTotalPrice: function () {
    var shopCartOrders = this.data.shopCartOrders;
    var shopCartIds = [];
    shopCartOrders.forEach(shopCart => {
      var shopCartItemDiscounts = shopCart.shopCartItemDiscounts;
      for (var i = 0; i < shopCartItemDiscounts.length; i++) {
        var cItems = shopCartItemDiscounts[i].shopCartItems;
        for (var j = 0; j < cItems.length; j++) {
          if (cItems[j].checked) {
            shopCartIds.push(cItems[j].basketId);
          }
        }
      }
    });

    var ths = this;
    wx.showLoading();
    var params = {
      url: "/p/shopCart/totalPay",
      method: "POST",
      data: shopCartIds,
      callBack: function (res) {
        ths.setData({
          finalMoney: res.finalMoney,
          totalMoney: res.totalMoney,
          subtractMoney: res.subtractMoney
        });
        wx.hideLoading();
      }
    };
    http.request(params);

  },

  /**
   * 减少数量
   */
  onCountMinus: function (e) {
    var index = e.currentTarget.dataset.index;
    var scindex = e.currentTarget.dataset.scindex;
    var topindex = e.currentTarget.dataset.topindex;

    var shopCartOrders = this.data.shopCartOrders;
    var shopCartItemDiscounts = shopCartOrders[topindex].shopCartItemDiscounts;
    var prodCount = shopCartItemDiscounts[scindex].shopCartItems[index].prodCount;
    if (prodCount > 1) {
      this.updateCount(shopCartOrders, topindex, scindex, index, -1);
    }
  },

  /**
   * 增加数量
   */
  onCountPlus: function (e) {
    var index = e.currentTarget.dataset.index;
    var scindex = e.currentTarget.dataset.scindex;
    var topindex = e.currentTarget.dataset.topindex;

    var shopCartOrders = this.data.shopCartOrders;

    this.updateCount(shopCartOrders, topindex, scindex, index, 1);
  },


  /**
   * 改变购物车数量接口
   */
  updateCount: function (shopCartOrders, topindex, scindex, index, prodCount) {
    var shopCartItemDiscounts = shopCartOrders[topindex].shopCartItemDiscounts;
    var ths = this;
    wx.showLoading({
      mask: true
    });
    var params = {
      url: "/p/shopCart/changeItem",
      method: "POST",
      data: {
        count: prodCount,
        prodId: shopCartItemDiscounts[scindex].shopCartItems[index].prodId,
        skuId: shopCartItemDiscounts[scindex].shopCartItems[index].skuId,
        shopId: shopCartItemDiscounts[scindex].shopCartItems[index].shopId
      },
      callBack: function (res) {
        shopCartItemDiscounts[scindex].shopCartItems[index].prodCount += prodCount;
        ths.setData({
          shopCartOrders: shopCartOrders
        });
        var discountData = {
          basketId: shopCartItemDiscounts[scindex].shopCartItems[index].basketId,
          discountId: shopCartItemDiscounts[scindex].shopCartItems[index].discountId
        }
        ths.loadBasketData(discountData)
        wx.hideLoading();
      }
    };
    http.request(params);
  },

  /**
   * 删除购物车商品
   */
  onDelBasket: function () {
    var ths = this;
    var shopCartOrders = this.data.shopCartOrders;
    var basketIds = [];
    shopCartOrders.forEach(shopCart => {
      var shopCartItemDiscounts = shopCart.shopCartItemDiscounts;
      for (var i = 0; i < shopCartItemDiscounts.length; i++) {
        var cItems = shopCartItemDiscounts[i].shopCartItems;
        for (var j = 0; j < cItems.length; j++) {
          if (cItems[j].checked) {
            basketIds.push(cItems[j].basketId);
          }
        }
      }
    })

    if (basketIds.length == 0) {
      wx.showToast({
        title: '请选择商品',
        icon: "none"
      })
    } else {
      wx.showModal({
        title: '',
        content: '确认要删除选中的商品吗？',
        confirmColor: "#eb2444",
        success(res) {
          if (res.confirm) {

            wx.showLoading({
              mask: true
            });
            var params = {
              url: "/p/shopCart/deleteItem",
              method: "DELETE",
              data: basketIds,
              callBack: function (res) {
                wx.hideLoading();
                ths.onShow();
              }
            };
            http.request(params);
          }
        }
      })
    }


  },

  /**
   * 点击满减活动 弹窗
   */
  onChooseDiscount: function (e) {
    var that = this;
    var basketId = e.currentTarget.dataset.basketid
    var discounts = e.currentTarget.dataset.discounts
    var discountid = e.currentTarget.dataset.discountid
    this.setData({
      prodDiscounts: discounts,
      hideModal: false,
      discountid: discountid,
      basketId: basketId
    });

    var animation = wx.createAnimation({
      duration: 500,
      timingFunction: 'ease',
    })
    this.animation = animation
    setTimeout(function () {
      that.fadeIn();
    }, 100)
  },

  radioChange(e) {
    this.loadBasketData({
      basketId: this.data.basketId,
      discountId: e.detail.value
    });
    this.setData({
      hideModal: true
    });
  },

  // 隐藏遮罩层
  hideModal: function () {
    var that = this;
    var animation = wx.createAnimation({
      duration: 600,
      timingFunction: 'ease',
    })
    this.animation = animation
    that.fadeDown();
    setTimeout(function () {
      that.setData({
        hideModal: true
      })
    }, 500)

  },

  //动画集
  fadeIn: function () {
    this.animation.translateY(0).step()
    this.setData({
      animationData: this.animation.export() //动画实例的export方法导出动画数据传递给组件的animation属性
    })
  },
  fadeDown: function () {
    this.animation.translateY(300).step()
    this.setData({
      animationData: this.animation.export(),
    })
  },

  /**
   * 跳转到商品详情`
   */
  toProdPage(e) {
    wx.navigateTo({
      url: '/pages/prod/prod?prodid=' + e.currentTarget.dataset.prodid,
    })
  },


  /**
   * 金额明细弹窗
   */
  showPriDet() {
    var that = this;
    if (this.data.hidePriModal == true) {
      this.setData({
        hidePriModal: false
      })
      var animation = wx.createAnimation({
        duration: 500,
        timingFunction: 'ease',
      })
      this.animation = animation
      setTimeout(function () {
        that.fadeIn();
      }, 100)
    } else if (this.data.hidePriModal == false) {
      this.hidePriModal()
    }
  },

  hidePriModal() {
    var that = this;
    var animation = wx.createAnimation({
      duration: 800,
      timingFunction: 'ease',
    })
    this.animation = animation
    that.fadeDown();
    setTimeout(function () {
      that.setData({
        hidePriModal: true
      })
    }, 680)
  },



})