var app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    language: "",
    countDownList: [],
    actEndTimeList: [],
    groupDetail: {}, // 总的信息
    goodsDetail: {}, // 商品信息
    has_many_success_member: "", // 参团会员信息
    has_many_success_member_count: "", // 已参团的成员数
    member_num: "", // 总的参团人数
    gooddatas: {},
    id: "",
    showOpenGroup: false, // 规格弹窗
    goodsInfo: {},
    goodsDescription: "",
    popPrice: 0,
    goodsId: "",
    activityId: "", // 活动id

    isOpen: 0, // 活动是否开启
    status: 0,
    action: 0,
    activityTest: "", // 当前活动状态
    btnTest: "", // 按钮的文字
    btnStatus: false, // 按钮是否禁用
    option_level_id: "", //规格层级id
    nowTime: new Date().getTime() / 1000,
    isCheckActivity: true, //下单前检查客户今天是否超出限制
    shareData: {},
    // 规格 -------
    optionsId: 0, //选择后的 规格ID
    popupSpecs: false,
    goodsCount: 1,
    optionsMaxCount: 1,
    popupSpecs2: false, //无规格选择商品数量
    popThumb: "",
    popStock: 0,
    specsManage: [], //选择池 用于排序
    popupModeshow: true, //动态模糊框
    // 规格end
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.mid) {
      app._setMid(options.mid);
    }
    console.log(options, "参数");
    this._getData();
  },

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

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    wx.showShareMenu({
      withShareTicket: false,
      menus: ["shareAppMessage", "shareTimeline"],
    });
  },

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

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

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

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

  /**
   * 用户点击右上角分享
   */
  onShareTimeline() {
    var value = wx.getStorageSync("yz_uid");
    var mid = "";
    if (value) {
      mid = value;
    }
    return {
      query: `id=${this.options.id}&mid=${mid}`,
    };
  },
  onShareAppMessage: function (res) {
    var value = wx.getStorageSync("yz_uid");
    var mid = "";
    if (value) {
      mid = value;
    }
    return {
      title: this.data.gooddatas.share_title == '' ? this.data.gooddatas.title : this.data.gooddatas.share_title,
      path:
        "/packageE/grab_group/grab_group_detail/grab_group_detail?id=" +
        this.options.id +
        "&mid=" +
        mid,
    };
  },
  getShare() {
    let urlStr = app.getNetAddresss(
      "plugin.snatch-regiment.api.index.getSnatchData"
    );
    urlStr += "&art=getShare";
    app._getNetWork({
      url: urlStr,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          this.setData({
            shareData: res.data.getShare,
          });
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
        }
      },
    });
  },
  _getData() {
    let urlStr = app.getNetAddresss(
      "plugin.snatch-regiment.api.index.getSnatchData"
    );
    urlStr += "&leader_id=" + this.options.id + "&art=raidDetail";
    app._getNetWork({
      url: urlStr,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          this.setData({
            gooddatas: res.data.raidDetail,
            "gooddatas.team_end_time": Number(
              res.data.raidDetail.team_end_time
            ),
            "gooddatas.activity_end_time": Number(
              res.data.raidDetail.activity_end_time
            ),
          });
          this.initPopView();
          this.getShare();
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
        }
      },
    });
  },
  // 获取数据
  checkActivity() {
    if(this.data.popPrice == 0){
      wx.showModal({
        title: '提示',
        showCancel:false,
        content: '开团/参团金额不正确，不能为0',
        success(res) {}
      });
      return;
    }
    let urlStr = app.getNetAddresss(
      "plugin.snatch-regiment.api.index.getSnatchData"
    );
    urlStr +=
      "&at_id=" +
      this.data.gooddatas.activity_id +
      "&art=inspectOverrun" +
      "&option_id=" +
      this.data.optionsId +
      "&goods_id=" +
      this.data.gooddatas.goods_id +
      "&total=" +
      this.data.goodsCount +
      "&leader_id=" +
      this.options.id;

    app._getNetWork({
      url: urlStr,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          this.setData({
            isCheckActivity: true,
          });
          this.submitAction();
        } else {
          this.setData({
            isCheckActivity: false,
          });
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
        }
      },
    });
  },

  // 去拼购聚合页
  gotoList() {
    wx.navigateTo({
      url: "/packageE/grab_group/grab_group_home/grab_group_home",
    });
  },
  gotoOrder() {
    let order_id = this.options.id;
    wx.navigateTo({
      url:
        "/packageA/member/orderdetail/orderdetail?order_id=" +
        order_id +
        "&orderType=grabGroup",
    });
  },

  showPopView() {
    if (
      this.data.gooddatas.has_option == 1 &&
      (app._isTextEmpty(this.data.optionsId) || this.data.optionsId == 0)
    ) {
      // 默认选择第一个
      for (let i = 0; i < this.data.gooddatas.has_many_specs.length; i++) {
        this.data.gooddatas.has_many_specs[
          i
        ].description = this.data.gooddatas.has_many_specs[i].specitem[0].id;
        this.selectSpecs(
          this.data.gooddatas.has_many_specs[i].specitem[0],
          "first",
          i
        );
      }
    }
    this.setData({
      popupSpecs: true,
      popupModeshow: false,
    });
  },
  //关闭popupSpecs
  popupSpecsbtn() {
    this.setData({
      popupSpecs: false,
      popupModeshow: true,
    });
  },
  //初始化弹窗view
  initPopView() {
    this.setData({
      "gooddatas.has_option":
        this.data.gooddatas.has_many_specs.length > 0 ? 1 : 0,
    });

    if (this.data.gooddatas.has_option == 1) {
      this.setData({
        popPrice:
          this.data.gooddatas.min_price + "-" + this.data.gooddatas.max_price, //设置默认价格
        popThumb: this.data.gooddatas.thumb, //设置默认图片
        popStock: this.data.gooddatas.stock, //设置默认库存
        goodsDescription: "选择",
      });
      for (let i = 0; i < this.data.gooddatas.has_many_specs.length; i++) {
        this.setData({
          goodsDescription:
            this.data.goodsDescription +
            " " +
            this.data.gooddatas.has_many_specs[i].title,
        });
      }
    } else {
      this.setData({
        popThumb: this.data.gooddatas.thumb, //设置默认图片
        popStock: this.data.gooddatas.stock, //设置默认库存
        popPrice: this.data.gooddatas.price, //设置默认价格
        goodsDescription: "",
        optionsMaxCount: this.data.gooddatas.stock,
      });
    }
  },

  // 输入数量
  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,
      });
    }
  },
  //减少
  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.gooddatas.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,
    // });
  },
  //界面选择规格触发事件
  selectSpecs(e, str, i) {
    let data = {};
    let specsIdex = 0;
    if (str == "first") {
      specsIdex = i;
      data = e;
    } else if (str == "sku_swiper") {
      data = e;
    } else {
      specsIdex = e.currentTarget.dataset.specsidex;
      data = e.currentTarget.dataset.specitem;
    }

    if (data.c) {
      return false;
    }
    this.setData({
      ["gooddatas.has_many_specs[" + specsIdex + "].description"]: data.id,
    });
    // let specid = data.specid; //对其他数据筛选 不筛选同级
    //处理选择池
    this.manageSpecs(data);
    //处理规格组合选择状态
    this.setGoodsSpecs(data);
    //设置选择规格后的 价格、照片、库存
    this.setGoodsSpecsChangeInfo();
    //判断当前购买总量与库存的关系
    this.getMaxCount();
  },
  //处理选择池
  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.gooddatas.has_many_specs.length) {
      var newSpecsManage = [];
      for (let i = 0; i < this.data.gooddatas.has_many_specs.length; i++) {
        for (let j = 0; j < specsManage.length; j++) {
          if (
            this.data.gooddatas.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.gooddatas.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.gooddatas.has_many_specs.length; i++) {
        for (let j = 0; j < specsManage.length; j++) {
          if (
            this.data.gooddatas.has_many_specs[i].id != specsManage[j].specid
          ) {
            description += this.data.gooddatas.has_many_specs[i].title + " ";
            break;
          }
        }
      }
      this.setData({
        goodsDescription: description,
      });
    }
  },
  //处理规格组合选择状态 过滤数据
  setGoodsSpecs(specs) {
    // let gooddatas = this.data.gooddatas;
    for (let i = 0; i < this.data.gooddatas.has_many_specs.length; i++) {
      if (specs.specid != this.data.gooddatas.has_many_specs[i].id) {
        // let specitem = this.setGoodsSpecsStatus(
        //   this.data.gooddatas.has_many_specs[i].specitem,
        //   specs.id
        // );
        // this.setData({
        // 	["gooddatas.has_many_specs[" + i + "].specitem"]: specitem
        // })
      }
    }
  },
  //处理规格组合选择状态 处理状态 specitem 组合数组(未选中的) id当前选中的ID 根据ID 组合算是否有当前组合
  setGoodsSpecsStatus(specitem, id) {
    let options = []; //数据池
    if(this.data.gooddatas && this.data.gooddatas.has_many_options){
      for (let i = 0; i < this.data.gooddatas.has_many_options.length; i++) {
        let _specs = this.data.gooddatas.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.gooddatas.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.gooddatas.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); //处理"_"
      if(this.data.gooddatas && this.data.gooddatas.has_many_options){
        for (let i = 0; i < this.data.gooddatas.has_many_options.length; i++) {
          if (
            goodsSpecs ==
            this.setGoodsSpecsBySort(
              this.data.gooddatas.has_many_options[i].specs
            )
          ) {
            this.setData({
              activeSkuIndex: i,
              popPrice: this.data.gooddatas.has_many_options[i].product_price, //设置价格
              popThumb: app._isTextEmpty(
                this.data.gooddatas.has_many_options[i].thumb
              )
                ? this.data.gooddatas.thumb
                : this.data.gooddatas.has_many_options[i].thumb, //设置图片
              popStock: this.data.gooddatas.has_many_options[i].stock, //设置库存
              optionsId: this.data.gooddatas.has_many_options[i].id, //设置规格ID，用于生成订单
            });
            this.data.optionsMaxCount = this.data.gooddatas.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;
  },
  //判断当前购买总量与库存的关系
  getMaxCount() {
    let specsManage = this.data.specsManage;
    let optionsMaxCount = this.data.optionsMaxCount;
    if (specsManage.length == this.data.gooddatas.has_many_specs.length) {
      if (optionsMaxCount == 0) {
        //库存不足
        this.setData({
          goodsCount: 0,
        });
      }
      if (this.data.goodsCount > optionsMaxCount) {
        this.setData({
          goodsCount: optionsMaxCount,
        });
      }
    }
  },
  OpenLeader() {
    let that = this;
    wx.navigateTo({
      url:
        "/packageA/detail_v2/detail_v2?id=" +
        that.data.gooddatas.goods_id +
        "&name=69",
    });
  },
  submitAction() {
    let _goodsId = this.data.gooddatas.goods_id;
    let _optionsId = this.data.optionsId;
    let _total = this.data.goodsCount;
    //库存不足
    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=-2" +
                "&optionsId=" +
                _optionsId +
                "&goodsId=" +
                _goodsId +
                "&total=" +
                _total +
                "&type=grabGroup_join" +
                "&at_id=" +
                that.data.gooddatas.activity_id+
                "&leader_id=" +
                that.options.id,
            });
          }
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
        }
      },
      fail: function (res) {},
    });
  },
});
