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: ''
  },
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
  },
  onReady: function () {
    // 页面渲染完成

  },
  onShow: function () {
    // 页面显示
    this.getCartList();
    this.getFootprintList();
  },
  onHide: function () {
    // 页面隐藏

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

  },
  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
    });
  },
  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;
    util.request(api.CartList).then(function (res) {
      if (res.errno === 0) {
        that.setCommonData(res);
      }
      //数据渲染选中
      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 that = this;

    util.request(api.CartChecked, {
      productIds: that.data.cartGoods[itemIndex].product_id,
      isChecked: that.data.cartGoods[itemIndex].checked ? 0 : 1
    }, '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;
      }
    });
    console.log(checkedGoodsCount);
    return checkedGoodsCount;
  },
  checkedAll: function () {
    let that = this;
    var productIds = this.data.cartGoods.map(function (v) {
      return v.product_id;
    });
    util.request(api.CartChecked, {
      productIds: productIds.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;
    if (goodsBizType == '00') {
      isCheckedTypeStatu = that.isCheckedTypeStatus00();
    }
    if (goodsBizType == '02') {
      isCheckedTypeStatu = that.isCheckedTypeStatus02();
    }
    if (goodsBizType == '10') {
      isCheckedTypeStatu = that.isCheckedTypeStatus10();
    }
    if (goodsBizType == '11') {
      isCheckedTypeStatu = that.isCheckedTypeStatus11();
    }
    util.request(api.CartChecked, {
      isChecked: isCheckedTypeStatu ? 0 : 1,
      goodsBizType: goodsBizType
    }, 'POST').then(function (res) {
      if (res.errno === 0) {
        that.setCommonData(res);
      }

      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
    }, '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.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) {
            return false;
          }
          wx.navigateTo({
            url: '../shopping/checkout/checkout'
          })
        }
      }
    });
  },
  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
          }, 'POST').then(function (res) {
            if (res.errno === 0) {
              that.setCommonData(res);
            }
            that.setCheckedData();
          });
          console.log('用户点击确定')
        }
      }
    });
  },
  getFootprintList() {
    let that = this;
    util.request(api.GuessFootprintList, { storeId: wx.getStorageSync('storeId') },).then(function (res) {
      if (res.errno === 0) {
        that.setData({
          footprintList: res.data.list
        });
      }
    });
  },
  switchAttrPop: function () {
    this.setData({
      openAttr: !this.data.openAttr
    })
  },
  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;
    var goodsId = e.currentTarget.dataset.goodsId;
    util.request(api.GoodsSku, { goodsId: goodsId }).then(function (res) {
      if (res.errno === 0 && null != res.data) {
        that.setData({
          goodsVo: res.data.goodsVo,
          specificationList: res.data.specificationList,
          productList: res.data.productList,
          openAttr: !that.data.openAttr
        });
        //
        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
    }, 'POST').then(function (res) {
      if (res.errno === 0 && null != res.data) {
        wx.showToast({
          title: '添加成功',
          icon: 'success',
          mask: true
        });
        that.setData({
          openAttr: !that.data.openAttr
        })
        // 页面显示
        that.getCartList();
        that.getFootprintList();
      } else {
        util.showErrorToast(res.errmsg)
      }
    });
  },
  deleteValidCart: function () {//获取购物车数据
    let that = this;
    wx.showModal({
      title: '',
      content: '确定要清空所有失效商品？',
      success: function (res) {
        if (res.confirm) {
          util.request(api.deleteValidCart).then(function (res) {
            if (res.errno === 0) {
              that.setCommonData(res);
            } else {
              util.showErrorToast(res.errmsg);
            }
          });
        }
      }
    });
  }
})