// packageC/o2o/o2oStore_v2/o2oStore_v2.js
var specsManage = []; //选择池 用于排序
var optionsId = ""; //选择后的 规格ID
var optionsMaxCount = 1;
var clicktag = 0;
var scrollY = 0;
var listHeight = [];
var listCategoryHeight = [];
var lastcurrentCategoryheight = "";
var lastcurrentIndexheight = "";
var windowHeight = 600;
try {
  const res = wx.getSystemInfoSync();
  windowHeight = res.windowHeight;
} catch (e) {
  // Do something when catch error
}
var app = getApp();
// const aloneUrl = 'plugin.store-alone-temp.frontend.microCommunities.index.get-micro-communities';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showLength: 0,

    language: '',
    store_id: '',
    order_id: '', //  订单id参数(从订单页面过来的时候带
    goodsCarts: {}, //购物车转为goods key的数组
    showStoreInfo: false,
    new_comment: {},
    store: {
      comment: {
        average_score: 0,
        comment_total: 0,
        new_comment: null
      },
      goods_total: 0,
      order_count: 0,
      business_hours: "9:00-22:00",
      store_address: "",
      store_mobile: "",
      operating_state: 0
    },
    show1: false,
    carts: [], //购物车商品
    cartsNum: 0,
    cartsTotal: 0.0,
    popNum: '',
    title: '',
    path: '',
    activeName: [], //分类折叠面板
    secondaryId: "", //二级分类id
    category_id: '', //一级分类id
    isBottom: false, //控制到底下一级分类加载
    category_loading: false, //控制下一级分类加载
    category_last_loading: false, //控制上一级分类加载
    category: [],
    secondCategory: [],
    goodsList: [],
    currentCategory: "",
    goodsCount: 0, //当前商品数量
    pageCount: 1,
    specid: "", //规格ID
    catesId: "",
    loading: false,
    allLoaded: true,
    showGoods: true,
    goodsInfo: {},
    showCart: false,
    popTitle: "",
    popThumb: "",
    popStock: "",
    popCard: {},
    popPrice: "",
    popmPrice: "",
    goodsDescription: "",
    // 滚动需要的数据
    secondTitle: [],
    goods: [],
    Index: 0,
    showDis: true,
    scrollTop: 0,
    goodsCartsOld: "",
    tabIndex: 0,
    tab: ["商品", "评价", "商家"],
    info: '',
    toolbar: false,
    cartchecked: true,
    goodsBoxheight: "564rpx",
    storeInfoboxtop: 0,
    minicartStyle: '',
    leftPrice: '',
    buttondisab: true,
    //more
    isLoadMore: true,
    page: 1,
    total_page: 0,

    amout: false,
    //
    get_coupon: [],
    micro_communities: [],
    get_recommend_goods: [],
    store_member: [],
    store_room: [],
    
    //门店配送 start +++++++++++++++++++++++
    delivery_note: "", //门店配送说明
    delivery_area: [
      [116.403322, 39.920255]
    ], // 配送范围经纬度
    locations: [116.403322, 39.920255], //门店经纬度
    delivery_status: 0, //是否开启门店配送
    markers_2: [{ // 获取返回结果，放到mks数组中
      latitude: 23.099994,
      longitude: 113.324520,
      iconPath: "https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png", //图标路径
      width: 20,
      height: 25,
      callout: {
        padding: '10rpx',
        borderRadius: '5rpx'
      }
    }],
    polygons_2: [{
      points: [],
      fillColor: "#FF88887F",
      strokeColor: "#FFF",
      strokeWidth: 2,
      zIndex: 1
    }],
    delivery: {
      longitude: "113.324520",
      latitude: "23.099994"
    },
    // end ---------------------------
    isAeadyLoad: false,

    // 满额减、满额包邮
    get_store_full_package: '',
    get_store_full_reduction: [],

    //good more
    goodPage: 1, //当前页数
    goodIsLoadMore: true, //判断是否要加载更多的标志
    goodTotal_page: 0, //总页数
    flxShow: false, // 控制是否固定顶部
    delivery_amount: 0, //门店起送金额
    // 门店独立余额
    storeAlone: false,

    tabIndex2: '店铺详情',
    tabList: [],
    menuList: [], //标签的数组集合
    tabName: "门店详情",
    isLoading: false, //是否处于请求状态
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.initData();
    if (app.globalData.store_alone_temp == 1) {
      this.setData({
        storeAlone: true
      });
    }
    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] == 'store_id') {
            this.setData({
              store_id: chil_arr[1]
            });
          }
          if (chil_arr[0] == 'mid') {
            app._setMid(chil_arr[1]);
          }
        }
      }
    }
    if (options.store_id) {
      this.setData({
        store_id: options.store_id
      });
    }
    if (options.fromOrder == 1) {
      this.setData({
        store_id: '',
        order_id: options.store_id
      });
    }
    if (options.mid) {
      app._setMid(options.mid);
    }
    if (options.activeType === "comment") {
      this.setData({
        tabIndex: 1
      });
    }
    this.getStoresDetails();
    this.data.isAeadyLoad = true;
  },
  readImg(e) {
    console.log(e);
    let url = e.currentTarget.dataset.url;
    wx.previewImage({
      current: url, // 当前显示图片的http链接
      urls: [url] // 需要预览的图片http链接列表
    });
  },
  gotoGoodDetail(e) {
    console.log(e);
    let id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/packageA/detail_v2/detail_v2?id=' + id
    });
  },
  copybtn(e) {
    let wechatCode = e.currentTarget.dataset.wechat;
    wx.setClipboardData({
      data: wechatCode ? wechatCode : '',
      success(res) {
        wx.showToast({
          icon: 'none',
          title: '复制成功',
          duration: 1000
        });
      }
    });
  },
  chooseTab(e) {
    let item = e.currentTarget.dataset.item;
    this.setData({
      tabIndex2: Number(e.currentTarget.dataset.index),
      tabName: item.name
    });
    if(item.name == '门店签到'){
      wx.navigateTo({
        url: '/packageF/storeSign/storeSign/storeSign?id='+this.data.store_id,
      })
      return
    }
    this.getTabsData(); //请求标签数据
  },
  getTabsData() {
    if (!this.data.menuList[this.data.tabIndex2].url) {
      // getStoreInfo()方法返回并处理menuList数组
      // 如该标签数据需要请求api获取，让后端返回请求接口的api;
      console.log("menu_list该标签没有返回请求api");
      return;
    }
    if (this.data.menuList[this.data.tabIndex2].list.length > 0) {
      this.data.isLoadMore = this.data.menuList[this.data.tabIndex2].isLoadMore;
      return;
    }
    let _totalPage = 1;
    let _list = [];
    this.data.isLoading = true;
    let urlStr = app.getNetAddresss(this.data.menuList[this.data.tabIndex2].url);
    app._postNetWork({
      url: urlStr,
      data: {
        page: 1,
        store_id: this.data.store_id
      },
      success: (resdata) => {
        let res = resdata.data;
        if (res.result == 1) {
          if (this.data.tabName == "门店微贴") {
            _totalPage = res.data.last_page;
            _list = this.setCommunities(res.data.data);
          } else if (this.data.tabName == "门店员工") {
            _list = res.data;
          } else if (res.data?.data) {
            _totalPage = res.data.last_page;
            _list = res.data.data;
          } else {
            console.log("getTabsData()::error", res.data);
          }
          this.data.isLoadMore = true;
          this.data.menuList[this.data.tabIndex2].isLoadMore = true;
          this.data.menuList[this.data.tabIndex2].total_page = _totalPage;
          if (!this.data.menuList[this.data.tabIndex2].total_page) {
            this.data.menuList[this.data.tabIndex2].total_page = 0;
          }
          this.setData({
            ['menuList[' + this.data.tabIndex2 + '].list']: _list
          });
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1000,
          });
        }
      },
      fail: (res) => {
        console.log(res);
      },
    });
  },

  setCommunities(_data) {
    let arr = [];
    _data.map(item => {
      arr.push({
        id: item.id,
        title: item.title,
        praise_num: item.praise_num,
        has_one_stick_user: {
          avatar: item.user_avatar,
          nickname: item.user_nickname,
        },
        has_many_image: [{
          url: item.image,
          stick_id: item.id
        }]
      });
    });
    return arr;
  },

  toCard(e) {
    let id = e.currentTarget.dataset.cardid;
    if (id) {
      wx.navigateTo({
        url: '/packageB/member/business_card/BusinessCard/BusinessCard?card_id=' + id +
          '&mark=card'
      });
    }
  },
  gomenphone(e) {
    let mobile = e.currentTarget.dataset.phone;
    wx.makePhoneCall({
      phoneNumber: mobile
    });
  },
  toGood(e) {
    let id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/packageA/detail_v2/detail_v2?id=' + id
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let language = wx.getStorageSync('langIndex');
    this.setData({
      'language': language.en
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (!this.data.isAeadyLoad) {
      this.getStoresDetails('cart');
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.data.isAeadyLoad = false;
  },

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

  },

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

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.isLoadMore) {
      this._getMoreData();
    } else {
      console.log('没有更多数据');
    }
  },
  _getMoreData() {
    let that = this;
    this.data.menuList[this.data.tabIndex2].isLoadMore = false;
    this.data.isLoadMore = false; // 防止多次请求分页数据

    if (this.data.menuList[this.data.tabIndex2].page >= this.data.menuList[this.data.tabIndex2].total_page) {
      return;
    } else {
      let _list = [];
      let _json = { store_id: this.data.store_id };
      this.data.menuList[this.data.tabIndex2].page = this.data.menuList[this.data.tabIndex2].page + 1;
      _json.page = this.data.menuList[this.data.tabIndex2].page;
      let urlStr = app.getNetAddresss(this.data.menuList[this.data.tabIndex2].url);
      app._postNetWork({
        url: urlStr,
        showToastIn: false,
        data: _json,
        success: (resdata)=> {
          var res = resdata.data;
          if (res.result == 1) {
            that.data.isLoadMore = true;

            if (this.tabName == "门店微贴") {
              _list = this.setCommunities(res.data);
            } else if (this.tabName == "门店员工") {
              _list = res;
            } else if (res&&res.data) {
              _list = res.data;
            } else {
              console.log("getTabsData()::error", res);
            }
            this.setData({
              ['menuList[' + this.data.tabIndex2 + '].list']: this.data.menuList[this.data.tabIndex2].list.concat(_list)
            });
          } else {
            this.data.menuList[this.data.tabIndex2].page = this.data.menuList[this.data.tabIndex2].page - 1;
            this.data.menuList[this.data.tabIndex2].isLoadMore = false;
            this.data.isLoadMore = false;
            return;
          }
        },
        fail: function (res) {
          console.log(res.msg);
        }
      });
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareTimeline: function () {
    let that = this;
    let kuid = wx.getStorageSync('yz_uid');
    let _title = app._isTextEmpty(that.data.store.store_name) ? "" : that.data.store.store_name;
    let _link = '/packageC/o2o/o2oStore/o2oStore?fromHome=1&mid=' + kuid + '&store_id=' + this.data.store_id;
    return {
      title: _title,
      path: _link
    };
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    let that = this;
    let kuid = wx.getStorageSync('yz_uid');
    let _title = app._isTextEmpty(that.data.store.store_name) ? '' : that.data.store.store_name;
    let _link = '/packageC/o2o/o2oStore/o2oStore?fromHome=1&mid=' + kuid + '&store_id=' + this.data.store_id;
    return {
      title: _title,
      path: _link
    };
  },
  trggleCart() {
    if (this.data.carts.length === 0) {
      return;
    }
    this.setData({
      showCart: !this.data.showCart
    });
    this.getminicartStyle();
  },
  show1Closebtn() {
    this.setData({
      show1: false
    });
  },
  initData() {
    this.setData({
      tabIndex: 0,
      category: [],
      goodsList: [],
      currentCategory: '',
      goodsCount: 0,
      pageCount: 1,
      cartsNum: 0,
      cartsTotal: 0.0,
      carts: [],
      goodsCarts: {},
      specid: ""
    });
    specsManage = []; //选择池 用于排序
    optionsId = ""; //选择后的 规格ID
    optionsMaxCount = 1;
    clicktag = 0;
    scrollY = 0;
    listHeight = [];
    listCategoryHeight = [];
    lastcurrentCategoryheight = "";
    lastcurrentIndexheight = "";
  },
  getStoresDetails(flag) {
    let that = this;
    let urlStr = app.getNetAddresss("plugin.store-cashier.frontend.store.get-store-info.get-stores-details");
    app._postNetWork({
      url: urlStr,
      data: {
        store_id: that.data.store_id,
        order_id: that.data.order_id,
      },
      success: (resdata)=> {
        var res = resdata.data;
        if (res.msg === "该商家已过期,去看看其他的吧") {
          that.setData({
            showDis: false,
            show8: true
          });
          return;
        }
        if (res.result == 1) {
          res.data.store_information = res.data.store_information.replace(/<img/gi, '<img style="max-width:100%;height:auto;display:block"');
          that.setData({
            store: res.data.store_info,
            store_id: res.data.store_info.store_id,
            new_comment: res.data.comment ? (res.data.comment.new_comment ? res.data.comment.new_comment : {}) : {},
            info: res.data.store_information ? res.data.store_information : '',
            infoShow: res.data.store_information ? true : false,
            get_store_full_package: res.data.get_store_full_package,
            get_store_full_reduction: res.data.get_store_full_reduction,
          });
          console.log(that.data.get_store_full_reduction);
          // 门店配送 start ++++++++++++++++++++++++++++
          if (that.data.store.store_delivery && that.data.store.store_delivery.delivery_status == 1) {
            that.setData({
              delivery_status: 1,
              delivery_note: that.data.store.store_delivery ? that.data.store.store_delivery.delivery_note : '',
              delivery_amount: that.data.store.store_delivery ? that.data.store.store_delivery.delivery_amount : 0,
            });
            let delivery_area = that.data.store.store_delivery && that.data.store.store_delivery.delivery_area ? that.data.store.store_delivery.delivery_area : [];
            let locations = that.data.store.store_delivery ? that.data.store.store_delivery.locations : [];
            let arr_delivery_area = [];
            delivery_area.forEach((item, index) => {
              arr_delivery_area.push([Number(item.R), Number(item.Q)]);
            });
            that.setData({
              delivery_area: arr_delivery_area,
              locations: [Number(locations.longitude).toFixed(6), Number(locations.latitude).toFixed(6)]
            });
            if (that.data.locations && that.data.locations.length > 0) {
              that.setData({
                "markers_2[0].longitude": that.data.locations[0],
                "markers_2[0].latitude": that.data.locations[1],
                "delivery.longitude": that.data.locations[0],
                "delivery.latitude": that.data.locations[1],
              });
            }
            if (that.data.delivery_area && that.data.delivery_area.length > 0) {
              let points = [];
              for (let i = 0; i < that.data.delivery_area.length; i++) {
                points.push({
                  longitude: that.data.delivery_area[i][0],
                  latitude: that.data.delivery_area[i][1]
                });
              }
              that.setData({
                "polygons_2[0].points": points,
              });
            }
          }
          // end ----------------------------
          if (that.data.store.operating_state === 1) {
            that.setData({
              show1: true
            });
          }
          that.setData({
            get_coupon: res.data.get_coupon,
            get_recommend_goods: res.data.get_recommend_goods
          });


          let tabList = [
            { name: "店铺详情", api: "" },
            { name: "门店员工", api: "plugin.store-cashier.frontend.store.get-store-info.get-store-staff" }
          ];
          if (res.data.is_micro_communities == 1) {
            tabList.push({ name: "门店微贴", api: "plugin.store-cashier.frontend.store.get-store-info.get-micro-communities" });
          }
          if (res.data.is_room == 1) {
            tabList.push({ name: "门店直播", api: "plugin.store-cashier.frontend.store.get-store-info.get-room" });
          }
          if (res.data.is_fight_groups == 1) {
            tabList.push({ name: "门店拼团", api: "plugin.fight-groups.frontend.store.frontend-fight-groups.index" });
          }
          if (res.data.is_store_deposit_ladder == 1) {
            tabList.push({ name: "定金阶梯团", api: "plugin.deposit-ladder.frontend.store.index.activities" });
          }
          if(res.data.enabled_store_attendance == 1){
            tabList.push({ name: "门店签到", api: "plugin.store-attendance.frontend.dashboard.index" });
          }
          let menuList = [];
          // 处理并重新组装新数组和请求api
          tabList.forEach((val, index) => {
            menuList.push({
              isLoadMore: true,
              page: 1,
              total_page: 0,
              list: [],
              url: val.api
            });
          });
          this.setData({
            menuList:menuList,
            tabList:tabList,
            tabName:'店铺详情',
            tabIndex2:0,
          });

          if (flag === 'cart') {
            that.getFirstCart(res.data.member_cart);
          } else {
            that.getAllCategory(res.data.first_category);
            that.getFirstCart(res.data.member_cart);
          }
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  onChange(e) {
    this.setData({
      activeName: e.detail
    });
  },
  upper(e) {
    this.setData({
      amout: false,
      flxShow: false
    });
  },
  binddragend() {
    if (this.data.isBottom && this.data.goodPage >= this.data.goodTotal_page && !this.data.category_loading) {
      let category_id = "";
      for (let i = 0; i < this.data.category.length; i++) {
        if (this.data.category_id == this.data.category[i].id && this.data.category[i + 1]) {
          category_id = this.data.category[i + 1].id;
          break;
        }
      }
      if (category_id) {
        this.setData({
          category_id: category_id,
        });
        this.getSecondCategory('load', {
          id: this.data.category_id
        });
      }
    }
  },
  bindscrolltolower() {
    if (this.data.goodIsLoadMore) {
      this.getMoreGood();
    }
    if (this.data.goodPage >= this.data.goodTotal_page && !this.data.category_loading) {
      this.data.isBottom = true;
    }
  },
  bindrefresherpulling() {
    this.data.isBottom = false;
  },
  bindrefresherrefresh() {
    this.setData({
      category_last_loading: true
    });
    if (this.data.category_last_loading && !this.data.category_loading) {
      let category_id = "";
      for (let i = 0; i < this.data.category.length; i++) {
        if (this.data.category_id == this.data.category[i].id && this.data.category[i - 1]) {
          category_id = this.data.category[i - 1].id;
          break;
        }
      }
      if (category_id) {
        console.log("加载上一个一级分类");
        this.setData({
          category_id: category_id,
        });
        this.getSecondCategory('load', {
          id: this.data.category_id
        });
      } else {
        this.setData({
          category_last_loading: false
        });
      }
    }

  },
  foodsScrollbtn(e) {
    let ytop = e.detail.scrollTop;
    scrollY = Math.abs(Math.round(ytop));
    // this.scrollMargin(scrollY)
    // this.currentCategoryIndexBtn()
    // this.currentIndexBtn()

    this.data.scrollTop = e.detail.scrollTop;
    if (windowHeight <= 670) {
      if (e.detail.scrollTop > 10) {
        if (!this.data.flxShow) {
          this.setData({
            amout: true,
            flxShow: true
          });
        }
      } else {
        if (this.data.flxShow) {
          this.setData({
            amout: false,
            flxShow: false
          });
        }
      }
    }
    setTimeout(() => {
      if(this.data.isBottom){
        this.binddragend();
      }
    }, 1000);
  },
  getAllCategory(data) {
    let that = this;
    data.second_category.unshift({
      name: '全部',
      id: '',
    });

    that.setData({
      category: data.first_category || [],
      secondCategory: data.second_category,
      secondaryId: "",
      goods: data.goods.data || [],
      goodTotal_page: data.goods.last_page
    });
    this.setData({
      showLength: Number(5 - this.data.goods.length) > 0 ? Number(5 - this.data.goods.length) : 1,
    });

    if (this.data.category && this.data.category.length > 0) {
      that.setData({
        category_id: this.data.category[0].id
      });
    }
    const query = wx.createSelectorQuery();
    query.select('#storeInfo_box').boundingClientRect();
    query.exec(function (res) {
      that.setData({
        Height: res[0].height + res[0].top - 60
      });
    });
    //判断加的数据相等和长度
    this.getgoodsboxheight();
  },
  getSecondCategory(e, category_id) {
    let item = {};
    if (e == 'load') {
      item = category_id;
    } else {
      item = e.target.dataset.item || e.currentTarget.dataset.item;
    }
    this.setData({
      category_id: item.id,
      goods: [],
      amout: false,
      flxShow: false,
      category_loading: true,
      scrollTop: '0',
    });
    this.data.isBottom = false;
    let that = this;
    let urlStr = app.getNetAddresss('plugin.store-cashier.frontend.store.get-store-info.get-second-category');
    urlStr += '&store_id=' + this.data.store_id;
    urlStr += '&category_id=' + this.data.category_id;
    app._getNetWork({
      url: urlStr,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          res.data.second_category.unshift({
            name: '全部',
            id: '',
          });

          that.setData({
            category_last_loading: false,
            secondCategory: res.data.second_category,
            secondaryId: "",
            goods: res.data.goods.data,
            goodPage: 1,
            goodIsLoadMore: true,
            goodTotal_page: res.data.goods.last_page,
          });
          this.setData({
            showLength: Number(5 - this.data.goods.length) > 0 ? Number(5 - this.data.goods.length) : 1,
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 1500
          });
        }
        setTimeout(() => {
          this.setData({
            category_last_loading: false,
            category_loading: false,
          });
        }, 1500);
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  getSecondGoods(e) {
    let item = e.target.dataset.item || e.currentTarget.dataset.item;
    this.setData({
      secondaryId: item.id,
      activeName: []
    });
    let that = this;
    let urlStr = app.getNetAddresss('plugin.store-cashier.frontend.store.get-store-info.get-goods');
    urlStr += '&store_id=' + this.data.store_id;
    urlStr += '&category_id=' + this.data.category_id;
    urlStr += '&second_category_id=' + this.data.secondaryId;
    app._getNetWork({
      url: urlStr,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            goods: res.data.goods.data,
            goodPage: 1,
            goodIsLoadMore: true,
            goodTotal_page: res.data.goods.last_page,
          });
          this.setData({
            showLength: Number(5 - this.data.goods.length) > 0 ? Number(5 - this.data.goods.length) : 1,
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  getMoreGood() {
    let that = this;

    this.setData({
      goodIsLoadMore: false,
      category_loading: true
    });
    if (this.data.goodPage >= this.data.goodTotal_page) {
      console.log("没有更多了");
      this.setData({
        category_loading: false,
      });
    } else {
      console.log("加载更多");
      this.setData({
        goodPage: this.data.goodPage + 1
      });

      let urlStr = app.getNetAddresss('plugin.store-cashier.frontend.store.get-store-info.get-goods');
      urlStr += '&store_id=' + this.data.store_id;
      urlStr += '&category_id=' + this.data.category_id;
      urlStr += '&second_category_id=' + this.data.secondaryId || 0;
      urlStr += '&page=' + this.data.goodPage;
      app._getNetWork({
        url: urlStr,
        success: (resdata) => {
          var res = resdata.data;
          if (res.result == 1) {
            that.setData({
              goodIsLoadMore: true,
              goods: this.data.goods.concat(res.data.goods.data),
            });

            if (this.data.goodPage >= this.data.goodTotal_page) {
              that.setData({
                goodIsLoadMore: false,
              });
            }
          } else {
            that.setData({
              goodIsLoadMore: false,
              goodPage: this.goodPage - 1,
            });
            wx.showToast({
              title: res.msg,
              icon: 'none',
              duration: 1500
            });
          }
          that.setData({
            category_loading: false,
          });
        },
        fail: function (res) {
          console.log(res);
        }
      });
    }

  },
  //直播间跳转
  gopage(e) {
    let status = e.currentTarget.dataset.status;
    let id = e.currentTarget.dataset.id;
    let backid = e.currentTarget.dataset.backid;
    if (status == 1) {
      wx.navigateTo({
        url: '/packageD/directSeeding/livePage/livePage?id=' + id + '&playerType=live'
      });
    } else if (status == 2) {
      wx.navigateTo({
        url: '/packageD/directSeeding/livePage/livePage?id=' + id + '&playerType=video' + '&backid=' + backid
      });
    } else if (status == 3) {
      wx.navigateTo({
        url: '/packageD/directSeeding/foreshow/foreshow?id=' + id
      });
    }
  },

  getCategory(data) {
    let that = this;
    this.setData({
      category: data.list || []
    });
    if (this.data.category.length > 0) {
      for (let i = 0; i < this.data.category.length; i++) {
        if (this.data.category[i].childrens.length > 0) {
          this.setData({
            ['category[' + i + '].active']: true
          });
          if (this.data.category[i].childrens.length > 0) {
            this.setData({
              ['category[' + i + '].childrens[0].active']: true,
              'currentCategory': this.data.category[i].childrens[0].name,
              'catesId': this.data.category[i].childrens[0].id
            });
            // 全部二级商品数据
            let firstClass = [];
            let secondTitle = [];
            this.data.category.forEach((first, index) => {
              console.log(first);
              if (first.childrens.length > 0) {
                // console.log(first.childrens)
                // return
                if (first.childrens.length == 1) {
                  firstClass.push(first.childrens);
                } else if (first.childrens && first.childrens[i].goods.length >= 0) {
                  firstClass.push(first.childrens);
                }
              } else {
                firstClass.push([]);
              }
            });
            firstClass.forEach(second => {
              if (second.length > 0) {
                second.forEach(title => {
                  secondTitle.push({
                    id: title.id,
                    name: title.name
                  });
                });
              }
            });

            this.setData({
              secondTitle: secondTitle,
              goods: firstClass,
            });
            this.setData({
              showLength: Number(5 - this.data.goods.length) > 0 ? Number(5 - this.data.goods.length) : 1,
            });
            const query = wx.createSelectorQuery();
            query.select('#storeInfo_box').boundingClientRect();
            query.exec(function (res) {
              that.setData({
                Height: res[0].height + res[0].top - 60
              });
            });
            //判断加加的数据相等和长度
            this.getgoodsboxheight();
            this._calculateCategoryHeight();
            this._calculateHeight();
            this.currentCategoryIndexBtn();
            this.currentIndexBtn();
            this.setData({
              currentCategoryIndex: i
            });
          }
          break;
        }
      }

    }
  },
  getgoodsboxheight() {
    let that = this;
    const query = wx.createSelectorQuery();
    query.select('#nav').boundingClientRect();
    const query_1 = wx.createSelectorQuery();
    query_1.select('#settlecomplete').boundingClientRect();
    const query_3 = wx.createSelectorQuery();
    query_3.select('#search_top').boundingClientRect();

    // 判断windowHeight <= 670 从而固定storeInfo_box
    query.exec(function (res) {
      query_1.exec(function (res_1) {
        query_3.exec(function (res_2) {
          that.setData({
            goodsBoxheight: windowHeight <= 670 ? windowHeight - res_1[0].height - res_2[0].height - (res[0].top + res[0].height) + that.data.Height + 'px' : windowHeight - res_1[0].height - res_2[0].height - that.data.Height + 'px'
          });
        });
      });
    });
  },
  // 监听可视化高度变化
  _calculateCategoryHeight() {
    let height = 0;
    listCategoryHeight.push(height);
    const query = wx.createSelectorQuery();
    query.selectAll('#foodsWrapper .food-list').boundingClientRect();
    query.exec(function (res) {
      let foodList = res[0];
      for (let i = 0; i < foodList.length; i++) {
        let item = foodList[i];
        height += item.height;
        listCategoryHeight.push(height);
      }
    });
  },
  // 监听可视化高度变化
  _calculateHeight() {
    let height = 0;
    listHeight.push(height);
    const query_1 = wx.createSelectorQuery();
    query_1.selectAll('#foodsWrapper .food-list-hook').boundingClientRect();
    query_1.exec(function (res) {
      let foodList = res[0];
      for (let i = 0; i < foodList.length; i++) {
        let item = foodList[i];
        height += item.height;
        listHeight.push(height);
      }
    });
  },
  // 计算li索引的高度变化
  currentCategoryIndexBtn() {
    for (let i = 0; i < listCategoryHeight.length; i++) {
      let height1 = listCategoryHeight[i];
      let height2 = listCategoryHeight[i + 1];
      if ((height2 == undefined) || (scrollY >= height1 && scrollY < height2)) {
        if (!(lastcurrentCategoryheight === height1)) {
          this.setData({
            currentCategoryIndex: i
          });
        }
        lastcurrentCategoryheight = height1;
        return false;
      }
    }
    this.setData({
      currentCategoryIndex: 0
    });
  },
  // 计算li索引的高度变化
  currentIndexBtn() {
    for (let i = 0; i < listHeight.length; i++) {
      let height1 = listHeight[i];
      let height2 = listHeight[i + 1];
      if (!height2 || (scrollY >= height1 && scrollY < height2)) {
        if (!(lastcurrentIndexheight === height1)) {
          this.setData({
            currentIndex: this.data.secondTitle[i].id
          });
        }
        lastcurrentIndexheight = height1;
        return false;
      }
    }
    this.setData({
      currentIndex: 0
    });
  },
  getFirstCart(data) {
    this.setData({
      carts: data,
      goodsCarts: data,
      cartsNum: 0,
      cartsTotal: 0
    });
    this.data.carts.forEach(item => {
      // this.setData({
      // 	['goodsCarts[' + item.goods_id + ']']: item
      // })
      if (
        item.goods_id === this.data.goodsInfo.id &&
        item.option_id === optionsId
      ) {
        this.setData({
          popNum: item.total,
          popCard: item
        });
      }
      this.setData({
        cartsNum: this.data.cartsNum + item.total,
        cartsTotal: this.data.cartsTotal + (item.total * item.goods.price)
      });
    });
    this.setData({
      goodsCartsTotal: this.calculateTotal(this.data.carts),
      cartsTotal: parseFloat(this.data.cartsTotal).toFixed(2)
    });
  },
  //搜索跳转
  searchJump() {
    wx.navigateTo({
      url: '/packageC/o2o/StoreSearch/StoreSearch?store_id=' + this.data.store_id + '&fromHome=1'
    });
  },
  //跳转门店优惠券
  gotoCupcon() {
    wx.navigateTo({
      url: '/packageC/o2o/store_coupon/store_coupon?id=' + this.data.store_id
    });
  },
  changeTab(e) {
    let index = e.currentTarget.dataset.index;
    this.setData({
      tabIndex: index,
      // storeInfoboxtop: 0
    });
    this.setData({
      amout: false,
      flxShow: false
    });
  },
  goBuy() {
    wx.navigateTo({
      url: '/packageC/cashier/cashier_pay/cashier_pay?store_id=' + this.data.store_id
    });
  },
  selectCategoryMenu(e) {
    let item = e.currentTarget.dataset.items;
    if (item.childrens[0]) {
      this.selectMenu(item.childrens[0].id);
      console.log('kkk', item);
    } else {
      wx.showToast({
        icon: 'none',
        title: "该分类暂无商品",
        duration: 1500
      });
    }
  },
  // 点击的时候对应变化
  selectMenuBtn(e) {
    let id = e.currentTarget.dataset.id;
    this.selectMenu(id);
  },
  //跳转门店商品的详情
  goToGoodsO2O(e) {
    let goods = e.currentTarget.dataset.food;
    if (this.data.store.operating_state !== 1) {
      wx.navigateTo({
        url: '/packageA/detail_v2/detail_v2?id=' + goods.goods_id + '&tag=o2o' + '&store_id=' + this.data.store_id
      });
    }
  },
  //添加有规格商品到购物车
  addGood(e) {
    let good = e.currentTarget.dataset.item;

    //价格权限
    if (good.vip_level_status && good.vip_level_status.status == 1) {
      wx.showToast({
        title: good.vip_level_status.tips,
        icon: 'none',
        duration: 2000
      });
      return false;
    }

    this.setData({
      show2: true,
      goodsInfo: good
    });
    this.initPopView(); //初始化弹窗view
  },
  numberLeft(e) {
    if (!this.data.buttondisab) {
      return;
    }
    wx.showLoading({
      title: '添加商品中'
    });
    this.setData({
      buttondisab: false
    });
    let foodData = e.currentTarget.dataset.food;
    let goodsT = e.currentTarget.dataset.goods;
    console.log('bb1:::', foodData);
    console.log('bb2:::', goodsT);
    if (app._isTextEmpty(goodsT)) {
      this.updateCart(goodsT.id, -1);
    } else {
      this.setData({
        goodsCartsOld: goodsT.total,
        ['goodsCarts[' + foodData.id + '].total']: Number(this.data.goodsCarts[foodData.id].total) - 1
      });
      clicktag = 0;
      this.updateCart(this.data.goodsCarts[foodData.id].id, -1);
      // this.changeCount(foodData.id, '');
    }
  },
  //商品列表 减(弹窗)
  numberLeft1(e) {
    if (!this.data.buttondisab) {
      return;
    }
    wx.showLoading({
      title: '添加商品中'
    });
    this.setData({
      buttondisab: false
    });
    let goodsT = e.currentTarget.dataset.item;
    let index = e.currentTarget.dataset.index;
    if (app._isTextEmpty(goodsT)) {
      this.updateCart(goodsT.id, -1);
    } else {
      this.setData({
        goodsCartsOld: goodsT.total,
        ['carts[' + index + '].total']: Number(goodsT.total) - 1
      });
      clicktag = 0;
      this.updateCart(this.data.carts[index].id, -1);
      // this.changeCount(index, "carts");
    }
  },
  //商品列表 加
  numberRight(e) {
    if (!this.data.buttondisab) {
      return;
    }
    wx.showLoading({
      title: '添加商品中'
    });
    this.setData({
      buttondisab: false
    });
    let foodData = e.currentTarget.dataset.food;
    let goodsT = e.currentTarget.dataset.goods;
    //价格权限
    if (foodData.vip_level_status && foodData.vip_level_status.status == 1) {
      wx.showToast({
        title: foodData.vip_level_status.tips,
        icon: 'none',
        duration: 2000
      });
      return false;
    }
    console.log('cc1:::', foodData);
    console.log('cc2:::', goodsT);
    let goodindex = e.currentTarget.dataset.goodindex;
    let index = e.currentTarget.dataset.index;
    let foodindex = e.currentTarget.dataset.foodindex;
    if (app._isTextEmpty(goodsT)) {
      this.addCart(foodData, '', goodindex, index, foodindex);
    } else {
      this.setData({
        goodsCartsOld: goodsT.total,
        ['goodsCarts[' + foodData.id + '].total']: Number(this.data.goodsCarts[foodData.id].total) + 1
      });
      this.addCart(foodData, '', goodindex, index, foodindex);
    }
  },
  //商品列表 加(弹窗)
  numberRight1(e) {
    if (!this.data.buttondisab) {
      return;
    }
    this.setData({
      buttondisab: false
    });
    wx.showLoading({
      title: '添加商品中'
    });
    let goodsT = e.currentTarget.dataset.item;
    let index = e.currentTarget.dataset.index;
    if (app._isTextEmpty(goodsT)) {
      this.addCart(goodsT, "cart");
    } else {
      this.setData({
        goodsCartsOld: goodsT.total,
        ['carts[' + index + '].total']: Number(goodsT.total) + 1
      });
      this.addCart(goodsT, "cart");
    }
  },
  changeCount_2(e) {
    let that = this;
    let val = e.detail.value;
    let index = e.currentTarget.dataset.index;
    that.setData({
      ['carts[' + index + '].total']: val
    });
    let goodsCartsData = that.data.carts[index];
    if (goodsCartsData.total < 0) {
      wx.showToast({
        icon: 'none',
        title: "商品数量不能为负数",
        duration: 1500
      });
      that.setData({
        ['carts[' + index + '].total']: that.data.goodsCartsOld
      });
      return;
    }
    if (goodsCartsData.total < that.data.goodsCartsOld) {
      let lowerNum = that.data.goodsCartsOld - goodsCartsData.total;
      that.updateCart(goodsCartsData.id, -lowerNum);
    } else if (goodsCartsData.total > that.data.goodsCartsOld) {
      let addNum = goodsCartsData.total - that.data.goodsCartsOld;
      that.updateCart(goodsCartsData.id, addNum);
    }
  },
  updateCartBtn(e) {
    let id = e.currentTarget.dataset.id;
    let num = e.currentTarget.dataset.num;
    this.updateCart(id, num);
  },
  updateCart(id, num) {
    if (num < 0) {
      var total = 0;
      this.data.carts.forEach(item => {
        console.log(item);
        if (item.id == id) {
          total = item.total;
        }
      });

      if (total + num < 0) {
        if (clicktag === 0) {
          clicktag = 1;
          this.delItemByCart(id);
          setTimeout(function () {
            clicktag = 0;
          }, 500);
        }
        return;
      }
      if (clicktag === 0) {
        clicktag = 1;
        this.updateCartRequest(id, num);
        setTimeout(function () {
          clicktag = 0;
        }, 500);
      }
    } else {
      if (clicktag === 0) {
        clicktag = 1;
        this.updateCartRequest(id, num);
        setTimeout(function () {
          clicktag = 0;
        }, 500);
      }
    }
  },
  delItemByCart(cart_id) {
    let that = this;
    let urlStr = app.getNetAddresss('plugin.store-cashier.frontend.shoppingCart.member-cart.destroy');
    urlStr += '&store_id=' + this.data.store_id;
    urlStr += '&ids=' + cart_id;
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.getCart();
          that.setData({
            popNum: that.data.popNum - 1,
            showCart: false
          });
          that.getminicartStyle();
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  updateCartRequest(id, num) {
    let that = this;
    let urlStr = app.getNetAddresss('plugin.store-cashier.frontend.shoppingCart.member-cart.updateNum');
    urlStr += '&id=' + id;
    urlStr += '&num=' + num;
    urlStr += '&store_id=' + this.data.store_id;
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          if (num < 0) {
            that.setData({
              popNum: that.data.popNum - 1
            });
          } else {
            that.setData({
              popNum: that.data.popNum + 1
            });
          }
          that.getCart();
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 1500
          });
          that.getCart();
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  changeCount(foodDatid, type) {
    //this.data.carts[index]
    let that = this;
    if (type == 'carts') {
      if (this.data.carts[foodDatid].total < 0) {
        wx.showToast({
          title: "商品数量不能为负数",
          icon: 'none',
          duration: 1500
        });
        that.setData({
          ['carts[' + foodDatid + '].total']: that.data.goodsCartsOld
        });
        return;
      }
      if (this.data.carts[foodDatid].total < that.data.goodsCartsOld) {
        let lowerNum = that.data.goodsCartsOld - this.data.carts[foodDatid].total;
        that.updateCart(this.data.carts[foodDatid].id, -lowerNum);
      } else if (this.data.carts[foodDatid].total > that.data.goodsCartsOld) {
        let addNum = this.data.carts[foodDatid].total - that.data.goodsCartsOld;
        that.updateCart(this.data.carts[foodDatid].id, addNum);
      } else if ((this.data.carts[foodDatid].total == that.data.goodsCartsOld)) {
        return;
      }
    } else {
      if (this.data.goodsCarts[foodDatid].total < 0) {
        wx.showToast({
          title: "商品数量不能为负数",
          icon: 'none',
          duration: 1500
        });
        that.setData({
          ['goodsCarts[' + foodDatid + '].total']: that.data.goodsCartsOld
        });
        return;
      }
      if (this.data.goodsCarts[foodDatid].total < that.data.goodsCartsOld) {
        let lowerNum = that.data.goodsCartsOld - this.data.goodsCarts[foodDatid].total;
        that.updateCart(this.data.goodsCarts[foodDatid].id, -lowerNum);
        console.log('kkkk_0:::');
      } else if (this.data.goodsCarts[foodDatid].total > that.data.goodsCartsOld) {
        let addNum = this.data.goodsCarts[foodDatid].total - that.data.goodsCartsOld;
        that.updateCart(this.data.goodsCarts[foodDatid].id, addNum);
        console.log('kkkk_1:::');
      } else if ((this.data.goodsCarts[foodDatid].total == that.data.goodsCartsOld)) {
        console.log('kkkk_2:::');
        return;
      }
    }

  },
  changeCount_1(e) {
    let that = this;
    let val = e.detail.value;
    let id = e.currentTarget.dataset.id;
    that.setData({
      ['goodsCarts[' + id + '].total']: val
    });
    let goodsCartsData = this.data.goodsCarts[id];
    if (goodsCartsData.total < 0) {
      wx.showToast({
        icon: 'none',
        title: "商品数量不能为负数",
        duration: 1500
      });
      that.setData({
        ['goodsCarts[' + id + '].total']: that.data.goodsCartsOld
      });
      return;
    }
    if (goodsCartsData.total < that.data.goodsCartsOld) {
      let lowerNum = that.data.goodsCartsOld - goodsCartsData.total;
      that.updateCart(goodsCartsData.id, -lowerNum);
    } else if (goodsCartsData.total > that.data.goodsCartsOld) {
      let addNum = goodsCartsData.total - that.data.goodsCartsOld;
      that.updateCart(goodsCartsData.id, addNum);
    } else if (goodsCartsData.total == that.data.goodsCartsOld) {
      return;
    }
  },
  clickCount(e) {
    let total = e.currentTarget.dataset.total;
    this.setData({
      goodsCartsOld: total
    });
  },
  Countstop(e) {

  },
  addCart(goods, tag, goodindex, index, foodindex) {
    let that = this;
    let id = "";
    if (tag === "cart") {
      id = goods.goods_id;
    } else {
      id = goods.id;
    }
    let urlStr = app.getNetAddresss('plugin.store-cashier.frontend.shoppingCart.member-cart.store');
    urlStr += '&goods_id=' + id;
    urlStr += '&total=1';
    urlStr += '&store_id=' + this.data.store_id;
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.getCart();
          // if (tag === "cart") {
          // 	that.getCart();
          // } else {
          // 	that.getCart(goodindex, index, foodindex);
          // }
        } else {
          that.getCart();
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  getCart(goodindex, index_1, foodindex) {
    let that = this;
    let urlStr = app.getNetAddresss('plugin.store-cashier.frontend.shoppingCart.member-cart.index');
    urlStr += '&store_id=' + this.data.store_id;
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            carts: res.data,
            goodsCarts: res.data,
          });
          that.data.cartsNum = 0;
          that.data.cartsTotal = 0;
          let cartsNum = 0,
            cartsTotal = 0;
          that.data.carts.forEach((item, index) => {
            // that.setData({
            // 	['goodsCarts[' + item.goods_id + ']']: item
            // })
            // if (foodindex && that.data.goods[goodindex][index_1].goods[foodindex].id == item.goods_id) {
            // 	that.setData({
            // 		['goods[' + goodindex + '][' + index_1 + '].goods[' + foodindex + '].buyNum']: item.total
            // 	})
            // }
            if (item.goods_id === that.data.goodsInfo.id && item.option_id === optionsId) {
              that.setData({
                popNum: item.total,
                popCard: item
              });
            }
            cartsNum += item.total;
            cartsTotal += (item.total * item.goods.price);

          });
          that.setData({
            cartsNum,
            cartsTotal: parseFloat(cartsTotal).toFixed(2),
            goodsCartsTotal: that.calculateTotal(that.data.carts)
          });

        }
        wx.hideLoading();
        that.setData({
          buttondisab: true
        });
      },
      fail: function (res) {
        wx.hideLoading();
        that.setData({
          buttondisab: true
        });
        console.log(res);
      }
    });
  },
  //不同规格的同一商品求和
  calculateTotal(arr) {
    let newArr = []; // 保存求和后的购物车数量列表
    let temp = {};
    let newArr2 = [];
    for (let i in arr) {
      let key = arr[i].goods_id;
      if (temp[key]) {
        temp[key].total = temp[key].total + arr[i].total; //id相同则把数量相加
      } else {
        temp[key] = {};
        temp[key].goods_id = arr[i].goods_id;
        temp[key].total = arr[i].total;
      }
    }
    for (let k in temp) {
      newArr.push(temp[k]);
    }
    newArr.forEach(item => {
      newArr2[item.goods_id] = item;
    });
    return newArr2;
  },
  selectMenu(id) {
    console.log(id);
    this.data.secondTitle.forEach((title, i) => {
      if (title.id === id) {
        this.setData({
          Index: i,
          scrollTop: listHeight[i]
        });
        return i;
      }
    });
  },
  goToAdress() {
    let latitude = this.data.store.lat;
    let longitude = this.data.store.lng;
    let store_name = this.data.store.store_name;
    let point = app.BMapTransqqMap(parseFloat(longitude), parseFloat(latitude));
    wx.openLocation({
      latitude: point.lat,
      longitude: point.lng,
      scale: 18,
      name: store_name
    });
  },
  gophone() {
    let mobile = this.data.store.store_mobile;
    wx.makePhoneCall({
      phoneNumber: mobile
    });
  },
  isHasDifferType(data) {
    //门店购物车提交结算的时候，要判断当前购物车中是否同时存在普通商品和安装服务商品，如果同时存在，要弹框提示
    // 商品不是安装服务商品，直接没有live_install这个字段
    let open_state = 0; //有安装服务的商品
    let clone_state = 0; //没安装服务的商品
    let plugin_name = "";
    data.forEach(item => {
      if (item.live_install && item.live_install.open_state == 1) {
        open_state += 1;
        plugin_name = item.live_install.plugin_name;
      } else {
        clone_state += 1;
      }
    });
    if (open_state != 0 && clone_state != 0) {
      //都有值说明存在 两种 不同商品类型，提示框显示
      wx.showModal({
        title: '提示',
        content: `普通商品与${plugin_name}商品一同下单将无法享受${plugin_name}，是否继续下单？`,
        success: (res) => {
          if (res.confirm) {
            this._goodsOrder(data, true);
          } else if (res.cancel) {
            console.log(res.cancel);
          }
        }
      });
      return false;
    }
    return true;
  },
  goodsOrder(e) {
    console.log(e);
    let val = e.currentTarget.dataset.goodscarts;
    this._goodsOrder(val);
  },
  _goodsOrder(val, status) {
    let sum = 0;
    if (!status && !this.isHasDifferType(val)) {
      return;
    }
    this.data.carts.forEach(val => {
      sum += val.total;
    });
    if (sum == 0) {
      return;
    }
    if (val.length == 0 || this.data.carts.length == 0) {
      return;
    } else {
      wx.navigateTo({
        url: '/packageD/buy/myOrder_v2/myOrder_v2?tag=store&store_id=' + this.data.store_id
      });
    }
  },
  clearCart() {
    var that = this;
    var destroyCarts = [];
    this.data.carts.forEach(item => {
      destroyCarts.push(item.id);
    });
    let urlStr = app.getNetAddresss('plugin.store-cashier.frontend.shoppingCart.member-cart.destroy');
    urlStr += '&store_id=' + this.data.store_id;
    urlStr += '&ids=' + destroyCarts;
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.getCart();
          that.setData({
            showCart: false,
            popNum: 0
          });
          that.getminicartStyle();
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  goTOHome() {
    wx.redirectTo({
      url: '/packageC/o2o/o2oHome/o2oHome'
    });
  },
  // 关闭弹窗
  close() {
    this.setData({
      show2: false
    });
    //确认后清空数值
    optionsId = "";
    specsManage = [];
    this.setData({
      specid: "",
      popNum: 0
    });
  },
  //界面选择规格触发事件
  selectSpecs(e, str, i) {
    let id = 0;
    let index = 0;
    let indexl = 0;
    // let data = {};
    if (str == 'first') {
      id = e.id;
      index = 0;
      indexl = i;
      // data = e;
    } else {
      id = e.currentTarget.dataset.itemid;
      index = e.currentTarget.dataset.index;
      indexl = e.currentTarget.dataset.indexl;
      // data = e.currentTarget.dataset.item;
    }

    //处理选择池
    this.manageSpecs(indexl, index);
    //处理规格组合选择状态
    this.setGoodsSpecs(indexl, index);
    //设置选择规格后的 价格、照片、库存
    this.setGoodsSpecsChangeInfo(id);
    //判断当前购买总量与库存的关系
    this.getMaxCount();
  },
  //处理选择池
  manageSpecs(indexl, index) {
    let data = this.data.goodsInfo.has_many_specs[indexl].specitem[index];
    var specsObject = new Object();
    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.goodsInfo.has_many_specs.length) {
      var newSpecsManage = [];
      for (let i = 0; i < this.data.goodsInfo.has_many_specs.length; i++) {
        for (let j = 0; j < specsManage.length; j++) {
          if (this.data.goodsInfo.has_many_specs[i].id == specsManage[j].specid) {
            newSpecsManage.push(specsManage[j]);
            break;
          }
        }
      }
      specsManage = newSpecsManage;
    }
    this.setGoodsDescription();
  },
  //处理goodsDescription 数据
  setGoodsDescription() {
    var description = "";
    //相等代表全选了 体现语句
    if (specsManage.length == this.data.goodsInfo.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.goodsInfo.has_many_specs.length; i++) {
        for (let j = 0; j < specsManage.length; j++) {
          if (this.data.goodsInfo.has_many_specs[i].id != specsManage[j].specid) {
            description += this.data.goodsInfo.has_many_specs[i].title + " ";
            break;
          }
        }
      }
      this.setData({
        goodsDescription: description
      });
    }
  },
  //处理规格组合选择状态 过滤数据
  setGoodsSpecs(indexl, index) {
    let specs = this.data.goodsInfo.has_many_specs[indexl].specitem[index];
    for (let i = 0; i < this.data.goodsInfo.has_many_specs.length; i++) {
      if (specs.specid != this.data.goodsInfo.has_many_specs[i].id) {
        this.setGoodsSpecsStatus(i,
          specs.id
        );
      }
    }
  },
  //处理规格组合选择状态 处理状态 specitem 组合数组(未选中的) id当前选中的ID 根据ID 组合算是否有当前组合
  setGoodsSpecsStatus(index, id) {
    let specitem = this.data.goodsInfo.has_many_specs[index].specitem;
    let options = []; //数据池
    for (let i = 0; i < this.data.goodsInfo.has_many_options.length; i++) {
      let _specs = this.data.goodsInfo.has_many_options[i].specs.split("_");
      for (let j = 0; j < _specs.length; j++) {
        if (_specs[j] == id) {
          options.push(this.data.goodsInfo.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) {
              this.setData({
                ['data.goodsInfo.has_many_specs[' + index + '].specitem[' + n + '].c']: true
              });
              return;
            }
          }
        } else if (_specs[y] != id && options[m].stock > 0) {
          for (let n = 0; n < specitem.length; n++) {
            if (_specs[y] == specitem[n].id) {
              this.setData({
                ['data.goodsInfo.has_many_specs[' + index + '].specitem[' + n + '].c']: false
              });
              return;
            }
          }
        }
      }
    }
  },
  //设置选择规格后的 价格、照片、库存
  setGoodsSpecsChangeInfo(id) {
    //根据ID 排序 specsManage.sort();
    specsManage.sort(function (a, b) {
      return a.id - b.id;
    });
    if (specsManage.length === this.data.goodsInfo.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); //处理"_"
      this.setData({
        specid: goodsSpecs
      });
      for (let i = 0; i < this.data.goodsInfo.has_many_options.length; i++) {
        if (goodsSpecs === this.setGoodsSpecsBySort(this.data.goodsInfo.has_many_options[i].specs)) {
          this.setData({
            popmPrice: this.data.goodsInfo.has_many_options[i].market_price, //设置价格
            popPrice: this.data.goodsInfo.has_many_options[i].product_price, //设置价格
            popThumb: app._isTextEmpty(this.data.goodsInfo.has_many_options[i].thumb) ? this.data.goodsInfo.thumb : this.data
              .goodsInfo.has_many_options[i].thumb, //设置图片
            popStock: this.data.goodsInfo.has_many_options[i].stock
          });
          optionsId = this.data.goodsInfo.has_many_options[i].id; //设置规格ID，用于生成订单
          optionsMaxCount = this.data.goodsInfo.has_many_options[i].stock; //库存最大数 用于切换更改买家购买数量
          if (optionsMaxCount > 0) {
            this.setData({
              popNum: 0
            });
          }
          break;
        }
      }
      for (let i = 0; i < this.data.carts.length; i++) {
        if (this.data.carts[i].goods_id === this.data.goodsInfo.id && this.data.carts[i].option_id === optionsId) {
          this.setData({
            popNum: this.data.carts[i].total,
            popCard: this.data.carts[i]
          });
          break;
        }
        this.setData({
          popNum: 0,
          popCard: {}
        });
      }
    } else {
      let goodsSpecs = "";
      for (let j = 0; j < specsManage.length; j++) {
        goodsSpecs += specsManage[j].id + "_";
      }
      this.setData({
        specid: goodsSpecs
      });
    }
  },
  //处理商品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() {
    if (specsManage.length == this.data.goodsInfo.has_many_specs.length) {
      if (optionsMaxCount == 0) {
        //库存不足
        this.setData({
          popNum: 0
        });
      }
      if (this.data.popNum > optionsMaxCount) {
        this.setData({
          popNum: optionsMaxCount
        });
      }
    }
  },
  //弹窗提交确认
  submitAction() {
    if (specsManage.length < this.data.goodsInfo.has_many_specs.length) {
      //请选择规格
      this.setData({
        show2: false
      });
      wx.showToast({
        title: this.data.goodsDescription,
        icon: 'none',
        duration: 1500
      });
      return;
    }
    //处理参数
    this.addCartRequest(this.data.goodsInfo.id, optionsId);
  },
  //加入购物车网络操作
  addCartRequest(_goodsId, _optionsId) {
    if (optionsMaxCount === 0) {
      //库存不足
      wx.showToast({
        title: "商品库存不足",
        icon: 'none',
        duration: 1500
      });
      return;
    }
    let that = this;
    let urlStr = app.getNetAddresss('plugin.store-cashier.frontend.shoppingCart.member-cart.store');
    urlStr += '&goods_id=' + _goodsId;
    urlStr += '&total=1';
    urlStr += '&option_id=' + _optionsId;
    urlStr += '&store_id=' + this.data.store_id;
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            popNum: that.data.popNum + 1,
          });
          that.getCart();
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 1500
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  showToolbar() {
    this.setData({
      toolbar: !this.data.toolbar
    });
  },
  gohome() {
    wx.reLaunch({
      url: '/packageG/index/index'
    });
  },
  goorderlist() {
    wx.navigateTo({
      url: '/packageA/member/myOrder_v2/myOrder_v2'
    });
  },
  gomember() {
    wx.reLaunch({
      url: '/packageG/member_v2/member_v2'
    });
  },
  cartChange(e) {
    let bol = e.detail;
    this.setData({
      cartchecked: bol
    });
  },
  //初始化弹窗view
  initPopView() {
    optionsId = "";
    specsManage = [];
    this.setData({
      specid: "",
      popNum: 0
    });
    if (this.data.goodsInfo.has_option === 1) {
      //是否有规格
      this.setData({
        popTitle: this.data.goodsInfo.title,
        popThumb: this.data.goodsInfo.thumb,
        popStock: this.data.goodsInfo.stock,
        popCard: {}
      });
      if (!this.data.specid.length) {
        this.setData({
          popPrice: this.data.goodsInfo.min_price + "-" + this.data.goodsInfo.max_price
        });
      }
      this.setData({
        goodsDescription: '请选择'
      });
      for (let i = 0; i < this.data.goodsInfo.has_many_specs.length; i++) {
        this.setData({
          goodsDescription: this.data.goodsDescription + " " + this.data.goodsInfo.has_many_specs[i].title
        });
      }

      if (!this.data.optionsId) {
        // 默认选择第一个
        for (let i = 0; i < this.data.goodsInfo.has_many_specs.length; i++) {
          this.selectSpecs(this.data.goodsInfo.has_many_specs[i].specitem[0], 'first', i);
        }
      }

    } else {
      this.setData({
        goodsDescription: ""
      });
      optionsMaxCount = this.data.goodsInfo.stock; //设置最大购买量
    }
  },
  getminicartStyle() {
    if (this.data.showCart) {
      this.setData({
        minicartStyle: "display: none;transform: translateY(-100%)",
        leftPrice: "transform: translateX(-60px);"
      });
    } else {
      this.setData({
        minicartStyle: "transform: translateY(0)",
        leftPrice: ''
      });
    }
  }
});