// lionfish_comshop/pages/order/shopCart.js
var util = require('../../utils/util.js');
var status = require('../../utils/index.js');
var a = require("../../utils/public");
var app = getApp();
var addFlag = 1;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    allselect: false,
    theme_type: '',
    community_id: 0,
    loadover: false,
    show_1: 0,
    allnum: 0,
    tablebar: 3,
    allcount: "0.00",
    recount: "0.00",
    carts: {},
    isEmpty: false,
    is_login: true,
    cartNum: 0,
    isIpx: false,
    disAmount: 0,
    totalAmount: 0,
    reduceNum: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    wx.hideTabBar();
    var that = this;
    wx.showLoading();
    util.check_login() ? this.setData({
      is_login: true
    }) : (this.setData({
      is_login: false
    }), wx.hideTabBar());

    that.setData({
      loadover: true,
      isIpx: app.globalData.isIpx
    });

    var allnum = 0;
    var allcount = 0.00;
    var that = this;
    var community = wx.getStorageSync('community');
    var community_id = community.communityId;

    that.setData({
      community_id: community_id
    })
    that.showCartGoods();
  },

  /**
   * 授权成功回调
   */
  authSuccess: function() {
    wx.reLaunch({
      url: '/lionfish_comshop/pages/order/shopCart',
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var that = this;
    (0, status.cartNum)('', true).then((res) => {
      res.code == 0 && that.setData({
        cartNum: res.data
      })
    });
    var show_1 = this.data.show_1;
    if (show_1 > 0) {
      wx.showLoading();
      util.check_login() ? this.setData({
        is_login: true
      }) : (this.setData({
        is_login: false
      }), wx.hideTabBar());
      that.showCartGoods();
    }
    this.setData({
      show_1: show_1 + 1,
      tabbarRefresh: true
    })
  },

  /**
   * 获取购物车信息20190604
   */
  showCartGoods: function(){
    let that = this;
    var community = wx.getStorageSync('community');
    var community_id = community.communityId;
    console.log('onshow购物车里面的community_id:');
    that.setData({ community_id: community_id })
    var token = wx.getStorageSync('token');
    app.util.request({
      'url': 'entry/wxapp/index',
      'data': {
        controller: 'car.show_cart_goods',
        token: token,
        community_id: community_id,
        buy_type: 'dan',
      },
      dataType: 'json',
      success: function (res) {
        wx.hideLoading();
        if (res.data.code == 0) {
          //un login carts
          let carts = res.data.carts;
          let isEmpty = true;
          if (Object.keys(carts).length != 0) {
            isEmpty = false;
            carts = that.sortCarts(carts);
          }
          let is_comunity_rest = res.data.is_comunity_rest;
          that.setData({
            carts,
            isEmpty,
            is_comunity_rest,
            open_man_orderbuy: res.data.open_man_orderbuy,
            man_orderbuy_money: res.data.man_orderbuy_money * 1,
            is_show_guess_like: res.data.is_show_guess_like
          })
          that.xuan_func();
        } else {
          that.setData({
            is_login: false
          })
          wx.hideTabBar();
        }
      }
    })
  },

  onHide: function() {
    this.setData({
      tabbarRefresh: false
    })
    console.log('onHide')
  },

  /**
   * 商品排序
   */
  sortCarts: function(carts) {
    let reduceNum = 0;
    let is_open_fullreduction = 0;
    let full_reducemoney = 0;
    let full_money = 0;

    for (let i in carts) {
      is_open_fullreduction = carts[i].is_open_fullreduction;
      full_reducemoney = carts[i].full_reducemoney;
      full_money = carts[i].full_money;

      let shopcarts = carts[i].shopcarts;
      shopcarts.forEach(function(item) {
        if (item.can_man_jian == 1) reduceNum++;
      })
      shopcarts.sort(function(x, y) {
        if (x.can_man_jian < y.can_man_jian) {
          return 1;
        }
        if (x.can_man_jian > y.can_man_jian) {
          return -1;
        }
        return 0;
      });
    }
    this.setData({
      reduceNum,
      is_open_fullreduction,
      full_reducemoney,
      full_money
    });
    return carts;
  },

  xuan_func: function() {
    var allnum = 0;
    var allcount = 0

    var flag = 1;
    var allselect = false;
    var all_cant_buy = 1;
    for (var i in this.data.carts) {
      var count = 0;
      this.data.carts[i].goodstypeselect = 0;
      this.data.carts[i].goodstype = this.data.carts[i].shopcarts.length;

      for (var j = 0; j < this.data.carts[i].shopcarts.length; j++) {
        let shopcartsItem = this.data.carts[i].shopcarts[j];
        if (shopcartsItem.isselect == false && shopcartsItem.can_buy == 1) flag = 0;
        if (shopcartsItem.isselect && shopcartsItem.can_buy == 1) {
          all_cant_buy = 0;
          count = count + parseFloat(shopcartsItem.currntprice) * parseFloat(shopcartsItem.goodsnum);
          this.data.carts[i].goodstypeselect++;
          allnum = parseInt(allnum) + parseInt(shopcartsItem.goodsnum);
        }

        if (shopcartsItem.can_buy == 0) shopcartsItem.isselect = false;
      }
      this.data.carts[i].count = count.toFixed(2);
      allcount = allcount + count;
    }
    if (flag == 1 && all_cant_buy == 0) { //是全部选中
      allselect = true;
    }
    this.setData({
      allselect: allselect,
      allnum: allnum,
      allcount: allcount.toFixed(2),
      carts: this.data.carts
    });
    this.calcAmount();
  },

  //编辑点击事件处理函数
  edit: function(e) {
    var index = parseInt(e.target.dataset.index);
    this.data.carts[index].caredit = "none";
    this.data.carts[index].finish = "inline";
    for (var i = 0; i < this.data.carts[index].shopcarts.length; i++) {
      this.data.carts[index].shopcarts[i].edit = "none";
      this.data.carts[index].shopcarts[i].finish = "inline";
      this.data.carts[index].shopcarts[i].description = "onedit-description";
      this.data.carts[index].shopcarts[i].cartype = "block";
    }
    this.setData({
      carts: this.data.carts
    })

  },

  //完成点击事件处理函数
  finish: function(e) {
    var index = parseInt(e.target.dataset.index);
    this.data.carts[index].caredit = "inline";
    this.data.carts[index].finish = "none";
    for (var i = 0; i < this.data.carts[index].shopcarts.length; i++) {
      this.data.carts[index].shopcarts[i].edit = "inline";
      this.data.carts[index].shopcarts[i].finish = "none";
      this.data.carts[index].shopcarts[i].description = "description";
      this.data.carts[index].shopcarts[i].cartype = "inline";
    }
    this.setData({
      carts: this.data.carts
    })
  },

  goLink: function(event) {
    let link = event.currentTarget.dataset.link;
    wx.redirectTo({
      url: link
    })

  },

  goGoods: function(event) {
    let id = event.currentTarget.dataset.type;

    var pages_all = getCurrentPages();
    if (pages_all.length > 3) {
      wx.redirectTo({
        url: '/Snailfish_shop/pages/goods/index?id=' + id
      })
    } else {
      wx.navigateTo({
        url: '/Snailfish_shop/pages/goods/index?id=' + id
      })
    }

  },

  //店铺点击选择事件
  shopselect: function(e) {
    var index = parseInt(e.target.dataset.index);
    console.log(index)
    var allselect = this.data.allselect;
    var isselect = this.data.carts[index].isselect;
    var allnum = 0;
    var allcount = 0.00;
    var count = 0.00;
    if (isselect == true) { //店铺为选中状态
      this.data.carts[index].isselect = false;
      allselect = false;
      for (var i = 0; i < this.data.carts[index].shopcarts.length; i++) { //循环商店下商品，改成不选中
        if (this.data.carts[index].shopcarts[i].isselect == true) {
          this.data.carts[index].shopcarts[i].isselect = false;
          allnum = parseInt(allnum) + parseInt(this.data.carts[index].shopcarts[i].goodsnum);
          this.data.carts[index].goodstypeselect = this.data.carts[index].goodstypeselect - 1;
        }

      }
      allnum = this.data.allnum - allnum; //去除不选中商店的产品数量
      allcount = parseFloat(this.data.allcount) - parseFloat(this.data.carts[index].count);
      this.data.carts[index].count = "0.00";
      this.setData({
        carts: this.data.carts,
        allnum: allnum,
        allcount: allcount.toFixed(2),
        allselect: allselect
      });
    } else {
      console.log(index)
      var addcount = 0.00;
      this.data.carts[index].isselect = true;
      for (var i = 0; i < this.data.carts[index].shopcarts.length; i++) {
        if (this.data.carts[index].shopcarts[i].isselect == false) {
          this.data.carts[index].shopcarts[i].isselect = true;
          this.data.carts[index].goodstypeselect = this.data.carts[index].goodstypeselect + 1;
          allnum = parseInt(allnum) + parseInt(this.data.carts[index].shopcarts[i].goodsnum);
          addcount = addcount + parseFloat(this.data.carts[index].shopcarts[i].currntprice) * this.data.carts[index].shopcarts[i].goodsnum;
        }
        count = count + parseFloat(this.data.carts[index].shopcarts[i].currntprice) * this.data.carts[index].shopcarts[i].goodsnum;
      }
      allnum = this.data.allnum + allnum;
      allcount = parseFloat(this.data.allcount) + addcount;
      this.data.carts[index].count = count.toFixed(2);
      var flag = 1;
      for (var i in this.data.carts) {
        // for (var i = 0; i < this.data.carts.length; i++) {//是否是全部选中
        for (var j = 0; j < this.data.carts[i].shopcarts.length; j++)
          if (this.data.carts[i].shopcarts[j].isselect == false)
            flag = 0;
      }
      if (flag == 1) { //是全部选中
        allselect = true;
      }
      this.setData({
        carts: this.data.carts,
        allnum: allnum,
        allcount: allcount.toFixed(2),
        allselect: allselect
      });
    }
    this.go_record();
  },

  //点击商品选中事件函数
  goodsselect: function(e) {
    var parentid = parseInt(e.target.dataset.parentid);
    var index = parseInt(e.target.dataset.index);
    var allselect = this.data.allselect;
    var isselect = this.data.carts[parentid].shopcarts[index].isselect;
    console.log(isselect);

    if (isselect == true) { //商品选中状态
      this.data.carts[parentid].shopcarts[index].isselect = false;
      if (allselect)
        allselect = false;

      this.data.carts[parentid].goodstypeselect = parseInt(this.data.carts[parentid].goodstypeselect) - 1;
      if (this.data.carts[parentid].goodstypeselect <= 0) { //选中商品为0
        this.data.carts[parentid].isselect = false;
      }
      var allnum = parseInt(this.data.allnum) - parseInt(this.data.carts[parentid].shopcarts[index].goodsnum);
      var allcount = parseFloat(this.data.allcount) - parseFloat(this.data.carts[parentid].shopcarts[index].currntprice) * this.data.carts[parentid].shopcarts[index].goodsnum;
      var count = parseFloat(this.data.carts[parentid].count) - parseFloat(this.data.carts[parentid].shopcarts[index].currntprice) * this.data.carts[parentid].shopcarts[index].goodsnum;
      this.data.carts[parentid].count = count.toFixed(2);
      this.setData({
        carts: this.data.carts,
        allnum: allnum,
        allcount: allcount.toFixed(2),
        allselect: allselect
      });
    } else { //商品为非选中状态
      this.data.carts[parentid].shopcarts[index].isselect = true;
      this.data.carts[parentid].goodstypeselect = parseInt(this.data.carts[parentid].goodstypeselect) + 1;

      if (this.data.carts[parentid].goodstypeselect > 0) { //选中商品个数大于0
        this.data.carts[parentid].isselect = true;
      }
      console.log(this.data.carts);
      var flag = 1;
      //for (var i = 0; i < this.data.carts.length; i++) {//判断是否是全部选中
      for (var i in this.data.carts) {
        console.log('in');
        for (var j = 0; j < this.data.carts[i].shopcarts.length; j++)
          if (this.data.carts[i].shopcarts[j].isselect == false)
            flag = 0;
      }
      // console.log(flag);

      if (flag == 1) { //全部商品选中
        allselect = true;
      }
      var allnum = parseInt(this.data.allnum) + parseInt(this.data.carts[parentid].shopcarts[index].goodsnum);
      var allcount = parseFloat(this.data.allcount) + parseFloat(this.data.carts[parentid].shopcarts[index].currntprice) * this.data.carts[parentid].shopcarts[index].goodsnum;
      var count = parseFloat(this.data.carts[parentid].count) + parseFloat(this.data.carts[parentid].shopcarts[index].currntprice) * this.data.carts[parentid].shopcarts[index].goodsnum;
      this.data.carts[parentid].count = count.toFixed(2);
      this.setData({
        carts: this.data.carts,
        allnum: allnum,
        allcount: allcount.toFixed(2),
        allselect: allselect
      });
    }
    this.go_record();
  },

  //全部选中事件函数
  allselect: function(e) {
    var allselect = this.data.allselect;
    var carts = this.data.carts;

    if (allselect) { //点击前为全部选中状态
      allselect = false;
      var allnum = 0;
      var allcount = 0.00;
      for (var i in this.data.carts) {
        this.data.carts[i].count = "0.00";
        this.data.carts[i].isselect = false;
        this.data.carts[i].goodstypeselect = 0;
        for (var j in this.data.carts[i].shopcarts)
          this.data.carts[i].shopcarts[j].isselect = false;
      }
      this.setData({
        carts: this.data.carts,
        allnum: allnum,
        allcount: allcount.toFixed(2),
        allselect: allselect
      });
    } else { //点击前为不全部选址状态
      allselect = true;
      var allnum = 0;
      var allcount = 0.00;

      for (var i in this.data.carts) {
        var count = 0;
        this.data.carts[i].isselect = true;
        let shopcarts = this.data.carts[i].shopcarts;
        this.data.carts[i].goodstypeselect = shopcarts.length;
        for (var j in shopcarts) {
          if (shopcarts[j].can_buy == 1) {
            count = count + parseFloat(shopcarts[j].currntprice) * parseFloat(shopcarts[j].goodsnum);
            allnum = parseInt(allnum) + parseInt(this.data.carts[i].shopcarts[j].goodsnum);
            shopcarts[j].isselect = true;
          }
        }
        this.data.carts[i].count = count.toFixed(2);
        allcount = allcount + count;
      }
      //console.log(this.data.carts);

      this.setData({
        carts: this.data.carts,
        allnum: allnum,
        allcount: allcount.toFixed(2),
        allselect: allselect
      });
    }
    this.go_record();
  },

  //减少商品数量函数
  regoodsnum: function(e) {
    var parentid = parseInt(e.currentTarget.dataset.parentid);
    var index = parseInt(e.currentTarget.dataset.index);

    var that = this;
    var goodsnum = this.data.carts[parentid].shopcarts[index].goodsnum;
    if (goodsnum == 1) { //减少前商品数量为1
      that.cofirm_del(parentid, index);
    } else { //减少前商品的数量不为1
      if (this.data.carts[parentid].shopcarts[index].isselect == true) { //商品为选中状态
        var allnum = parseInt(this.data.allnum) - 1;
        var allcount = parseFloat(this.data.allcount) - parseFloat(this.data.carts[parentid].shopcarts[index].currntprice);
        var count = parseFloat(this.data.carts[parentid].count) - parseFloat(this.data.carts[parentid].shopcarts[index].currntprice);
        that.data.carts[parentid].count = count.toFixed(2);
        this.data.carts[parentid].shopcarts[index].goodsnum = this.data.carts[parentid].shopcarts[index].goodsnum - 1;
        this.setData({
          carts: this.data.carts,
          allnum: allnum,
          allcount: allcount.toFixed(2),
        });
      } else { //商品为非选中状态
        this.data.carts[parentid].shopcarts[index].goodsnum = parseInt(this.data.carts[parentid].shopcarts[index].goodsnum) - 1;
        this.setData({
          carts: this.data.carts
        });
      }
    }
    if (this.data.carts[parentid].shopcarts[index].goodstype == '') {
      let goodsnum = that.data.carts[parentid].shopcarts[index].goodsnum * 1;
      let gid = e.currentTarget.dataset.gid;
      status.indexListCarCount(gid, goodsnum)
    }
    that.go_record();
  },

  /**
   * 确认删除提示框
   */
  cofirm_del: function(parentid, index, type = 1) {
    let that = this;
    wx.showModal({
      title: '提示',
      content: '确定删除这件商品吗？',
      confirmColor: '#FF0000',
      success: function(res) {
        if (res.confirm) {
          if (that.data.carts[parentid].shopcarts[index].goodstype == '') {
            let gid = that.data.carts[parentid].shopcarts[index].id;
            status.indexListCarCount(gid, 0);
          }
          var del_car_keys = that.data.carts[parentid].shopcarts[index].key;
          // 满减商品数量减一
          let reduceNum = that.data.reduceNum;
          if (that.data.carts[parentid].shopcarts[index].can_man_jian == 1) {
            reduceNum--;
            that.setData({
              reduceNum
            });
            console.log(reduceNum);
          }

          if (that.data.carts[parentid].shopcarts[index].isselect == true) { //商品为选中状态
            var allnum = that.data.allnum - 1;
            var allcount = parseFloat(that.data.allcount) - parseFloat(that.data.carts[parentid].shopcarts[index].currntprice);
            var count = parseFloat(that.data.carts[parentid].count) - parseFloat(that.data.carts[parentid].shopcarts[index].currntprice);
            that.data.carts[parentid].count = count.toFixed(2);
            that.data.carts[parentid].goodstype = that.data.carts[parentid].goodstype - 1;
            that.data.carts[parentid].goodstypeselect = that.data.carts[parentid].goodstypeselect - 1
            if (that.data.carts[parentid].goodstype == 0) { //购物车商店商品类别为0，去掉这个商店
              // that.data.carts.splice(parentid, 1)
              let carts = that.data.carts;
              delete carts[parentid];
              if (Object.keys(carts).length == 0) that.setData({
                isEmpty: true
              })
            } else { //不为0，去掉这个商品
              that.data.carts[parentid].shopcarts.splice(index, 1);
              //判断全选状态，有失效商品20190212
              that.isAllSelect();
            }
            that.setData({
              carts: that.data.carts,
              allnum: allnum,
              allcount: allcount.toFixed(2),
            });
          } else { //商品为非选中状态
            that.data.carts[parentid].goodstype = that.data.carts[parentid].goodstype - 1;
            if (that.data.carts[parentid].goodstype == 0) {
              // that.data.carts.splice(parentid, 1)
              let carts = that.data.carts;
              delete carts[parentid];
              if (Object.keys(carts).length == 0) that.setData({
                isEmpty: true
              })
            } else {
              that.data.carts[parentid].shopcarts.splice(index, 1);
            }
            that.setData({
              carts: that.data.carts
            });
          }
          that.del_car_goods(del_car_keys);
          that.calcAmount();
        } else {
          console.log('取消删除')
        }
      }
    })
  },

  /**
   * 20190212
   * 删除选中商品，存在失效商品全选状态判断
   */
  isAllSelect: function() {
    var flag = 1,
      allselect = false,
      carts = this.data.carts,
      isCanBuy = 0;
    for (let i in carts) {
      for (let j = 0; j < carts[i].shopcarts.length; j++) {
        if (carts[i].shopcarts[j].can_buy == 1) isCanBuy = 1;
        if (carts[i].shopcarts[j].isselect == false && carts[i].shopcarts[j].can_buy == 1) flag = 0;
      }
    }
    // console.log(flag);
    if (flag == 1 && isCanBuy == 1) allselect = true;

    this.setData({
      allselect: allselect
    })
  },


  //添加商品数量函数
  addgoodsnum: function(e) {
    if (addFlag == 0) return;
    addFlag = 0;
    var parentid = parseInt(e.currentTarget.dataset.parentid);
    var index = parseInt(e.currentTarget.dataset.index);
    var that = this;
    var max_quantity = parseInt(this.data.carts[parentid].shopcarts[index].max_quantity);

    if (this.data.carts[parentid].shopcarts[index].isselect == true) { //商品为选中状态
      var allnum = parseInt(this.data.allnum) + 1;
      var allcount = parseFloat(this.data.allcount) + parseFloat(this.data.carts[parentid].shopcarts[index].currntprice);
      var count = parseFloat(this.data.carts[parentid].count) + parseFloat(this.data.carts[parentid].shopcarts[index].currntprice);
      that.data.carts[parentid].count = count.toFixed(2);

      if (this.data.carts[parentid].shopcarts[index].goodsnum < max_quantity) {
        this.data.carts[parentid].shopcarts[index].goodsnum = parseInt(this.data.carts[parentid].shopcarts[index].goodsnum) + 1;
      } else {
        this.data.carts[parentid].shopcarts[index].goodsnum = max_quantity;
        allnum--;
        var msg = '最多购买' + max_quantity + '个';
        wx.showToast({
          title: msg,
          icon: 'none',
          duration: 2000
        })
        return false;
      }

      this.setData({
        carts: this.data.carts,
        allnum: allnum,
        allcount: allcount.toFixed(2)
      });
    } else { //商品为非选中状态
      if (parseInt(this.data.carts[parentid].shopcarts[index].goodsnum) < max_quantity) {
        this.data.carts[parentid].shopcarts[index].goodsnum = parseInt(this.data.carts[parentid].shopcarts[index].goodsnum) + 1;
      } else {
        var msg = '最多购买' + max_quantity + '个';
        wx.showToast({
          title: msg,
          icon: 'none',
          duration: 2000
        })
        return false;
      }
    }

    var token = wx.getStorageSync('token');
    var keys_arr = [];
    var all_keys_arr = [];
    var allnum = this.data.allnum;

    var carts = this.data.carts;

    for (var i in carts) {
      for (var j in carts[i]['shopcarts']) {
        //if (carts[i]['shopcarts'][j]['isselect']) {
        keys_arr.push(carts[i]['shopcarts'][j]['key']);
        // }
        all_keys_arr.push(carts[i]['shopcarts'][j]['key'] + '_' + carts[i]['shopcarts'][j]['goodsnum']);
      }
    }

    app.util.request({
      'url': 'entry/wxapp/index',
      'data': {
        controller: 'car.checkout_flushall',
        'token': token,
        'car_key': keys_arr,
        community_id: that.data.community_id,
        'all_keys_arr': all_keys_arr
      },
      method: 'POST',
      dataType: 'json',
      success: function(msg) {
        if (msg.data.code == 0) {
          that.setData({
            carts: that.data.carts
          });
          (0, status.cartNum)('', true).then((res) => {
            res.code == 0 && that.setData({
              cartNum: res.data
            })
          });
          if (that.data.carts[parentid].shopcarts[index].goodstype == '') {
            let goodsnum = that.data.carts[parentid].shopcarts[index].goodsnum * 1;
            let gid = e.currentTarget.dataset.gid;
            status.indexListCarCount(gid, goodsnum);
          }
        } else {
          that.data.carts[parentid].shopcarts[index].goodsnum = parseInt(that.data.carts[parentid].shopcarts[index].goodsnum) - 1;
          if (that.data.carts[parentid].shopcarts[index].isselect == true) {
            var allcount_new = parseFloat(that.data.allcount) - parseFloat(that.data.carts[parentid].shopcarts[index].currntprice);
            var count_new = parseFloat(that.data.carts[parentid].count) - parseFloat(that.data.carts[parentid].shopcarts[index].currntprice);
            that.data.carts[parentid].count = count_new.toFixed(2);
            allnum--;
            that.setData({
              allnum: allnum,
              allcount: allcount_new.toFixed(2)
            });
          }
          that.setData({
            carts: that.data.carts
          });
          console.log(that.data.carts[parentid].shopcarts[index].goodsnum);

          wx.showToast({
            title: msg.data.msg,
            icon: 'none',
            duration: 2000
          })
        }
        addFlag = 1;
        that.calcAmount();
      }
    })
    // this.calcAmount();
  },

  /**
   * 输入框监控
   */
  changeNumber: function(e) {
    wx.hideLoading();
    var that = this;
    var parentid = parseInt(e.currentTarget.dataset.parentid);
    var index = parseInt(e.currentTarget.dataset.index);
    var iptVal = e.detail.value;
    var newCount = that.count_goods(parentid, index);
    let lastGoodsnum = this.data.carts[parentid].shopcarts[index].goodsnum;
    console.log(iptVal);
    if (iptVal > 0) {
      var max_quantity = parseInt(this.data.carts[parentid].shopcarts[index].max_quantity);
      if (iptVal > max_quantity) {
        iptVal = max_quantity;
        wx.showToast({
          title: '不能购买更多啦',
          icon: 'none'
        })
      }
      this.data.carts[parentid].shopcarts[index].goodsnum = iptVal;
      if (that.data.carts[parentid].shopcarts[index].isselect == true) { //商品为选中状态
        newCount = that.count_goods(parentid, index);
        console.log(newCount)
      }
      this.setData({
        carts: this.data.carts,
        allnum: newCount.allnum,
        allcount: newCount.allcount
      });

      var token = wx.getStorageSync('token');
      var keys_arr = [];
      var all_keys_arr = [];
      var allnum = this.data.allnum;
      var carts = this.data.carts;

      for (var i in carts) {
        for (var j in carts[i]['shopcarts']) {
          keys_arr.push(carts[i]['shopcarts'][j]['key']);
          all_keys_arr.push(carts[i]['shopcarts'][j]['key'] + '_' + carts[i]['shopcarts'][j]['goodsnum']);
        }
      }

      app.util.request({
        'url': 'entry/wxapp/index',
        'data': {
          controller: 'car.checkout_flushall',
          'token': token,
          'car_key': keys_arr,
          community_id: that.data.community_id,
          'all_keys_arr': all_keys_arr
        },
        method: 'POST',
        dataType: 'json',
        success: function(msg) {
          if (msg.data.code == 0) {
            that.setData({
              carts: that.data.carts
            });
            (0, status.cartNum)('', true).then((res) => {
              res.code == 0 && that.setData({
                cartNum: res.data
              })
            });
            if (that.data.carts[parentid].shopcarts[index].goodstype == '') {
              let goodsnum = that.data.carts[parentid].shopcarts[index].goodsnum * 1;
              let gid = that.data.carts[parentid].shopcarts[index].id;
              status.indexListCarCount(gid, goodsnum);
            }
            that.go_record();
          } else {
            that.data.carts[parentid].shopcarts[index].goodsnum = lastGoodsnum;
            if (that.data.carts[parentid].shopcarts[index].isselect == true) { //商品为选中状态
              newCount = that.count_goods(parentid, index);
            }
            that.setData({
              carts: that.data.carts,
              allnum: newCount.allnum,
              allcount: newCount.allcount
            });

            wx.showToast({
              title: msg.data.msg,
              icon: 'none',
              duration: 2000
            })
          }
        }
      })
    } else {
      wx.hideLoading();
      this.data.carts[parentid].shopcarts[index].goodsnum = 1;
      if (that.data.carts[parentid].shopcarts[index].isselect == true) { //商品为选中状态
        newCount = that.count_goods(parentid, index);
      }
      this.setData({
        carts: this.data.carts,
        allnum: newCount.allnum,
        allcount: newCount.allcount
      });
      var token = wx.getStorageSync('token');
      var keys_arr = [];
      var all_keys_arr = [];
      var allnum = this.data.allnum;
      var carts = this.data.carts;

      for (var i in carts) {
        for (var j in carts[i]['shopcarts']) {
          keys_arr.push(carts[i]['shopcarts'][j]['key']);
          all_keys_arr.push(carts[i]['shopcarts'][j]['key'] + '_' + carts[i]['shopcarts'][j]['goodsnum']);
        }
      }

      app.util.request({
        'url': 'entry/wxapp/index',
        'data': {
          controller: 'car.checkout_flushall',
          'token': token,
          'car_key': keys_arr,
          community_id: that.data.community_id,
          'all_keys_arr': all_keys_arr
        },
        method: 'POST',
        dataType: 'json',
        success: function(msg) {
          if (msg.data.code == 0) {
            that.setData({
              carts: that.data.carts
            });
            (0, status.cartNum)('', true).then((res) => {
              res.code == 0 && that.setData({
                cartNum: res.data
              })
            });
            if (that.data.carts[parentid].shopcarts[index].goodstype == '') {
              let goodsnum = that.data.carts[parentid].shopcarts[index].goodsnum * 1;
              let gid = that.data.carts[parentid].shopcarts[index].id;
              status.indexListCarCount(gid, goodsnum);
            }
            that.go_record();
          }
        }
      })
      that.cofirm_del(parentid, index);
    }
  },

  count_goods: function(parentid, index) {
    let cart = this.data.carts[parentid];
    let allnum = 0;
    let allcount = 0;

    cart.shopcarts.forEach(function(item, idx) {
      if (item.isselect) {
        allcount += item.currntprice * parseInt(item.goodsnum);
        allnum += parseInt(item.goodsnum);
      }
    })

    return {
      allnum,
      allcount: allcount.toFixed(2)
    }
  },

  //删除商品函数
  delgoods: function(e) {
    var parentid = parseInt(e.target.dataset.parentid);
    var index = parseInt(e.target.dataset.index);
    var that = this;
    wx.showModal({
      title: '提示',
      content: '确定删除这件商品吗？',
      confirmColor: '#FF0000',
      success: function(res) {
        if (res.confirm) {
          var del_car_keys = that.data.carts[parentid].shopcarts[index].key;
          if (that.data.carts[parentid].shopcarts[index].isselect == true) { //商品为选中状态
            var allnum = parseInt(that.data.allnum) - parseInt(that.data.carts[parentid].shopcarts[index].goodsnum);
            var allcount = parseFloat(that.data.allcount) - parseFloat(that.data.carts[parentid].shopcarts[index].currntprice) * that.data.carts[parentid].shopcarts[index].goodsnum;
            var count = parseFloat(that.data.carts[parentid].count) - parseFloat(that.data.carts[parentid].shopcarts[index].currntprice) * that.data.carts[parentid].shopcarts[index].goodsnum;
            that.data.carts[parentid].count = count.toFixed(2);
            that.data.carts[parentid].goodstype = that.data.carts[parentid].goodstype - 1;
            that.data.carts[parentid].goodstypeselect = that.data.carts[parentid].goodstypeselect - 1
            if (that.data.carts[parentid].goodstype == 0) {
              console.log(that.data.carts);

              console.log(parentid);
              //that.data.carts.splice(parentid, 1)
              that.data.carts[parentid].shopcarts.splice(index, 1);
            } else {
              that.data.carts[parentid].shopcarts.splice(index, 1);
            }
            var num = 0;
            for (var i = 0; i < that.data.carts.length; i++) {
              for (var j = 0; j < that.data.carts[i].shopcarts.length; j++) {
                num = num + that.data.carts[i].shopcarts[j].goodsnum;
              }
            }
            if (allnum == num)
              that.data.allselect = true;
            that.setData({
              carts: that.data.carts,
              allnum: allnum,
              allcount: allcount.toFixed(2),
              allselect: that.data.allselect
            });
          } else { //商品为选中状态
            that.data.carts[parentid].goodstype = that.data.carts[parentid].goodstype - 1;
            if (that.data.carts[parentid].goodstype == 0) {
              //  that.data.carts.splice(parentid, 1)
              that.data.carts[parentid].shopcarts.splice(index, 1);
            } else {
              that.data.carts[parentid].shopcarts.splice(index, 1);
            }
            var num = 0;
            for (var i = 0; i < that.data.carts.length; i++) {
              for (var j = 0; j < that.data.carts[i].shopcarts.length; j++) {
                num = num + that.data.carts[i].shopcarts[j].goodsnum;
              }
            }
            if (that.data.allnum == num)
              that.data.allselect = true;
            that.setData({
              carts: that.data.carts,
              allselect: that.data.allselect
            });
          }

          //that.data.carts.splice(parentid, 1);
          if (that.data.carts[parentid].shopcarts.length == 0) {
            delete that.data.carts[parentid];
            if (Object.keys(that.data.carts).length == 0) {
              that.setData({
                carts: []
              });
            }
          }
          //删除商品
          that.del_car_goods(del_car_keys);
        }
      }
    })
    this.go_record();
  },

  del_car_goods: function(carkey) {
    var token = wx.getStorageSync('token');
    var that = this;
    console.log('del_car_goods:开始');

    var community = wx.getStorageSync('community');
    var community_id = community.communityId;

    console.log('缓存中的：' + community_id);

    console.log('使用中的：' + that.data.community_id);

    app.util.request({
      'url': 'entry/wxapp/index',
      'data': {
        controller: 'car.del_car_goods',
        carkey: carkey,
        community_id: that.data.community_id,
        token: token
      },
      method: 'POST',
      dataType: 'json',
      success: function(msg) {
        if (msg.data.code == 0)(0, status.cartNum)('', true).then((res) => {
          res.code == 0 && that.setData({
            cartNum: res.data
          })
        });
      }
    })
  },

  /**
   * 提示不可购买并提示是否删除
   */
  delete: function(e) {
    var parentid = parseInt(e.currentTarget.dataset.parentid);
    var index = parseInt(e.currentTarget.dataset.index);
    var that = this;
    wx.showModal({
      title: '提示',
      content: '确认删除这件商品吗？',
      confirmColor: '#FF0000',
      success: function(res) {
        if (res.confirm) {
          let carts = that.data.carts;
          var del_car_keys = carts[parentid].shopcarts[index].key;
          carts[parentid].shopcarts.splice(index, 1);
          that.setData({
            carts: carts
          });
          if (carts[parentid].shopcarts.length == 0) {
            delete carts[parentid];
            if (Object.keys(carts).length == 0) {
              that.setData({
                carts: {}
              });
            }
          }
          //删除商品
          that.del_car_goods(del_car_keys);
        }
      }
    })
  },

  //清空失效商品函数
  clearlose: function() {
    var that = this;
    wx.showModal({
      title: '提示',
      content: '确认清空失效商品吗？',
      confirmColor: '#FF0000',
      success: function(res) {
        if (res.confirm) {
          that.setData({
            loselist: []
          });
        }
      }
    })
  },

  //记录购物车状态值，为了下次进来还是和上次一样
  go_record: function() {
    var that = this;
    var token = wx.getStorageSync('token');
    var keys_arr = [];
    var all_keys_arr = [];
    var allnum = this.data.allnum;
    var carts = this.data.carts;

    for (var i in carts) {
      for (var j in carts[i]['shopcarts']) {
        if (carts[i]['shopcarts'][j]['isselect']) {
          keys_arr.push(carts[i]['shopcarts'][j]['key']);
        }
        all_keys_arr.push(carts[i]['shopcarts'][j]['key'] + '_' + carts[i]['shopcarts'][j]['goodsnum']);
      }
    }

    app.util.request({
      'url': 'entry/wxapp/index',
      'data': {
        controller: 'car.checkout_flushall',
        token: token,
        car_key: keys_arr,
        community_id: that.data.community_id,
        all_keys_arr: all_keys_arr
      },
      method: 'POST',
      dataType: 'json',
      success: function(msg) {
        if (msg.data.code == 0) {
          // todo
          (0, status.cartNum)('', true).then((res) => {
            res.code == 0 && that.setData({
              cartNum: res.data
            })
          });
        } else {
          wx.showToast({
            title: msg.data.msg,
            icon: 'none',
            duration: 2000
          })
        }

      }
    })
    that.calcAmount();
  },

  //结算跳转页面函数
  toorder: function() {
    var token = wx.getStorageSync('token');
    var keys_arr = [];
    var all_keys_arr = [];
    var that = this;

    var allnum = this.data.allnum;
    if (allnum > 0) {
      var carts = this.data.carts;
      for (var i in carts) {
        for (var j in carts[i]['shopcarts']) {
          if (carts[i]['shopcarts'][j]['isselect']) {
            keys_arr.push(carts[i]['shopcarts'][j]['key']);
          }

          all_keys_arr.push(carts[i]['shopcarts'][j]['key'] + '_' + carts[i]['shopcarts'][j]['goodsnum']);
        }
      }

      app.util.request({
        'url': 'entry/wxapp/index',
        'data': {
          controller: 'car.checkout_flushall',
          token: token,
          community_id: that.data.community_id,
          car_key: keys_arr,
          all_keys_arr: all_keys_arr
        },
        method: 'POST',
        dataType: 'json',
        success: function(msg) {
          if (msg.data.code == 0) {
            let is_limit = msg.data.data || 0;
            wx.navigateTo({
              url: '/lionfish_comshop/pages/order/placeOrder?type=dan&is_limit=' + is_limit
            })
          } else {
            wx.showToast({
              title: msg.data.msg,
              icon: 'none',
              duration: 2000
            })
          }
        }
      })

    } else {
      wx.showModal({
        title: '提示',
        content: '请选择您要购买的商品',
        confirmColor: '#FF0000',
        success: function(res) {
          if (res.confirm) {

          }
        }
      })
    }

  },

  goindex: function() {
    wx.switchTab({
      url: '/lionfish_comshop/pages/index/index',
    })
  },

  /**
   * 计算优惠
   */
  calcAmount: function() {
    let carts = this.data.carts;
    let totalAmount = 0; //总额
    let disAmount = 0; //优惠
    let diffMoney = 0; //差多少可满减
    let cartsArr = Object.getOwnPropertyNames(carts);
    let allReducGoods = []; //所有满减商品
    let full_money = 0;
    let full_reducemoney = 0;
    cartsArr.forEach((key, i) => {
      let cart = carts[key];
      let isOpen = cart.is_open_fullreduction || 0;
      if (isOpen == 0) return false;

      let shopcarts = cart.shopcarts;
      full_money = cart.full_money * 1;
      full_reducemoney = cart.full_reducemoney * 1;

      // 1选提取所有的满减商品
      shopcarts.forEach(function(item) {
        if (item.isselect && item.can_man_jian) {
          allReducGoods.push(item);
        }
      })
    })


    // 计算满减金额
    let accordTot = 0;
    allReducGoods.forEach(function(item) {
      if (item.isselect && item.can_man_jian) {
        accordTot += item.currntprice * item.goodsnum * 1;
      }
    })

    if (accordTot >= full_money) {
      disAmount += full_reducemoney;
    } else {
      diffMoney = full_money - accordTot;
    }

    totalAmount = (this.data.allcount * 1 - disAmount).toFixed(2);
    totalAmount = totalAmount <= 0 ? 0 : totalAmount;
    let canbuy_other = totalAmount * 1 - this.data.man_orderbuy_money;
    this.setData({
      totalAmount,
      disAmount: disAmount.toFixed(2),
      diffMoney: diffMoney.toFixed(2),
      canbuy_other: canbuy_other.toFixed(2)
    })
  },

  /**
   * 大家常卖
   */
  openSku: function(t) {
    var that = this,
      e = t.detail;
    var goods_id = e.actId;
    var options = e.skuList;
    that.setData({
      addCar_goodsid: goods_id
    })
    let list = options.list || [];
    let arr = [];
    if (list.length > 0) {
      for (let i = 0; i < list.length; i++) {
        let sku = list[i]['option_value'][0];
        let temp = {
          name: sku['name'],
          id: sku['option_value_id'],
          index: i,
          idx: 0
        };
        arr.push(temp);
      }
      var id = '';
      for (let i = 0; i < arr.length; i++) {
        if (i == arr.length - 1) {
          id = id + arr[i]['id'];
        } else {
          id = id + arr[i]['id'] + "_";
        }
      }

      var cur_sku_arr = options.sku_mu_list[id];
      that.setData({
        sku: arr,
        sku_val: 1,
        cur_sku_arr: cur_sku_arr,
        skuList: e.skuList,
        visible: true,
        showSku: true
      });
    } else {
      let goodsInfo = e.allData;
      that.setData({
        sku: [],
        sku_val: 1,
        skuList: [],
        cur_sku_arr: goodsInfo
      })
      let formIds = {
        detail: {
          formId: ""
        }
      };
      formIds.detail.formId = "the formId is a mock one";
      that.gocarfrom(formIds);
    }
  },

  /**
   * 确认加入购物车
   */
  gocarfrom: function(e) {
    var that = this;
    var is_just_addcar = 1;
    wx.showLoading();
    a.collectFormIds(e.detail.formId);
    that.goOrder();
  },

  goOrder: function() {
    var that = this;
    if (that.data.can_car) {
      that.data.can_car = false;
    }
    var token = wx.getStorageSync('token');
    var community = wx.getStorageSync('community');

    var goods_id = that.data.addCar_goodsid;
    var community_id = community.communityId;
    var quantity = that.data.sku_val;
    var cur_sku_arr = that.data.cur_sku_arr;
    var sku_str = '';
    var is_just_addcar = 1;

    if (cur_sku_arr && cur_sku_arr.option_item_ids) {
      sku_str = cur_sku_arr.option_item_ids;
    }

    app.util.request({
      'url': 'entry/wxapp/user',
      'data': {
        controller: 'car.add',
        'token': token,
        "goods_id": goods_id,
        "community_id": community_id,
        "quantity": quantity,
        "sku_str": sku_str,
        "buy_type": 'dan',
        "pin_id": 0,
        "is_just_addcar": is_just_addcar
      },
      dataType: 'json',
      method: 'POST',
      success: function(res) {
        if (res.data.code == 3) {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 2000
          })
        } else if (res.data.code == 4) {
          wx.showToast({
            title: '您未登录',
            duration: 2000,
            success: () => {
              that.setData({
                needAuth: true
              })
            }
          })
        } else if (res.data.code == 6) {
          let max_quantity = res.data.max_quantity || '';
          (max_quantity > 0) && that.setData({
            sku_val: max_quantity
          })
          var msg = res.data.msg;
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000
          })
        } else {
          if (is_just_addcar == 1) {
            that.closeSku();
            that.showCartGoods();
            (0, status.cartNum)(res.data.total);
            that.setData({
              cartNum: res.data.total
            })
            wx.showToast({
              title: "已加入购物车",
              image: "../../images/addShopCart.png"
            })
          }

        }

      }
    })
  },

  selectSku: function(event) {
    var that = this;
    let str = event.currentTarget.dataset.type;
    let obj = str.split("_");
    let arr = that.data.sku;
    let temp = {
      name: obj[3],
      id: obj[2],
      index: obj[0],
      idx: obj[1]
    };
    arr.splice(obj[0], 1, temp);
    that.setData({
      sku: arr
    })
    var id = '';
    for (let i = 0; i < arr.length; i++) {
      if (i == arr.length - 1) {
        id = id + arr[i]['id'];
      } else {
        id = id + arr[i]['id'] + "_";
      }
    }
    var options = this.data.skuList;
    var cur_sku_arr = options.sku_mu_list[id];

    that.setData({
      cur_sku_arr: cur_sku_arr
    });

    console.log(id);
  },

  /**
   * 数量加减
   */
  setNum: function(event) {
    let types = event.currentTarget.dataset.type;
    var that = this;
    var num = 1;
    let sku_val = this.data.sku_val * 1;
    if (types == 'add') {
      num = sku_val + 1;
    } else if (types == 'decrease') {
      if (sku_val > 1) {
        num = sku_val - 1;
      }
    }

    let arr = that.data.sku;
    var options = this.data.skuList;

    if (arr.length > 0) {
      var id = '';
      for (let i = 0; i < arr.length; i++) {
        if (i == arr.length - 1) {
          id = id + arr[i]['id'];
        } else {
          id = id + arr[i]['id'] + "_";
        }
      }
    }

    if (options.length > 0) {
      let cur_sku_arr = options.sku_mu_list[id];
      if (num > cur_sku_arr['canBuyNum']) {
        num = num - 1;
      }
    } else {
      let cur_sku_arr = this.data.cur_sku_arr;
      if (num > cur_sku_arr['canBuyNum']) {
        num = num - 1;
      }
    }

    this.setData({
      sku_val: num
    })
  },

  skuConfirm: function() {
    this.closeSku(), (0, status.cartNum)().then((res) => {
      res.code == 0 && that.setData({
        cartNum: res.data
      })
    });
  },

  /**
   * 关闭购物车选项卡
   */
  closeSku: function() {
    this.setData({
      visible: 0,
      stopClick: false,
    });
  },
})