// pages/prod/prod.js
const app = getApp()
var http = require('../../../utils/http.js');
var config = require('../../../utils/config.js');
var util = require('../../../utils/util.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    shopId: 1,
    shopName: '',
    picDomain: config.picDomain,
    indicatorDots: true,
    indicatorColor: '#f2f2f2',
    indicatorActiveColor: '#eb2444',
    isAuthInfo: true,
    autoplay: true,
    interval: 3000,
    duration: 1000,
    prodNum: 1,
    totalCartNum: 0,
    groupActivityId: 0,
    pic: "",
    imgs: '',
    prodName: '',
    price: 0,
    actPrice: 0,
    content: '',
    prodId: 0,
    brief: '',
    skuId: 0,
    popupShow: false,
    skuShow: false,
    skuGroupShow: false,
    commentShow: false,
    skuList: [],
    skuGroup: {},
    findSku: true,
    defaultSku: undefined,
    detaultGroupSku: undefined,
    selectedProp: [],
    selectedPropObj: {},
    selectedProperties: "",
    propKeys: [],
    allProperties: [],

    isCollection: false,

    skuShowType: 0, // sku的显示类型 0普通sku 1拼团sku

    totalStocks: 0, // 活动剩余库存
    hasMaxNum: false, // 是否限购
    maxNum: 0, // 限购数量
    totalStocks: 0, //库存量
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.setData({
      prodId: options.prodId,
    });
    // 加载商品信息
    this.getProdInfo();
  },


  /**
   * 获取是否关注信息
   */
  getCollection() {
    wx.showLoading();
    var params = {
      url: "/p/user/collection/isCollection",
      method: "GET",
      data: {
        prodId: this.data.prodId
      },
      callBack: (res) => {
        this.setData({
          isCollection: res
        })
        wx.hideLoading();
      }
    };
    http.request(params);
  },


  // 获取商品信息
  getProdInfo() {
    wx.showLoading();
    var params = {
      url: "/score/prod/prodInfo",
      method: "GET",
      data: {
        prodId: this.data.prodId,
        // userType: 0
      },
      callBack: (res) => {
        var imgStrs = res.imgs;
        var imgs = imgStrs.split(",");
        var content = util.formatHtml(res.content);
        this.setData({
          imgs: imgs,
          content: content,
          price: res.price,
          prodName: res.prodName,
          groupActivityId: res.groupActivityId,
          prodId: res.prodId,
          brief: res.brief,
          totalStocks: res.totalStocks,
          // skuId: res.skuId
          skuList: res.skuList,
          totalStocks: res.totalStocks, //库存量
          pic: res.pic,
          shopId: res.shopId,
          scorePrice: res.scorePrice, //积分价格
        });
        // 团购活动
        if (res.groupActivityId) {
          this.getJoinGroupList();
        }
        // 组装sku
        this.groupSkuProp(res.skuList);

        // this.getShopInfo();

        wx.hideLoading();
      }
    };
    http.request(params);
  },

  //根据sku的属性 分组
  groupSkuProp: function(skuList) {
    // var skuList = this.data.skuList;
    if (skuList.length == 1 && skuList[0].properties == "") {
      this.setData({
        defaultSku: skuList[0]
      });
      // this.setDefaultGroupSku();
      return;
    }
    var skuGroup = {};
    var allProperties = [];
    var propKeys = [];
    this.setData({
      selectedPropObj: {}
    });
    for (var i = 0; i < skuList.length; i++) {
      var defaultSku = this.data.defaultSku;
      var isDefault = false;
      if (!defaultSku && skuList[i].price == this.data.price) { //找到和商品价格一样的那个SKU，作为默认选中的SKU
        defaultSku = skuList[i];
        isDefault = true;
        this.setData({
          defaultSku: defaultSku
        });
      }
      var properties = skuList[i].properties; //版本:公开版;颜色:金色;内存:64GB
      allProperties.push(properties);
      var propList = properties.split(";"); // ["版本:公开版","颜色:金色","内存:64GB"]

      var selectedPropObj = this.data.selectedPropObj;
      for (var j = 0; j < propList.length; j++) {

        var propval = propList[j].split(":"); //["版本","公开版"]
        var props = skuGroup[propval[0]]; //先取出 版本对应的值数组

        //如果当前是默认选中的sku，把对应的属性值 组装到selectedProp
        if (isDefault) {
          propKeys.push(propval[0]);
          selectedPropObj[propval[0]] = propval[1];
        }

        if (props == undefined) {
          props = []; //假设还没有版本，新建个新的空数组
          props.push(propval[1]); //把 "公开版" 放进空数组
        } else {
          if (!this.array_contain(props, propval[1])) { //如果数组里面没有"公开版"
            props.push(propval[1]); //把 "公开版" 放进数组
          }
        }
        skuGroup[propval[0]] = props; //最后把数据 放回版本对应的值
      }
      this.setData({
        selectedPropObj: selectedPropObj,
        propKeys: propKeys
      });
    }
    this.parseSelectedObjToVals();
    this.setData({
      skuGroup: skuGroup,
      allProperties: allProperties
    });
    // this.setDefaultGroupSku();
  },

  //将已选的 {key:val,key2:val2}转换成 [val,val2]
  parseSelectedObjToVals: function() {
    var selectedPropObj = this.data.selectedPropObj;
    var selectedProperties = "";
    var selectedProp = [];
    for (var key in selectedPropObj) {
      selectedProp.push(selectedPropObj[key]);
      selectedProperties += key + ":" + selectedPropObj[key] + ";";
    }
    selectedProperties = selectedProperties.substring(0, selectedProperties.length - 1);
    // console.log(selectedProperties);
    this.setData({
      selectedProp: selectedProp,
      selectedProperties: selectedProperties
    });

    var findSku = false;
    for (var i = 0; i < this.data.skuList.length; i++) {
      if (this.data.skuList[i].properties == selectedProperties) {
        findSku = true;
        this.setData({
          defaultSku: this.data.skuList[i]
        });
        break;
      }
    }
    this.setData({
      findSku: findSku
    });
    // this.setDefaultGroupSku();
  },

  //点击选择规格
  toChooseItem: function(e) {
    var ok = e.currentTarget.dataset.ok;
    if (ok == 0) {
      return;
    }
    var val = e.currentTarget.dataset.val;
    var key = e.currentTarget.dataset.key;
    var selectedPropObj = this.data.selectedPropObj;
    selectedPropObj[key] = val;
    this.setData({
      selectedPropObj: selectedPropObj
    });
    this.parseSelectedObjToVals();
  },

  //判断数组是否包含某对象
  array_contain: function(array, obj) {
    for (var i = 0; i < array.length; i++) {
      if (array[i] == obj) //如果要求数据类型也一致，这里可使用恒等号===
        return true;
    }
    return false;
  },


  /**
   * 立即兑换
   */
  redeemNow: function() {
    if (!this.data.findSku) {
      return;
    }
    if (!this.data.skuShow) {
      this.setData({
        skuShow: true
      })
      return
    }
    wx.showLoading({
      mask: true
    });
    if (this.data.totalStocks < 0) {
      wx.showToast({
        title: '商品库存不足！',
        icon: none,
        duration: 2000,
      })
      return
    }
    // 查看是否授权
    util.checkAuthInfo(this._redeemNow)
  },
  _redeemNow() {
    wx.setStorageSync("orderItem", JSON.stringify({
      prodId: this.data.prodId,
      skuId: this.data.defaultSku.skuId,
      prodCount: this.data.prodNum,
      shopId: this.data.shopId,
      distributionCardNo: this.data.distributionCardNo
    }));
    wx.navigateTo({
      url: '/packageMemberIntegral/pages/integralSubmitOrder/integralSubmitOrder?orderEntry=1',
    })
  },

  /**
   * 页面隐藏触发
   */
  onHide(){
    this.setData({
      skuShow: false
    })
  },

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

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.setData({
      totalCartNum: app.globalData.totalCartCount,
    });
    // 查看用户是否关注
    this.getCollection();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 跳转到首页
   */
  toHomePage: function() {
    wx.switchTab({
      url: '/pages/index/index',
    })
  },


  /**
   * 减数量
   */
  onCountMinus: function() {
    var prodNum = this.data.prodNum;
    if (prodNum > 1) {
      this.setData({
        prodNum: prodNum - 1
      });
    }
  },

  /**
   * 加数量
   */
  onCountPlus: function() {
    var prodNum = this.data.prodNum;
    // 判断是否限购
    if (this.data.hasMaxNum) {
      if (prodNum < this.data.totalStocks && prodNum < this.data.maxNum) {
        this.setData({
          prodNum: prodNum + 1
        });
      } else {
        wx.showToast({
          title: '限购' + this.data.maxNum + '件',
          icon: 'none',
        })
      }
    } else {
      if (prodNum < this.data.totalStocks) {
        this.setData({
          prodNum: prodNum + 1
        });
      }
    }
  },


  // sku弹框
  showSku: function(e) {
    if (e.currentTarget.dataset.alonebuy == 1) {
      this.setData({
        skuShow: true,
        skuShowType: 0
      });
    } else {
      if (this.data.groupActivityId) {
        this.setData({
          skuShow: true,
          skuShowType: 1
        });
      } else {
        this.setData({
          skuShow: true,
          skuShowType: 0
        });
      }
    }

  },


  // 关闭规格弹窗
  closePopup: function() {
    this.setData({
      popupShow: false,
      skuShow: false,
      commentShow: false
    });
  },

  /**
   * 获取用户信息
   */
  onGotUserInfo: function(e) {
    if (e.detail.errMsg != "getUserInfo:fail auth deny") {
      this.setData({
        isAuthInfo: true
      });
      http.updateUserInfo();
    }
  },

  groupConfirmOrder: function(e) {
    if (!this.data.findSku) {
      return;
    }
    var ths = this;
    wx.showLoading({
      mask: true
    });
    // 查看是否授权
    util.checkAuthInfo(ths._groupConfirmData)
  },
  _groupConfirmData() {
    wx.setStorageSync("groupOrderItem", JSON.stringify({
      groupSkuId: ths.data.detaultGroupSku.groupSkuId, // this.data.groupSkuId,
      prodCount: ths.data.prodNum, // this.data.prodNum,
      groupTeamId: e.currentTarget.dataset.teamid // this.data.groupTeamId
    }));
    wx.navigateTo({
      url: '/pages/groupConfirmOrder/groupConfirmOrder',
    })
  }
})