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

Page({
  data: {
    bannerInfo: {
      'img_url': '',
      'name': ''
    },
    categoryFilter: false,
    filterCategory: [],
    goodsList: [],
    categoryId: 0,
    currentSortType: 'desc',
    currentSortOrder: 'a.create_time',
    page: 1,
    size: 4,
    showNavList: false,
    footCart: {},
    openAttr: false,
    productList: {},
    specificationList: {},
    checkedSpecText: '请选择规格数量',
    number: 1,
    retailPrice: '',
    stockNum: 0,
    cartNumber: 0,
    totalPages: 0
  },
  toggleNav() {
    this.setData({
      showNavList: !this.data.showNavList
    })
  },
  getData: function () {
    let that = this;
    util.request(api.GoodsHot).then(function (res) {
      if (res.errno == 0) {
        that.setData({
          bannerInfo: res.data.bannerInfo,
          goodsList: [],
          page: 1
        });
        that.getGoodsList();
      }
    });
  },
  getGoodsList() {
    wx.showLoading({
      title: '加载中...',
    });
    var that = this;

    util.request(api.HotGoodsList, { isHot: 1, page: that.data.page, size: that.data.size, order: that.data.currentSortOrder, sort: that.data.currentSortType, categoryId: that.data.categoryId})
      .then(function (res) {
        if (res.errno === 0) {
          let goodsList = that.data.goodsList.concat(res.data.goodsList);
          that.setData({
            goodsList: goodsList,
            filterCategory: res.data.filterCategory,
            totalPages: 0
          });
          wx.hideLoading();
          if(that.data.categoryId>0){
            let filterCategory = that.data.filterCategory;
            filterCategory.forEach(function (val, index, arr) {
              if (val.id == that.data.categoryId) {
                val.checked = true;
                filterCategory[index] = val;
                that.setData({ filterCategory: filterCategory });
              }else {
                val.checked = false;
              }
            }, that);
          }
        }
      });
  },
  switchNav(event) {
    let name = event.currentTarget.dataset.name;
    wx.switchTab({
      url: `/pages/${name}/${name}`,
    });
  },
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
    this.getData();
    this.getFootCart();

  },
  onReady: function () {
    // 页面渲染完成
  },
  onShow: function () {
    // 页面显示

  },
  onHide: function () {
    // 页面隐藏

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

  },
  openSortFilter: function (event) {
    let currentId = event.currentTarget.id;
    switch (currentId) {
      case 'categoryFilter':
        this.setData({
          'categoryFilter': !this.data.categoryFilter,
          'currentSortType': 'category',
          'currentSortOrder': 'asc'
        });
        break;
      case 'priceSort':
        let tmpSortOrder = 'asc';
        if (this.data.currentSortOrder == 'asc') {
          tmpSortOrder = 'desc';
        }
        this.setData({
          'currentSortType': 'price',
          'currentSortOrder': tmpSortOrder,
          'categoryFilter': false,
          goodsList: [],
          page: 1
        });

        this.getData();
        break;
      default:
        //综合排序
        this.setData({
          'currentSortType': 'default',
          'currentSortOrder': 'desc',
          'categoryFilter': false,
          goodsList: [],
          page: 1
        });
        this.getData();
    }
  },
  selectCategory: function(event){
    let that = this;
    let currentIndex = event.target.dataset.categoryIndex;
    this.setData({
      categoryFilter: false,
      categoryId: this.data.filterCategory[currentIndex].id
    });
    this.getData();
  },
  getFootCart: function () {
    let that = this;
    util.request(api.GetFootCart).then(function (res) {
      if (res.errno === 0) {
        that.setData({
          footCart: res.data,
        });
      }
    });
  },
  switchAttrPop: function () {
    this.setData({
      openAttr: !this.data.openAttr
    })
  },
  hideSwitchAttrPop: function () {
    this.setData({
      openAttr: false
    })
  },
  //购物车增加
  addCart: function (e) {
    let that = this;
    that.setData({
      number: 1
    });
    var goodsId = e.currentTarget.dataset.goodsId;
    var retailPrice = e.currentTarget.dataset.retailPrice; 
    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,
          retailPrice: retailPrice,
          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
        });

      }
    });
  },
  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);
  },
  cutNumber: function () {
    this.setData({
      number: (this.data.number - 1 > 1) ? this.data.number - 1 : 1
    });
  },
  addNumber: function () {
    this.setData({
      number: this.data.number + 1
    });
  },
  //购物车增加
  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.getFootCart();
      } else {
        wx.showToast({
          title: res.errmsg,
          icon: 'none'
        })
      }
    });
  },
  onReachBottom() {
    var that = this;
    if (!that.data.goodsList) {
      wx.showLoading({
        title: '加载中...',
      })
    }
    that.setData({
      page: that.data.page + 1,
    });
    that.getGoodsList();
  }
})