// packageE/community_buying/buying_personal/buying_personal.js
var WxParse = require("../../../wxParse/wxParse");
var app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    time: 24 * 60 * 60 * 1000,
    group_id: 0,
    deliver_id: 0,
    group: {},
    deliver: {},
    hand_goods_obj: {},
    hand_goods_id: 0,
    cart_ids: [],
    disabledInp: false,

    shareShow: false,
    shareOptions: [
      { name: "生成海报", icon: "poster" },
      { name: "分享给好友", icon: "wechat", openType: "share" },
    ],

    themeColor: "#f14e4e", //#f14e4e
  },
  /**
   * 生命周期函数--监听页面加载
   */

  onLoad: function (options) {
    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({ group_id: chil_arr[1] });
        }
        if (chil_arr[0] == "deliver_id") {
          this.setData({ deliver_id: chil_arr[1] });
        }
      }
      console.log(info_arr);
    }
    if (options.buyingid) {
      this.setData({ group_id: options.buyingid });
    }
    if (options.deliver_id) {
      this.setData({ deliver_id: options.deliver_id });
    }

    this.getData();

    console.log(options);
  },

  onChangeTime(e) {
    this.setData({
      timeData: e.detail,
    });
  },

  onSelectShare(evt) {
    this.onCloseShare();
    if (evt.detail.index == 0) {
      this.setData({
        posterShow: true,
      });
    }
    console.log(evt.detail.index);
  },
  onCloseShare() {
    this.setData({ shareShow: false });
  },
  openShareShow() {
    this.setData({
      shareShow: true,
    });
  },

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

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

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

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

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

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},
  gotoBusinessInfo() {
    let id = this.data.group_id;
    let deliver_id = this.data.deliver_id;
    wx.navigateTo({
      url:
        "/packageE/community_buying/business_info/business_info?buyingid=" +
        id +
        "&deliver_id=" +
        deliver_id,
    });
  },

  getData() {
    let that = this;
    let id = this.data.group_id;
    let deliver_id = this.data.deliver_id;
    let urlStr = app.getNetAddresss(
      "plugin.package-deliver.frontend.communityGroups.groupDetail"
    );
    app._getNetWork({
      url: urlStr,
      data: { id, deliver_id },
      success: (resdata) => {
        let res = resdata.data;
        if (res.result !== 1) return this.tips(res.msg);
        let group = res.data.group;
        let deliver = res.data.deliver;
        let time = 0;
        if (group.group_status == 0) {
          time =
            new Date(group.start_time.replace(/-/g, "/")).getTime() -
            new Date().getTime();
        } else if (group.group_status == 1) {
          time =
            new Date(group.end_time.replace(/-/g, "/")).getTime() -
            new Date().getTime();
        }
        this.setData({
          group,
          time,
          deliver,
        });
        let article = res.data.group.description;
        try {
          if (article.indexOf("&#") <= -1) {
            WxParse.wxParse("article", "html", article, that);
          }
        } catch (e) {
          console.log(e);
        }
        if (group.color) this.setData({ themeColor: group.color });
        //获取购物车
        this.getCartList();
      },
    });
  },

  getCartList() {
    let group_id = this.data.group_id;
    let deliver_id = this.data.deliver.id;
    console.log(deliver_id, "deliver_id");
    let urlStr = app.getNetAddresss(
      "plugin.package-deliver.frontend.memberCart.index"
    );
    app._postNetWork({
      url: urlStr,
      data: { group_id, deliver_id },
      success: (resdata) => {
        let res = resdata.data;
        if (res.result !== 1) return this.tips(res.msg);
        let carList = res.data;
        this.setData({
          carList,
        });
        this.getFirstCart(carList);
      },
    });
  },
  close_yz_cartList_popup() {
    this.setData({
      cartListShow: false,
    });
  },
  checkGoods() {
    this.submitGoods();
    // let urlStr = app.getNetAddresss("memberCart.checkout");
    // app._getNetWork({
    //   url: urlStr,
    //   data: {
    //     cart_ids: this.data.cart_ids.join(","),
    //   },
    //   success: (resdata) => {
    //     let res = resdata.data;
    //     if (res.result !== 1) return this.tips(res.msg);
    //     if (res.data.need_choose == 1) {
    //       this.setData({
    //         dispatch_types: res.data.dispatch_types,
    //         showChoose: true,
    //       });
    //     } else {
    //       this.submitGoods();
    //     }
    //   },
    // });
  },
  submitGoods() {
    if (this.data.showChoose) {
      // 配送方式有冲突
      this.data.cart_ids = [];
      for (
        let i = 0;
        i < this.data.dispatch_types[this.data.radioChoose].member_carts.length;
        i++
      ) {
        this.data.cart_ids.push(
          this.data.dispatch_types[this.data.radioChoose].member_carts[i].id
        );
      }
    }
    if (this.data.cart_ids.length == 0) return;

    let { id, deliver_name, deliver_mobile, full_address } = this.data.deliver;
    let changeSelfCarry = {
      id,
      deliver_name,
      deliver_mobile,
      full_address,
      isChangeAddress: true,
    };

    wx.navigateTo({
      url:
        "/packageD/buy/myOrder_v2/myOrder_v2?tag=communityBuy" + 
        "&package_deliver_id=" + this.data.deliver.id +"&group_id=" + this.data.group_id+
        "&cart_ids=" +
        JSON.stringify(this.data.cart_ids)
    });
  },

  openGoodsDetail(e) {
    let item = e.currentTarget.dataset.item;
    if (item.id == this.data.hand_goods_id) {
      this.setData({
        goodsPopupShow: true,
      });
    } else {
      this.data.hand_goods_id = item.id;
      this.getGoodsDetails(item.id, "goodsDetails");
    }
  },
  openCartListPopup() {
    this.setData({
      cartListShow: !this.data.cartListShow,
    });
  },

  //不同规格的同一商品求和
  calculateTotal(arr) {
    let temp = {};
    for (let i in arr) {
      let key = arr[i].goods_id;
      this.data.cart_ids.push(arr[i].id);
      if (temp[key]) {
        // temp[key].goods_id = temp[key].goods_id;
        temp[key].total = temp[key].total + arr[i].total;
      } else {
        temp[key] = {};
        temp[key].goods_id = arr[i].goods_id;
        temp[key].total = arr[i].total;
        temp[key].id = arr[i].id;
      }
    }
    this.setData({
      goodsCartsTotal: temp,
    });
  },

  //统计购物车的总价格和总数量
  getFirstCart(data) {
    this.data.carts = data;
    let cartsNum = 0;
    let cartsTotal = 0;
    this.data.carts.forEach((item) => {
      cartsNum += item.total;
      cartsTotal += item.total * item.goods.price;
    });
    cartsTotal = parseFloat(cartsTotal).toFixed(2);
    this.setData({
      cartsNum,
      cartsTotal,
    });
    this.calculateTotal(this.data.carts);
  },

  updateCartNum(evt) {
    console.log(evt);
    let item = evt.target.dataset.item;
    let cartid = evt.target.dataset.cartid;
    let value = evt.detail.value;
    let total = value;
    if (value == "" || value == 0) {
      total = 0;
    }
    if (this.data.goodsCartsTotal[item.id].total == total) return;
    this.reduceCartRequest({
      goods: item,
      cartid,
      total,
    });
  },

  reduceCartNum(evt) {
    let item = evt.currentTarget.dataset.item;
    let cartid = evt.currentTarget.dataset.cartid;
    this.reduceCartRequest({ goods: item, cartid });
  },
  reduceCartRequest(obj) {
    let { goods, cartid, total } = obj;
    let id = goods.id;
    let num = 0;
    if (total || total === 0) {
      num = total;
    } else {
      let obj = this.data.goodsCartsTotal;
      num = Number(obj[id].total) - 1;
      this.data.goodsCartsTotal[id].total = num;
    }

    let urlStr = "";
    let json = {};
    if (num <= 0) {
      //清楚购物车
      urlStr = app.getNetAddresss(
        "plugin.package-deliver.frontend.memberCart.destroy"
      );
      json = {
        ids: cartid,
      };
    } else {
      urlStr = app.getNetAddresss(
        "plugin.package-deliver.frontend.memberCart.updateNumV2"
      );
      json = {
        id: cartid,
        num: num,
      };
    }
    this.setData({
      disabledInp: true
    })
    app._getNetWork({
      url: urlStr,
      data: json,
      success: (resdata) => {
        var res = resdata.data;
        this.tips(res.msg);
        // if (res.result == 1) {
          this.getCartList();
        // }
        this.setData({
          disabledInp: false
        })
      },
    });
  },

  addCartNum(evt) {
    let item = evt.currentTarget.dataset.item;
    let cartid = evt.currentTarget.dataset.cartid;
    console.log(item);
    item.id = item.goods_id;
    this.addCartRequest({ goods: item, cartid });
  },

  //加入购物车
  addCartRequest(obj) {
    let { goods, cartid, total, optionsId } = obj;
    console.log("加入购物车");
    if (goods.vip_level_status && goods.vip_level_status.status == 1) {
      return this.tips(goods.vip_level_status.tips);
    }

    if (goods.stock == 0) {
      return this.tips("库存为零");
    }
    let num = 1;
    let urlStr = "";
    let jsons = {};
    if (!app._isTextEmpty(this.data.goodsCartsTotal[goods.id]) && cartid != 0) {
      if (this.data.goodsCartsTotal[goods.id].total >= goods.stock) {
        return this.tips("库存不足");
      }
      let obj = this.data.goodsCartsTotal;
      num = Number(obj[goods.id].total) + 1;
      if (total && total > 0) {
        num = total;
      }
      this.data.goodsCartsTotal[goods.id].total = num;
      urlStr = app.getNetAddresss(
        "plugin.package-deliver.frontend.memberCart.updateNumV2"
      );
      jsons = {
        id: cartid,
        num: num,
      };
    } else {
      urlStr = app.getNetAddresss(
        "plugin.package-deliver.frontend.memberCart.store"
      );
      if (total && total > 0) {
        num = total;
      }
      jsons = {
        goods_id: goods.id,
        total: num,
      };
      if (optionsId && optionsId > 0) jsons.option_id = optionsId;
    }
    let deliver_id = this.data.deliver.id;
    jsons.group_id = this.data.group_id;
    jsons.deliver_id = deliver_id;
    app._getNetWork({
      url: urlStr,
      data: jsons,
      success: (resdata) => {
        var res = resdata.data;
        this.tips(res.msg);
        if (res.result == 1) {
          this.getCartList();
        }
      },
    });
  },
  cartListAdd(item) {
    console.log(item.detail);
    console.log(this.data.goodsCartsTotal);
    this.addCartRequest({
      goods: item.detail.goods,
      cartid: item.detail.id,
      total: item.detail.total + 1,
    });
  },

  cartListReduce(item) {
    console.log(item.detail);
    this.reduceCartRequest({
      goods: item.detail.goods,
      cartid: item.detail.id,
      total: item.detail.total - 1,
    });
  },
  goodsDetailCartAdd(evt) {
    this.setData({
      goodsPopupShow: false,
      specsShow: true,
    });
  },

  cartListInputBlur(item) {
    let cartList = this.data.carList;
    for (let obj of cartList) {
      console.log(item);
      if (obj.id == item.detail.id) {
        if (obj.total == item.detail.total) return;
      }
    }
    this.reduceCartRequest({
      goods: item.detail.goods,
      cartid: item.detail.id,
      total: item.detail.total,
    });
  },

  openSpecs(e) {
    let item = e.currentTarget.dataset.item;
    console.log(item);
    if (item.id == this.data.hand_goods_id) {
      this.setData({
        specsShow: true,
      });
    } else {
      this.data.hand_goods_id = item.id;
      this.getGoodsDetails(item.id, "specs");
    }
  },
  close_yz_specs_popup(e) {
    console.log(e);
    if (e.detail.clicktype == 1) {
      //点击确认按钮
      this.addCartRequest({
        goods: { id: e.detail.goodsId },
        cartid: e.detail.cartid,
        total: e.detail.goodsCount,
        optionsId: e.detail.optionsId,
      });
      this.setData({
        specsShow: false,
      });
    } else {
      this.setData({
        specsShow: false,
      });
    }
  },
  getGoodsDetails(id, type) {
    let urlStr = app.getNetAddresss("goods.goods.get-goods-page");
    app._postNetWork({
      url: urlStr,
      data: { id: Number(id) },
      success: (resdata) => {
        let res = resdata.data;
        if (res.result !== 1) return this.tips(res.msg);
        let name = "";
        if (type == "goodsDetails") {
          name = "goodsPopupShow";
        } else if (type == "specs") {
          name = "specsShow";
        }
        res.data.get_goods.end_time = this.data.time;
        this.setData({
          [name]: true,
          hand_goods_obj: res.data.get_goods,
        });
      },
    });
  },

  tips(msg) {
    wx.showToast({
      title: msg,
      icon: "none",
    });
    return;
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let path =
      "/packageE/community_buying/buying_personal/buying_personal?buyingid=" +
      this.data.group_id +
      "&deliver_id=" +
      this.data.deliver_id;
    var mid = wx.getStorageSync('yz_uid');
    if (mid) {
      path = path + '&mid=' + mid
    }
    let obj = { path };
    if (this.data.group.share_img) {
      obj.imageUrl = this.data.group.share_img;
    }
    console.log(obj);
    return obj;
  },
});
