// packageF/cart_share/cart_share.js
var app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    share_id: "",
    set: {},
    member: {},
    cartList: [], //商品列表
    eachCheckList: [], //选中商品列表
    checkAll: false,
    selectBol: true,

    showCouponDetail: false, //优惠券弹窗
    good_clicktag: 0,
    all_get_coupon: false,
    share_coupons: [], //分享优惠券
    coupons: [], //自己的优惠券
    old_coupons: [],
    coupons_temp: {}, //折叠优惠券显示数量
    checkCouponList: [], //选中的优惠券

    language: "",
    timer: null,

    showWechatshar: false,
    path: "/packageF/cart_share/cart_share",
    imageUrl: "",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.sid) {
      this.setData({
        share_id: options.sid,
        path: `/packageF/cart_share/cart_share?sid=${options.sid}`
      });
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let language = wx.getStorageSync('langIndex');
    this.setData({
      'language': language.en
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getData();
  },
  getData() {
    let url = app.getNetAddresss("plugin.cart-sharing.frontend.cart.get-sharing-data"); // 从购物车过来  分享者
    if (this.data.share_id) {
      url = app.getNetAddresss("plugin.cart-sharing.frontend.cart.receive-page-data"); // 被分享
      url += "&share_id=" + this.data.share_id;
    }
    app._getNetWork({
      url: url,
      success: (resdata) => {
        var response = resdata.data;
        if (response.result == 1) {
          if (this.data.share_id) {
            this.setData({
              cartList: response.data.goods || [],
              share_coupons: response.data.coupons || [],
            });
            this.checkAllCoupon();
            this.setData({
              imageUrl: this.data.cartList[0] ? this.data.cartList[0].thumb : '',
            });
          } else {
            this.setData({
              cartList: response.data.cart_list,
              coupons: response.data.coupons || []
            });
            this.initSelectCoupon(this.data.coupons);
          }
          this.setData({
            set: response.data.set,
            member: response.data.member
          });
        } else {
          app.tips(response.msg);
        }
      },
      fail: (res) => {
        console.log(res);
      },
    });
  },
  shareGoods() {
    // 保存分享商品
    console.log("分享商品");
    if (this.data.eachCheckList.length == 0 && this.data.share_coupons.length == 0) {
      return;
    }
    let goods = [];
    let imgUrl = "";
    let link = `/packageF/cart_share/cart_share?sid=`;
    this.data.cartList.map((good) => {
      if (this.data.eachCheckList.includes(String(good.goods_id))) {
        if (!imgUrl) {
          imgUrl = good.goods.thumb;
          this.setData({
            imageUrl: imgUrl
          });
        }
        goods.push({
          goods_id: good.goods_id,
          amount: good.total,
          option_id: good.goods_option ? good.goods_option.id : ''
        });
      }
    });

    let urlStr = app.getNetAddresss("plugin.cart-sharing.frontend.cart.save-sharing-goods");

    wx.showLoading({
      title: '生成中',
      mask: true
    });
    app._postNetWork({
      url: urlStr,
      data: {
        goods: goods
      },
      success: (resdata) => {
        let res = resdata.data;
        if (res.result === 1) {
          link = link + res.data.share_id;
          this.setData({
            path: link
          });
          if (this.data.share_coupons.length > 0) {
            this.shareCoupon(res.data.share_id);
          } else {
            wx.hideLoading();
            this.setData({
              showWechatshar: true
            });
          }
        } else {
          app.tips(res.msg);
        }
      },
      fail: (res) => {
        console.log(res);
      },
    });

  },
  shareCoupon(share_id) {
    // 保存分享优惠券
    let coupon = [];
    this.data.share_coupons.map((item) => {
      coupon.push({
        coupon_id: item.coupon_id,
        amount: item.num
      });
    });
    let urlStr = app.getNetAddresss("plugin.cart-sharing.frontend.cart.save-sharing-coupon");
    app._postNetWork({
      url: urlStr,
      data: {
        share_id: share_id,
        coupon: coupon
      },
      success: (resdata) => {
        let res = resdata.data;
        wx.hideLoading();
        if (res.result === 1) {
          //成功就弹窗
          this.setData({
            showWechatshar: true
          });
        } else {
          app.tips(res.msg);
        }
      },
      fail: (res) => {
        console.log(res);
      },
    });
  },
  getCoupon(e) {
    let data = e.currentTarget.dataset.coupon;
    let index = e.currentTarget.dataset.index;
    // 领取优惠券
    let couponData = [];
    if (data == "all" && this.data.all_get_coupon) {
      // 领完就别领了
      return;
    }
    if (data == "all") {
      this.data.share_coupons.map((item) => {
        couponData.push({
          coupon_id: item.id,
          type: item.share_type
        });
      });
    } else {
      couponData.push({
        coupon_id: data.id,
        type: data.share_type
      });
    }

    let urlStr = app.getNetAddresss("plugin.cart-sharing.frontend.cart.receive-coupon");
    app._postNetWork({
      url: urlStr,
      data: {
        share_id: this.data.share_id,
        couponData: couponData
      },
      success: (resdata) => {
        let res = resdata.data;
        if (res.result === 1) {
          if (data == "all") {
            this.setData({
              all_get_coupon: true
            });
          } else {
            this.checkAllCoupon();
            data.sharing_status = 1;
          }
          this.setData({
            ["share_coupons[" + index + "]"]: data,
          });
          app.tips("领取成功");
        } else {
          app.tips(res.msg);
        }
      },
      fail: (res) => {
        console.log(res);
      },
    });

  },
  checkAllCoupon() {
    let flag = true;
    this.data.share_coupons.map((item) => {
      if (item.sharing_status == 0) {
        flag = false;
      }
    });
    this.setData({
      all_get_coupon: flag
    });
  },
  addIntoCart() {
    // 加入购物车
    let goods_data = [];
    this.data.cartList.map((good) => {
      if (this.data.eachCheckList.includes(String(good.goods_id))) {
        goods_data.push({
          goods_id: good.goods_id,
          total: good.total,
          option_id: good.option_id || ''
        });
      }
    });
    let urlStr = app.getNetAddresss("member.member-cart.batch-store");
    app._postNetWork({
      url: urlStr,
      data: {
        goods_data: goods_data
      },
      success: (resdata) => {
        let res = resdata.data;
        if (res.result === 1) {
          if (res.data.error.length > 0) {
            let msg = "";
            this.data.cartList.map((good) => {
              if (res.data.error.includes(good.goods_id)) {
                msg = msg + good.title + '、';
              }
            });
            app.confirm(msg.slice(0, -1) + "加入购物车失败,请重新选择！", '', false);
          } else {
            app.tips("加入成功");
          }
        } else {
          app.tips(res.msg);
        }
      },
      fail: (res) => {
        console.log(res);
      },
    });
  },
  //初始化优惠券
  initSelectCoupon(coupon) {
    let coupon_data = coupon;
    let result = [];
    let temp = {};

    for (let i = 0; i < coupon_data.length; i++) {
      let num = 0; //优惠券数量
      coupon_data[i].valid = true;
      coupon_data[i].checked = false;
      let _data = coupon_data[i];
      result.push(_data);
      temp[coupon_data[i].coupon_id] = {};
      temp[coupon_data[i].coupon_id].num = num;
    }
    this.setData({
      coupons_temp: temp,
      coupons: result
    });
    // console.log(this.data.coupons, this.data.coupons_temp,"coupons_temp");
  },
  //选择优惠券
  selectCoupon(e, num) {
    let couponBol = e.detail;
    let index = e.currentTarget.dataset.index;
    let item = e.currentTarget.dataset.item;
    // console.log(couponBol, index, item,num);
    this.setData({
      ["coupons[" + index + "].checked"]: couponBol,
    });
    this._screenCoupon(couponBol, item, num);
  },
  //筛选数据优惠券状态
  _screenCoupon(couponBol, valObj, num) {
    let tarValue = valObj;
    let checkCouponList = this.data.checkCouponList;
    if (this.data.checkCouponList.length > 0) {
      for (let i = 0; i < this.data.checkCouponList.length; i++) {
        if (this.data.checkCouponList[i].coupon_id == tarValue.coupon_id) {
          checkCouponList.splice(i, 1);
        }
      }
    }
    if (couponBol) {
      //选中添加
      tarValue.num = num || 1;
      checkCouponList.push(tarValue);
    } else {
      tarValue.num = 0;
    }
    //开启折叠优惠券并且为点击复选框为选中状态
    this.data.coupons_temp[tarValue.coupon_id].num = couponBol ? num || 1 : 0;
    this.setData({
      coupons_temp: this.data.coupons_temp
    });
    this.setData({
      checkCouponList: checkCouponList
    });
  },
  changeCoupon(e) {
    let valObj = e.target.dataset.item;
    let num = e.detail;
    let index = e.target.dataset.index;
    // console.log("=================", e.detail, valObj);
    if (num > valObj.count) {
      wx.showToast({
        icon: "none",
        title: "数量已达上限",
        duration: 2000,
      });
      clearTimeout(this.data.timer);
      this.data.timer = setTimeout(() => {
        // 注意此时修改 value 后会再次触发 change 事件
        this.data.coupons_temp[valObj.coupon_id].num = valObj.count;
        this.setData({
          coupons_temp: this.data.coupons_temp,
        });
      }, 200);
      return;
    } else if (num == "" || num == undefined || num == 0) {
      wx.showToast({
        icon: "none",
        title: "暂不使用请取消勾选",
        duration: 2000,
      });
      return;
    } else {
      clearTimeout(this.data.timer);
      valObj.num = num;
      this.data.coupons_temp[valObj.coupon_id].num = num;
      this.setData({
        coupons_temp: this.data.coupons_temp,
      });
    }

    // clearTimeout方法，以便控制连续触发带来的无用调用
    let value = {
      detail: true,
      currentTarget: {
        dataset: {
          index: index,
          item: valObj,
        },
      },
    };
    if (this.data.timeoutId) {
      clearTimeout(this.data.timeoutId); // 先清除之前的延时，并在下面重新开始计算时间
    }
    this.data.timeoutId = setTimeout(() => {
      // 100毫秒以后执行方法
      this.selectCoupon(value, num);
    }, 200); // 如果还没有执行就又被触发，会根据上面的clearTimeout来清除并重新开始计算
  },
  openCoupon() {
    this.setData({
      showCouponDetail: true,
      old_coupons: JSON.parse(JSON.stringify(this.data.coupons)),
      checkCouponList: JSON.parse(JSON.stringify(this.data.share_coupons)),
    });
  },
  sureCoupon() {
    this.setData({
      showCouponDetail: false,
      share_coupons: JSON.parse(JSON.stringify(this.data.checkCouponList))
    });
  },
  cancelCoupon() {
    this.setData({
      showCouponDetail: false,
      coupons: JSON.parse(JSON.stringify(this.data.old_coupons))
    });
  },
  //点击全选
  allSelect(event) {
    let bol = event.detail;
    this.setData({
      checkAll: bol,
    });
    this.selectBolfun('1');
    if (this.data.selectBol) {
      // console.log(this.selectBol, event, "全选");
      if (this.data.checkAll) {
        let all_carts_id = [];
        this.data.cartList.map((item) => {
          all_carts_id.push(String(item.goods_id));
        });
        this.data.eachCheckList = JSON.parse(JSON.stringify(all_carts_id));
      } else {
        this.data.eachCheckList = [];
      }
      this.setData({
        eachCheckList: this.data.eachCheckList
      });
    }
  },
  selectBolfun(num) {
    // 判断点击是否点击全选 '1', 防止多次触发this.eachCheckList[c_index]变化allSelectHandle
    num === '1' ? this.data.selectBol = true : this.data.selectBol = false;
  },

  //选择商品监听 this.eachCheckList变化会触发
  allSelectHandle(event) {
    let value = event.detail;
    this.selectBolfun('0');
    // console.log(this.data.selectBol,value, "value",this.data.cartList);
    if (!this.data.selectBol) {
      this.data.checkAll = value.length === this.data.cartList.length;
      this.setData({
        checkAll: this.data.checkAll,
        eachCheckList: value
      });
    }
    // console.log(this.data.eachCheckList,"this.eachCheckList");
  },
  //商品输入框输入绑定
  goodinpbtn(e) {
    let index = e.currentTarget.dataset.index;
    let goodval = e.detail.value;
    this.setData({
      [`cartList[${index}].total`]: goodval,
    });
  },
  numberLeft(e) {
    let index = e.currentTarget.dataset.index;
    // console.log(this.cartList[index].total);
    if (this.data.cartList[index].total <= 1) {
      app.tips("商品数量不能为负数或零");
      return;
    }
    this.setData({
      [`cartList[${index}].total`]: Number(this.data.cartList[index].total) - 1,
    });
    // this.changeCount(this.cartList[index].total, this.cartList[index].goods_id, index);
  },

  numberRight(e) {
    let index = e.currentTarget.dataset.index;
    this.data.cartList[index].total = Number(this.data.cartList[index].total) + 1;
    if (this.data.cartList[index].stock && this.data.cartList[index].total > this.data.cartList[index].stock) {
      app.tips(`该商品库存只剩${this.data.cartList[index].stock}件`);
      this.data.cartList[index].total = this.data.cartList[index].stock;
      // return;
    }
    this.setData({
      [`cartList[${index}].total`]: this.data.cartList[index].total,
    });
  },
  onClose() {
    this.setData({
      showWechatshar: false
    });
  },

  //跳转商品详情
  toGoodsInfo(e) {
    let goods_id = e.currentTarget.dataset.goodsid;
    wx.navigateTo({
      url: "/packageA/detail_v2/detail_v2?id=" + goods_id,
    });
  },
  gotoCart() {
    wx.reLaunch({
      url: "/packageG/pages/buy/cart_v2/cart_v2",
    });
  },

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

  },

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

  },

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

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let description = `${this.data.member.nickname}${this.data.set.title}` + (this.data.eachCheckList.length > 0 ? `（共${this.data.eachCheckList.length}款商品）` : '');
    if (this.data.share_id) {
      description = `${this.data.member.nickname}${this.data.set.title}` + (this.data.cartList.length > 0 ? `（共${this.data.cartList.length}款商品）` : '');
    }
    return {
      title: description,
      path: this.data.path,
      imageUrl: this.data.imageUrl,
    };
  },
  onShareTimeline() {
    let description = `${this.data.member.nickname}${this.data.set.title}` + (this.data.eachCheckList.length > 0 ? `（共${this.data.eachCheckList.length}款商品）` : '');
    if (this.data.share_id) {
      description = `${this.data.member.nickname}${this.data.set.title}` + (this.data.cartList.length > 0 ? `（共${this.data.cartList.length}款商品）` : '');
    }
    return {
      title: description,
      imageUrl: this.data.imageUrl,
    };
  }
});