var util = require('../../utils/util.js');
var goodsUtil = require('../../utils/goods.js');
var api = require('../../config/api.js');

var app = getApp();

Page({
  data: {
    cartGoods00: [], //保税仓数据
    cartGoods02: [], //保税展示数据
    cartGoods10: [], //现场速递数据
    cartGoods11: [], //普通商品
    cartGoods: [],
    validCartList: [],
    goodsBizTypeList: ['保税仓', '保税展示', '现场速递', '普通商品'],
    goodsBizType: '', //货品业务类型
    footprintList: [],
    cartTotal: {
      "goodsCount": 0,
      "goodsAmount": 0.00,
      "checkedGoodsCount": 0,
      "checkedGoodsAmount": 0.00
    },
    checkedAllStatus: true,
    checkedTypeStatus00: true,
    checkedTypeStatus02: true,
    checkedTypeStatus10: true,
    checkedTypeStatus11: true,
    couponInfoList: [],
    openAttr: false,
    specificationList: {},
    checkedSpecText: '请选择规格数量',
    number: 1,
    isAdd: true,
    mobile: '',
    retailPrice: '',
    stockNum: 0,
    cartNumber: 0,
    checkCart: app.globalData.appCheckCart,
    total00: 0,
    total11: 0,
    page: 1,
    size: 4
  },
  onLoad: function(options) {
    // 页面初始化 options为页面跳转所带来的参数
  },
  onReady: function() {
    // 页面渲染完成

  },
  onShow: function () {
    let that = this;
    that.setData({
      checkCart: app.globalData.appCheckCart
    });
    // 页面显示
    if (wx.getStorageSync('userInfo') || wx.getStorageSync('token')) {
      if (wx.getStorageSync('storeId')) {
        util.request(api.ChooseStoreId, {
          storeId: wx.getStorageSync('storeId'),
          merchSn: wx.getStorageSync('merchSn')
        }, 'POST').then(function (res) {
          if (res.errno === 0) {
            wx.setStorageSync('storeId', wx.getStorageSync('storeId'));
            wx.setStorageSync('merchSn', wx.getStorageSync('merchSn'));
            that.reLoad();
          }
        });
        that.setData({
          footprintList: [],
          page: 1
        });
        that.getCartList();
        that.getFootprintList();
      }
    } else {
      wx.navigateTo({
        url: '/pages/auth/btnAuth/btnAuth',
      })
    }
  },
  openSortFilter: function(event) {
    let that = this;
    let currentId = event.currentTarget.id;
    switch (currentId) {
      case 'defaultActivity':
        that.setData({
          'checkCart': '00',
          footprintList: [],
          page: 1
        });
        app.globalData.appCheckCart = '00';
        this.getCartList();
        this.getFootprintList();
        break;
      case 'ordActivity':
        that.setData({
          'checkCart': '11',
          footprintList: [],
          page: 1
        });
        app.globalData.appCheckCart = '11';
        this.getCartList();
        this.getFootprintList();
        break;
      default:
        //综合排序
        that.setData({
          'checkCart': '00',
          footprintList: [],
          page: 1
        });
        app.globalData.appCheckCart = '00';
        this.getCartList();
        this.getFootprintList();
    }
  },
  onHide: function() {
    // 页面隐藏

  },
  onUnload: function() {
    // 页面关闭

  },
  reLoad: function () {
    let that = this;
    if (wx.getStorageSync('storeId')) {
      if (wx.getStorageSync('userId')) {
        wx.request({
          url: api.updateLoginUser,
          data: {
            userId: wx.getStorageSync('userId'), storeId: wx.getStorageSync('storeId'), merchSn: wx.getStorageSync('merchSn')
          },
          method: 'POST',
          header: {
            'Content-Type': 'application/json'
          },
          success: function (wxRes) {
            if (wxRes.data.errno === 0) {
              // console.log("用户信息更新成功");
            }
          },
          fail: function (err) {
            console.log("failed");
          }
        });
      }
    }
  },
  setCommonData(res) {
    let that = this;
    that.setData({
      cartGoods: res.data.cartList,
      cartGoods00: res.data.cart00List,
      cartGoods02: res.data.cart02List,
      cartGoods10: res.data.cart10List,
      cartGoods11: res.data.cart11List,
      validCartList: res.data.validCartList,
      cartTotal: res.data.cartTotal,
      couponInfoList: res.data.couponInfoList,
      total00: res.data.total00,
      total11: res.data.total11
    });
  },
  setCheckedData() {
    let that = this;
    that.setData({
      checkedAllStatus: that.isCheckedAll(),
      checkedTypeStatus00: that.isCheckedTypeStatus00(),
      checkedTypeStatus02: that.isCheckedTypeStatus02(),
      checkedTypeStatus10: that.isCheckedTypeStatus10(),
      checkedTypeStatus11: that.isCheckedTypeStatus11()
    });
  },
  setCheckedAllData() {
    let that = this;
    that.setData({
      checkedAllStatus: that.isCheckedAll(),
      checkedTypeStatus00: that.isCheckedAll(),
      checkedTypeStatus02: that.isCheckedAll(),
      checkedTypeStatus10: that.isCheckedAll(),
      checkedTypeStatus11: that.isCheckedAll()
    });
  },
  getCartList: function() { //获取购物车数据
    let that = this;
    wx.showLoading({
      title: '加载中...',
    });
    console.log('分享的storeId' + wx.getStorageSync('storeId'))
    util.request(api.CartList, {
      checkCart: that.data.checkCart,
      storeId: wx.getStorageSync('storeId')
    }).then(function(res) {
      if (res.errno === 0) {
        that.setCommonData(res);
      }
      wx.hideLoading();
      //数据渲染选中
      that.setCheckedData();
    });
  },
  isCheckedAll: function() {
    //判断购物车所有商品是否已全选
    return this.data.cartGoods.every(function(element, index, array) {
      if (element.checked == true) {
        return true;
      } else {
        return false;
      }
    });
  },
  isCheckedTypeStatus00: function() {
    //判断该业务类型的购物车商品是否已全选
    return this.data.cartGoods00.every(function(element, index, array) {
      if (element.checked == true) {
        return true;
      } else {
        return false;
      }
    });
  },
  isCheckedTypeStatus02: function() {
    //判断该业务类型的购物车商品是否已全选
    return this.data.cartGoods02.every(function(element, index, array) {
      if (element.checked == true) {
        return true;
      } else {
        return false;
      }
    });
  },
  isCheckedTypeStatus10: function() {
    //判断该业务类型的购物车商品是否已全选
    return this.data.cartGoods10.every(function(element, index, array) {
      if (element.checked == true) {
        return true;
      } else {
        return false;
      }
    });
  },
  isCheckedTypeStatus11: function() {
    //判断该业务类型的购物车商品是否已全选
    return this.data.cartGoods11.every(function(element, index, array) {
      if (element.checked == true) {
        return true;
      } else {
        return false;
      }
    });
  },
  toIndexPage: function() {
    wx.switchTab({
      url: "/pages/index/index"
    });
  },
  checkedItem: function(event) {
    let itemIndex = event.target.dataset.itemIndex;
    let goodsBizType = event.target.dataset.goodsBizType;
    let goodsId = event.target.dataset.goodsId;
    let checked = event.target.dataset.checked;
    let that = this;
    // console.log(goodsBizType);
    // console.log(goodsId);
    // console.log(that.data.cartGoods[itemIndex].checked);
    util.request(api.CartChecked, {
      goodsIds: goodsId,
      isChecked: checked ? 0 : 1,
      checkCart: that.data.checkCart
    }, 'POST').then(function(res) {
      if (res.errno === 0) {
        that.setCommonData(res);
      }
      that.setCheckedData();
    });

  },
  getCheckedGoodsCount: function() {
    let checkedGoodsCount = 0;
    this.data.cartGoods.forEach(function(v) {
      if (v.checked === true) {
        checkedGoodsCount += v.number;
      }
    });
    return checkedGoodsCount;
  },
  checkedAll: function() {
    let that = this;
    var goodsIds = this.data.cartGoods.map(function(v) {
      return v.goodsIds;
    });
    util.request(api.CartChecked, {
      goodsIds: goodsIds.join(','),
      isChecked: that.isCheckedAll() ? 0 : 1
    }, 'POST').then(function(res) {
      if (res.errno === 0) {
        that.setCommonData(res);
      }
      that.setCheckedAllData();
    });
  },
  checkedAllGoodType: function(e) {
    let that = this;
    let goodsBizType = e.target.dataset.goodsBizType;
    let isCheckedTypeStatu;
    let checkCart;
    if (goodsBizType == '00') {
      isCheckedTypeStatu = that.isCheckedTypeStatus00();
      checkCart = '00';
    }
    if (goodsBizType == '02') {
      isCheckedTypeStatu = that.isCheckedTypeStatus02();
      checkCart = '00';
    }
    if (goodsBizType == '10') {
      isCheckedTypeStatu = that.isCheckedTypeStatus10();
      checkCart = '00';
    }
    if (goodsBizType == '11') {
      isCheckedTypeStatu = that.isCheckedTypeStatus11();
      checkCart = '11';
    }
    util.request(api.CartChecked, {
      isChecked: isCheckedTypeStatu ? 0 : 1,
      goodsBizType: goodsBizType, 
      checkCart: checkCart
    }, 'POST').then(function(res) {
      if (res.errno === 0) {
        // that.setCommonData(res);
        that.setData({
          validCartList: res.data.validCartList,
          couponInfoList: res.data.couponInfoList,
        });
        if (goodsBizType == '11') {
          that.setData({
            cartGoods: res.data.cartList,
            cartTotal: res.data.cartTotal,
            cartGoods11: res.data.cart11List,
            total11: res.data.total11
          });
        } else {
          that.setData({
            cartGoods: res.data.cartList,
            cartTotal: res.data.cartTotal,
            cartGoods00: res.data.cart00List,
            cartGoods02: res.data.cart02List,
            cartGoods10: res.data.cart10List,
            total00: res.data.total00
          });
        }
      }
      if (goodsBizType == '00') {
        that.setData({
          checkedTypeStatus00: that.isCheckedTypeStatus00()
        });
      }
      if (goodsBizType == '02') {
        that.setData({
          checkedTypeStatus02: that.isCheckedTypeStatus02()
        });
      }
      if (goodsBizType == '10') {
        that.setData({
          checkedTypeStatus10: that.isCheckedTypeStatus10()
        });
      }
      if (goodsBizType == '11') {
        that.setData({
          checkedTypeStatus11: that.isCheckedTypeStatus11()
        });
      }
      that.setData({
        checkedAllStatus: that.isCheckedAll()
      });
    });
  },
  updateCart: function(productId, goodsId, number, beforeNumber, id, itemIndex) {
    let that = this;

    util.request(api.CartUpdate, {
      productId: productId,
      goodsId: goodsId,
      number: number,
      id: id,
      checkCart: that.data.checkCart
    }, 'POST').then(function(res) {
      if (res.errno === 0) {
        // console.log(res.data);
        that.setCommonData(res);
      } else {
        // util.showErrorToast(res.errmsg);
        wx.showModal({
          title: '提示信息',
          content: res.errmsg,
          showCancel: false
        });
        let cartItem = that.data.cartGoods[itemIndex];
        cartItem.number = beforeNumber;
        that.setData({
          cartGoods: that.data.cartGoods
        });
        that.setCommonData(res);
      }
      that.setCheckedData();
    });
  },
  cutNumber: function(event) {
    let itemIndex = event.target.dataset.itemIndex;
    let cartItem = this.data.cartGoods[itemIndex];
    let beforeNumber = cartItem.number;
    let number = (cartItem.number - 1 > 1) ? cartItem.number - 1 : 1;
    cartItem.number = number;
    this.setData({
      cartGoods: this.data.cartGoods
    });
    this.updateCart(cartItem.product_id, cartItem.goods_id, number, beforeNumber, cartItem.id, itemIndex);
  },
  addNumber: function(event) {
    let itemIndex = event.target.dataset.itemIndex;
    let cartItem = this.data.cartGoods[itemIndex];
    let beforeNumber = cartItem.number;
    let number = cartItem.number + 1;
    cartItem.number = number;
    this.setData({
      cartGoods: this.data.cartGoods
    });
    this.updateCart(cartItem.product_id, cartItem.goods_id, number, beforeNumber, cartItem.id, itemIndex);
  },
  checkoutOrder: function() {
    //获取已选择的商品
    let that = this;
    util.request(api.getCurUser, {
      userInfo: app.globalData.userInfo
    }, 'POST').then(function(res) {
      if (res.errno === 0) {
        // console.log('that.data.mobile:' + res.data.mobile);
        if (res.data.mobile == '' || res.data.mobile == null) {
          wx.showModal({
            title: '',
            confirmColor: '#b4282d',
            showCancel: false,
            content: '您的手机号码未绑定，请先绑定手机号再进行购买',
            success: function(res) {
              if (res.confirm) {
                wx.navigateTo({
                  url: '../../pages/auth/newuser/newuser'
                });
              }
            }
          });
        } else {
          var checkedGoods = that.data.cartGoods.filter(function(element, index, array) {
            if (element.checked == true) {
              return true;
            } else {
              return false;
            }
          });

          if (checkedGoods.length <= 0) {
            wx.showToast({
              title: '请选择要购买的商品',
              icon: 'none'
            })
            return false;
          }
          wx.navigateTo({
            url: '../shopping/checkout/checkout?checkCart=' + that.data.checkCart
          })
        }
      }
    });
  },
  deleteCart: function(event) {
    //获取已选择的商品
    let that = this;

    let cartId = event.target.dataset.cartId;
    let goodsName = event.target.dataset.goodsName;

    wx.showModal({
      title: '',
      content: '确定要删除' + goodsName + '？',
      success: function(res) {
        if (res.confirm) {
          util.request(api.CartDelete, {
            cartId: cartId,
            checkCart: that.data.checkCart
          }, 'POST').then(function(res) {
            if (res.errno === 0) {
              that.setCommonData(res);
            }
            that.setCheckedData();
          });
          console.log('用户点击确定')
        }
      }
    });
  },
  switchAttrPop: function() {
    this.setData({
      openAttr: !this.data.openAttr
    })
  },
  hideSwitchAttrPop: function () {
    this.setData({
      openAttr: false
    })
  },
  clickSkuValue: function(event) {
    let that = this;
    let specValueId = event.currentTarget.dataset.valueId;
    let index = event.currentTarget.dataset.index;
    let _specificationList = this.data.specificationList;
    for (let j = 0; j < _specificationList[index].valueList.length; j++) {
      if (_specificationList[index].valueList[j].id == specValueId) {
        //如果已经选中，则反选
        if (_specificationList[index].valueList[j].checked) {
          _specificationList[index].valueList[j].checked = false;
        } else {
          _specificationList[index].valueList[j].checked = true;
        }
      } else {
        _specificationList[index].valueList[j].checked = false;
      }
    }
    this.setData({
      'specificationList': _specificationList
    });
    //重新计算spec改变后的信息
    goodsUtil.changeSpecInfo(that);
  },
  cutNumber2: function() {
    this.setData({
      number: (this.data.number - 1 > 1) ? this.data.number - 1 : 1
    });
  },
  addNumber2: function() {
    this.setData({
      number: this.data.number + 1
    });
  },

  //购物车增加
  addCart: function(e) {
    let that = this;
    that.setData({
      number: 1
    });
    var goodsId = e.currentTarget.dataset.goodsId;
    util.request(api.GoodsSku, {
      goodsId: goodsId
    }).then(function(res) {
      if (res.errno === 0 && null != res.data) {
        let stockNumbers = 0;
        if (res.data.goodsVo.goodsBizType=='00') {
          if (res.data.goodsVo.isStockShare == 1) {
            stockNumbers = res.data.goodsVo.goods_number;
          } else {
            stockNumbers = res.data.goodsVo.stockNum;
          }
        } else {
          stockNumbers = res.data.goodsVo.stockNum;
        }
        that.setData({
          goodsVo: res.data.goodsVo,
          specificationList: res.data.specificationList,
          productList: res.data.productList,
          openAttr: !that.data.openAttr,
          stockNum: stockNumbers,
          cartNumber: res.data.cartNumber,
          checkedSpecText: res.data.specificationList[0].valueList[0].value
        });
        //
        let _specificationList = res.data.specificationList;
        for (let i = 0; i < _specificationList.length; i++) {
          if (_specificationList[i].valueList.length == 1) {
            //如果已经选中，则反选
            _specificationList[i].valueList[0].checked = true;
          }
        }
        that.setData({
          'specificationList': _specificationList
        });
      }
    });
  },
  //购物车增加
  addToCart: function() {
    let that = this;
    var goodsId = that.data.goodsVo.id;
    //提示选择完整规格
    if (!that.data.productList || !that.data.productList.length) {
      util.showErrorToast('当前门店没有库存');
      return false;
    }
    //提示选择完整规格
    if (!goodsUtil.isCheckedAllSpec(that)) {
      return false;
    }
    //根据选中的规格，判断是否有对应的sku信息
    let checkedProduct = goodsUtil.getCheckedProductItem(goodsUtil.getCheckedSpecKey(that), that);
    if (!checkedProduct || checkedProduct.length <= 0) {
      //找不到对应的product信息，提示没有库存
      return false;
    }
    //验证库存
    if (checkedProduct.stock_num < this.data.number) {
      //找不到对应的product信息，提示没有库存
      return false;
    }
    util.request(api.CartAdd, {
      goodsId: goodsId,
      productId: checkedProduct[0].id,
      number: this.data.number,
      checkCart: that.data.checkCart
    }, 'POST').then(function(res) {
      if (res.errno === 0 && null != res.data) {
        wx.showToast({
          title: '添加成功',
          icon: 'success',
          mask: true
        });
        that.setData({
          openAttr: !that.data.openAttr,
          footprintList:[],
          page:1
        })
        // 页面显示
        that.getCartList();
        that.getFootprintList();
      } else {
        wx.showToast({
          title: res.errmsg,
          icon: 'none'
        });
        that.hideSwitchAttrPop();
      }
    });
  },
  deleteValidCart: function() { //获取购物车数据
    let that = this;
    wx.showModal({
      title: '',
      content: '确定要清空所有失效商品？',
      success: function(res) {
        if (res.confirm) {
          util.request(api.deleteValidCart, {
            checkCart: that.data.checkCart
          }).then(function(res) {
            if (res.errno === 0) {
              that.setCommonData(res);
            } else {
              util.showErrorToast(res.errmsg);
            }
          });
        }
      }
    });
  },
  getFootprintList() {
    let that = this;
    util.request(api.GuessFootprintList, {
      storeId: wx.getStorageSync('storeId'),
      checkCart: that.data.checkCart, page: that.data.page, size: that.data.size
    }).then(function (res) {
      if (res.errno === 0) {
        let goodsList = that.data.footprintList.concat(res.data.list);
        that.setData({
          footprintList: goodsList
        });
        wx.hideLoading();
      }
    });
  },
  onReachBottom() {
    var that = this;
    if(!that.data.footprintList){
      // wx.showLoading({
      //   title: '加载中...',
      // })
    }
    that.setData({
      page: that.data.page + 1
    });
    that.getFootprintList();
  }
})