// packageB/member/distribution_queue/activity_details/activity_details.js
var app = getApp();
Page({

  /**
	 * 页面的初始数据
	 */
  data: {
    language: '',
    checked: -1,
    activeName: "first",
    posterShow: false,
    posterImg: "",
    goods_list: [],
    datas: {},
    id: "",

    cservice: '', //客服
    share_title: "",
    share_icon: "",
    share_desc: "",


    // 选择商品
    selected_goods: {},
    isGoods: true,
    specsManage: [], //选择池 用于排序
    SUBMIT_ACTION_CART: "-1", //添加到购物车
    SUBMIT_ACTION_BUY: "-2", //立即购买
    submitActionTag: "-2",
    optionsId: '', //选择后的 规格ID
    goodsCount: 1,
    optionsMaxCount: 1,
    popupSpecs: false,
    popupSpecs2: false,
    popStock: 0, //库存
    popPrice: 0, //价格
    goodsDescription: "", //体现语言
  },

  /**
	 * 生命周期函数--监听页面加载
	 */
  onLoad: function(options) {
    if (options.scene) {
      let scene = decodeURIComponent(options.scene);
      if (scene) {
        var info_arr = [];
        info_arr = scene.split(',');
        for (let i = 0; i < info_arr.length; i++) {
          let chil_arr = [];
          chil_arr = info_arr[i].split('=');
          console.log(chil_arr);
          if (chil_arr[0] == 'id') {
            this.setData({
              checked: -1,
              id: chil_arr[1]
            });
          } else if (chil_arr[0] == 'mid') {
            app._setMid(chil_arr[1]);
          }
        }
      }
    } else {
      if (options.id) {
        this.setData({
          checked: -1,
          id: options.id
        });
      }
      if (options.mid) {
        app._setMid(options.mid);
      }
    }
    this.getData();
  },
  saveImg() {
    // var times = _this.data.timeend - _this.data.timestart;
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {
              console.log('授权成功');
            }
          });
        }
      }
    });
    var imgSrc = this.data.posterImg.image_url;
    wx.downloadFile({
      url: imgSrc,
      success: function(res) {
        console.log(res);
        //图片保存到本地
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: function(data) {
            wx.showToast({
              title: '保存成功',
              icon: 'none',
              duration: 2000
            });
          },
          fail: function(err) {
            console.log(err);
            if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
              console.log("当初用户拒绝，再次发起授权");
              wx.openSetting({
                success(settingdata) {
                  if (settingdata.authSetting['scope.writePhotosAlbum']) {
                    wx.showToast({
                      icon: 'none',
                      title: '获取权限成功,再次长按保存图片',
                      duration: 1500
                    });
                  } else {
                    wx.showToast({
                      icon: 'none',
                      title: '获取权限失败,保存图片需要用户授权',
                      duration: 1500
                    });
                  }
                }
              });
            }
          },
          complete(res) {
            console.log(res);
          }
        });
      }
    });
  },
  //提交确认
  submitAction() {
    let specsManage = this.data.specsManage;
    let submitActionTag = this.data.submitActionTag;
    // let SUBMIT_ACTION_CART = this.data.SUBMIT_ACTION_CART;
    let SUBMIT_ACTION_BUY = this.data.SUBMIT_ACTION_BUY;
    if (specsManage.length < this.data.goods_list[this.data.checked].has_many_specs.length) {
      this.setData({
        popupSpecs: false,
      });
      wx.showToast({
        icon: 'none',
        title: this.data.goodsDescription,
        duration: 1500
      });
      return;
    }

    if (submitActionTag == SUBMIT_ACTION_BUY) { //立即购买处理
      this.setData({
        popupSpecs: false,
      });
      this.buyNowRequest(this.data.selected_goods.id, this.data.optionsId, this.data.goodsCount);
    }
  },
  //新处理立即购买
  buyNowNew() {
    this.popupSpecs2CloseBtn();
    this.buyNowRequest(this.data.selected_goods.id, this.data.optionsId, this.data.goodsCount);
  },
  //减少
  reduceGoods() {
    let lastgoodsCount = this.data.goodsCount;
    if (this.data.goodsCount == 1 || this.data.goodsCount == 0) {
      return;
    }
    this.setData({
      goodsCount: lastgoodsCount - 1
    });
  },
  //增加
  addGoods() {
    let lastgoodsCount = this.data.goodsCount;
    let specsManage = this.data.specsManage;
    let optionsMaxCount = this.data.optionsMaxCount;
    console.log("增加");
    if (specsManage.length == this.data.goods_list[this.data.checked].has_many_specs.length && this.data.goodsCount ==
			optionsMaxCount) {
      console.log("数量超出范围");
      wx.showToast({
        icon: 'none',
        title: '数量超出范围',
        duration: 1500
      });
      console.log("max=" + this.data.goodsCount);
      return;
    }
    this.setData({
      goodsCount: lastgoodsCount + 1
    });

  },
  // 输入数量
  inputGoodsNum: function(e) {
    var num = parseInt(e.detail.value);
    var lastgoodsCount = this.data.goodsCount;
    if (e.detail.keyCode == 8) {
      if (app._isTextEmpty(e.detail.value)) {
        this.setData({
          goodsCount: ''
        });
        return;
      }
    }
    if (num) {
      this.setData({
        goodsCount: num
      });
    } else {
      this.setData({
        goodsCount: lastgoodsCount
      });
    }
  },
  //立即购买网络操作
  buyNowRequest(_goodsId, _optionsId, _total) {
    //库存不足
    if (this.data.optionsMaxCount == 0) {
      wx.showToast({
        icon: 'none',
        title: '商品库存不足',
        duration: 1500
      });
      return;
    }
    if (_total <= 0) {
      wx.showToast({
        icon: 'none',
        title: '请选择商品数量',
        duration: 1500
      });
      return;
    }
    let that = this;
    let goods = [];
    goods.push(_goodsId);
    let urlStr = app.getNetAddresss("from.div-from.isDisplay");
    urlStr += "&goods_ids=" + JSON.stringify(goods);
    app._getNetWork({
      showToastIn: false,
      url: urlStr,
      success: function(resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          var _data = res.data;
          console.log('xxxx', _data);
          if (res.data.status && !res.data.member_status) {
            wx.showModal({
              title: '提示',
              content: '购买此商品,请补充您的个人信息',
              success(res) {
                if (res.confirm) {
                  //保税真实信息添加
                  wx.navigateTo({
                    url: "/packageB/member/address/myinfo/myinfo?tag=delta"
                  });

                } else if (res.cancel) {

                  console.log('用户点击取消');
                }
              }
            });
          } else {
            wx.navigateTo({
              url: '/packageD/buy/myOrder_v2/myOrder_v2?tag=' + that.data.submitActionTag + '&goodsId=' + _goodsId +
								'&optionsId=' + _optionsId + '&total=' + _total + '&activity_id=' + that.data.id
            });
          }

        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }

      },
      fail: function(res) {

      }
    });
  },
  goMember() {
    wx.reLaunch({
      url: '/packageG/member_v2/member_v2'
    });
  },
  goHome() {
    wx.reLaunch({
      url: '/packageG/index/index'
    });
  },
  posterShowCloseBtn() {
    this.setData({
      posterShow: false
    });
  },
  getData() {
    let that = this;
    let urlStr = app.getNetAddresss("plugin.commission-activity.api.activity.detail");
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: {
        id: this.data.id
      },
      success: function(resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          let datas = res.data;
          that.setData({
            datas: datas,
            goods_list: datas.goods,
            share_title: datas.share_title,
            share_icon: datas.share_icon,
            share_desc: datas.share_desc
          });
        } else {
          wx.showModal({
            title: '提示',
            content: res.msg,
            showCancel: false,
            success(res) {
              if (res.confirm) {
                wx.navigateBack({
                  delta: 1,
                  fail() {
                    wx.reLaunch({
                      url: '/packageG/index/index'
                    });
                  }
                });
              }
            }
          });
        }
      },
      fail: function(res) {
        console.log(res.msg);
      }
    });
  },
  // 初始化商品信息
  initGoods() {
    this.data.specsManage = []; //选择池 用于排序
    this.data.optionsId = ""; //选择后的 规格ID
    this.data.optionsMaxCount = 1;
    this.setData({
      popStock: 0,
      popPrice: 0,
      goodsDescription: '',
      goodsCount: 1
    });
  },
  //立即购买
  buyNow() {
    let that = this;
    if (this.data.checked == -1) {
      wx.showToast({
        icon: 'none',
        title: '请选择要购买的商品',
        duration: 1500
      });
      return false;
    }
    // 初始化商品信息
    this.initGoods();
    this.setData({
      selected_goods: this.data.goods_list[this.data.checked]
    });
    this.data.optionsMaxCount = this.data.selected_goods.stock;
    // let urlStr = app.getNetAddresss("member.member.isValidatePageGoods");
    // app._getNetWork({
    // 	url: urlStr,
    // 	success: function(resdata) {
    // 		var res = resdata.data;
    // 		if (res.result == 1) {
    if (!that.data.isGoods) {
      wx.showToast({
        icon: 'none',
        title: '商品已下架或不存在',
        duration: 1500
      });
      return;
    }
    //判断是否有规格
    if (that.data.goods_list[that.data.checked].has_option == 1) {
      //有规格 但是还未选择
      that.setData({
        popupSpecs: true
      });
      if (!that.data.optionsId) {
        // 默认选择第一个
        for (let i = 0; i < that.data.goods_list[that.data.checked].has_many_specs.length; i++) {
          that.setData({
            ['goods_list[' + that.data.checked + '].has_many_specs[' + i + '].description']: that.data.goods_list[
              that.data.checked].has_many_specs[i].has_many_specs_item[0]
          });
          that.selectSpecs(
            that.data.goods_list[that.data.checked].has_many_specs[i].has_many_specs_item[0], 'first', i
          );
        }
      }
    } else if (that.data.goods_list[that.data.checked].has_option == 0) {
      that.showPopView2();
    }
    // 		} else {
    // 			wx.showToast({
    // 				icon: 'none',
    // 				title: res.msg,
    // 				duration: 1500
    // 			})
    // 		}
    // 	},
    // 	fail: function(res) {
    // 		console.log(res);
    // 	}
    // });
  },
  //无规格选择 增加数量
  showPopView2() {
    this.setData({
      popupSpecs2: true
    });
  },
  popupSpecsCloseBtn() {
    this.setData({
      popupSpecs: false
    });
  },
  popupSpecs2CloseBtn() {
    this.setData({
      popupSpecs2: false
    });
  },
  //界面选择规格触发事件
  selectSpecs(e, str, i) {
    let data = {};
    let specsIdex = 0;
    if (str == 'first') {
      specsIdex = i;
      data = e;
    } else {
      specsIdex = e.currentTarget.dataset.specsidex;
      data = e.currentTarget.dataset.specitem;
    }
    if (data.c) {
      return false;
    }
    this.setData({
      ["goods_list[" + this.data.checked + "].has_many_specs[" + specsIdex + "].description"]: data.id
    });
    // let specid = data.specid; //对其他数据筛选 不筛选同级
    //处理选择池
    this.manageSpecs(data);
    //处理规格组合选择状态
    this.setGoodsSpecs(data);
    //设置选择规格后的 价格、照片、库存
    this.setGoodsSpecsChangeInfo();
    //判断当前购买总量与库存的关系
    this.getMaxCount();
  },
  //判断当前购买总量与库存的关系
  getMaxCount() {
    let specsManage = this.data.specsManage;
    let optionsMaxCount = this.data.optionsMaxCount;
    if (specsManage.length == this.data.goods_list[this.data.checked].has_many_specs.length) {
      if (optionsMaxCount == 0) //库存不足
      {
        this.setData({
          goodsCount: 0
        });
      }
      if (this.data.goodsCount > optionsMaxCount) {
        this.setData({
          goodsCount: optionsMaxCount
        });
      }
    }
  },
  //处理选择池
  manageSpecs(data) {
    let specsObject = new Object();
    let specsManage = this.data.specsManage;
    specsObject.id = data.id;
    specsObject.specid = data.specid;
    specsObject.title = data.title;

    if (specsManage.length > 0) {
      for (let i = 0; i < specsManage.length; i++) {
        if (specsManage[i].specid == specsObject.specid) {
          specsManage.splice(i, 1);
        }
      }
      specsManage.push(specsObject);
    } else {
      specsManage.push(specsObject);
    }

    //排序
    if (specsManage.length == this.data.goods_list[this.data.checked].has_many_specs.length) {
      var newSpecsManage = [];
      for (let i = 0; i < this.data.goods_list[this.data.checked].has_many_specs.length; i++) {
        for (let j = 0; j < specsManage.length; j++) {
          if (this.data.goods_list[this.data.checked].has_many_specs[i].id == specsManage[j].specid) {
            newSpecsManage.push(specsManage[j]);
            break;
          }
        }
      }
      specsManage = newSpecsManage;
    }
    this.setData({
      specsManage: specsManage
    });
    this.setGoodsDescription();
  },
  //处理goodsDescription 数据
  setGoodsDescription() {
    let description = "";
    let specsManage = this.data.specsManage;
    //相等代表全选了 体现语句
    if (specsManage.length == this.data.goods_list[this.data.checked].has_many_specs.length) {
      description = "已选择 ";
      for (let i = 0; i < specsManage.length; i++) {
        description += specsManage[i].title + " ";
      }
      this.setData({
        goodsDescription: description
      });
    } else {
      description = "请选择 ";
      for (let i = 0; i < this.data.goods_list[this.data.checked].has_many_specs.length; i++) {
        for (let j = 0; j < specsManage.length; j++) {
          if (this.data.goods_list[this.data.checked].has_many_specs[i].id != specsManage[j].specid) {
            description += this.data.goods_list[this.data.checked].has_many_specs[i].title + " ";
            break;
          }
        }
      }
      this.setData({
        goodsDescription: description
      });
    }
  },
  //处理规格组合选择状态 过滤数据
  setGoodsSpecs(specs) {
    // let goodsInfo = this.data.goods_list[this.data.checked];
    for (let i = 0; i < this.data.goods_list[this.data.checked].has_many_specs.length; i++) {
      if (specs.specid != this.data.goods_list[this.data.checked].has_many_specs[i].id) {
        let specitem = this.setGoodsSpecsStatus(this.data.goods_list[this.data.checked].has_many_specs[i].specitem, specs
          .id);
        this.setData({
          ["goods_list[" + this.data.checked + "].has_many_specs[" + i + "].specitem"]: specitem
        });
      }
    }
  },
  //处理规格组合选择状态 处理状态 specitem 组合数组(未选中的) id当前选中的ID 根据ID 组合算是否有当前组合
  setGoodsSpecsStatus(specitem, id) {
    let options = []; //数据池
    for (let i = 0; i < this.data.goods_list[this.data.checked].has_many_options.length; i++) {
      let _specs = this.data.goods_list[this.data.checked].has_many_options[i].specs.split("_");
      //console.log(_specs);
      //判断是否包含
      for (let j = 0; j < _specs.length; j++) {
        if (_specs[j] == id) {
          options.push(this.data.goods_list[this.data.checked].has_many_options[i]);
          return;
        }
      }
    }

    //关键处理方式 后期要优化 效率低
    for (let m = 0; m < options.length; m++) {
      let _specs = options[m].specs.split("_");
      for (let y = 0; y < _specs.length; y++) {
        if (_specs[y] != id && options[m].stock == 0) {
          for (let n = 0; n < specitem.length; n++) {
            if (_specs[y] == specitem[n].id) {
              specitem[n].c = true;
            }
          }
        } else if (_specs[y] != id && options[m].stock > 0) {
          for (let n = 0; n < specitem.length; n++) {
            if (_specs[y] == specitem[n].id) {
              specitem[n].c = false;
            }
          }
        }
      }
    }
    return specitem;
  },
  //设置选择规格后的 价格、照片、库存
  setGoodsSpecsChangeInfo() {
    let specsManage = this.data.specsManage;
    //根据ID 排序 specsManage.sort();
    specsManage.sort(function(a, b) {
      return a.id - b.id;
    });
    if (specsManage.length == this.data.goods_list[this.data.checked].has_many_specs.length) {
      let goodsSpecs = "";
      for (let j = 0; j < specsManage.length; j++) {
        goodsSpecs += specsManage[j].id + "_";
      }
      goodsSpecs = goodsSpecs.substring(0, goodsSpecs.length - 1); //处理"_"
      for (let i = 0; i < this.data.goods_list[this.data.checked].has_many_options.length; i++) {
        if (goodsSpecs == this.setGoodsSpecsBySort(this.data.goods_list[this.data.checked].has_many_options[i].specs)) {

          this.setData({
            popPrice: this.data.goods_list[this.data.checked].has_many_options[i].product_price, //设置价格
            popThumb: app._isTextEmpty(this.data.goods_list[this.data.checked].has_many_options[i].thumb) ? this.data.goods_list[
              this.data.checked].thumb : this.data.goods_list[this.data.checked].has_many_options[i].thumb, //设置图片
            popStock: this.data.goods_list[this.data.checked].has_many_options[i].stock, //设置库存
            optionsId: this.data.goods_list[this.data.checked].has_many_options[i].id //设置规格ID，用于生成订单
          });
          this.data.optionsMaxCount = this.data.goods_list[this.data.checked].has_many_options[i].stock; //库存最大数 用于切换更改买家购买数量
          if (this.data.optionsMaxCount > 0) {
            this.setData({
              goodsCount: 1
            });
          }

          break;
        }
      }
    }
    this.setData({
      specsManage: specsManage
    });
  },
  //处理商品goodsSpecs 并排序 新方法
  setGoodsSpecsBySort(specs) {
    let _specs = specs.split("_"); //先变成数组
    //_specs.sort();//排序
    _specs.sort(function(a, b) {
      return a - b;
    });
    // 在组装回去
    let goodsSpecs = "";
    for (let j = 0; j < _specs.length; j++) {
      goodsSpecs += _specs[j] + "_";
    }
    goodsSpecs = goodsSpecs.substring(0, goodsSpecs.length - 1); //处理"_"
    return goodsSpecs;
  },

  /**
	 * 生命周期函数--监听页面初次渲染完成
	 */
  onReady: function() {
    let language = wx.getStorageSync('langIndex');
    this.setData({ 'language': language.en});
  },

  /**
	 * 生命周期函数--监听页面显示
	 */
  onShow: function() {

  },

  /**
	 * 生命周期函数--监听页面隐藏
	 */
  onHide: function() {

  },

  /**
	 * 生命周期函数--监听页面卸载
	 */
  onUnload: function() {

  },

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

  },

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

  },

  /**
	 * 用户点击右上角分享
	 */
  onShareAppMessage: function() {
    var value = wx.getStorageSync('yz_uid');
    var mid = '';
    if (value) {
      mid = value;
    }
    return {
      path: '/packageB/member/distribution_queue/DistributionActivityDetail/DistributionActivityDetail?id=' + this.data
        .id + '&mid=' + mid
    };
  },
  onChange(e) {
    let index = e.detail;
    this.setData({
      checked: Number(index)
    });
  },
  //海报生成
  postShow() {
    if (this.data.posterImg) {
      this.setData({
        posterShow: true
      });
    } else {
      let that = this;
      let urlStr = app.getNetAddresss("plugin.commission-activity.api.activity-poster.index");
      urlStr += '&id=' + this.data.id;
      app._getNetWork({
        url: urlStr,
        success: function(resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            that.setData({
              posterImg: res.data,
              posterShow: true
            });
          } else {
            that.setData({
              posterShow: false
            });
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1500
            });
          }
        },
        fail: function(res) {
          console.log(res);
        }
      });
    }
  },
  gotoGoods(e) {
    let id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/packageA/detail_v2/detail_v2?id=' + id + '&activity_id=' + this.data.id
    });
  },
});
