// pages/category_v2/category_v2.js
var app = getApp();
import * as watch from "../../../utils/watch.js";
var specsManage = []; // 选择池 用于排序
var optionsId = ""; // 选择后的 规格ID
var optionsMaxCount = 1;
var location = require("../../../mybehaviors/location/location");

let categoryApi = {
  home: "goods.category.category-home",
  children: "goods.category.get-children-category",
  goods: "goods.category.get-goods-list-by-category-id"
};
let activeApi;
Page({
  behaviors: [location],
  /**
   * 页面的初始数据
   */
  data: {
    language: "",
    brandShow: "",
    categoryShow: "",
    active: 9999,
    active2: true,
    allLoaded: false,
    topStatus: "",
    err: true,
    turl: "/category",
    arg: {
      index: 10,
      item: "pinch",
    },
    onelist: [],
    contentlist: {},
    cartInfo: {},
    list: [],
    goodsInfo: {},
    // advimg: window.localStorage.adv_img,
    carts: [],
    cartIDs: [],
    specid: "", // 规格ID
    goodsCarts: [], // 购物车转为goods key的数组
    goodsCartsTotal: [],
    activeName: "", // 分类折叠面板
    secondaryId: "", // 二级分类id
    threeId: "", // 三级分类ID
    threeInfo: [], // 三级商品列表
    show2: false, // 规格弹窗
    showTitle: "", // 分类折叠标题
    titleInfo: {}, // 用于保存分类折叠时自定义标题分类
    foodInfo: [],
    show: true,
    // more
    page: 1, // 分页数，当前页数
    isLoadMore: true, // 判断是否要加载更多的标志
    total_page: 0, // 总页数
    activatId: "", // 当前的分类id
    LoadMoreTest: "",

    isGetCart: true, // 是否请求获取购物车接口数据
    ADImg: "", // 广告图片地址
    ADUrl: "", // 广告跳转链接
    small_cat_adv_url: null, //广告跳转小程序
    isRecommend: true, // 是否为推荐分类
    showCate: false,
    state: {}, // 广告的数据对象
    scrollTop: null, // 滚动的距离
    flxShow: false, // 控制是否固定顶部
    category_template: "01", //后台开启那个模板
    lastItem: "",
    lastIndex: "",
    parent_id: null,

    isCategoryMore: false, //装修01，03导航栏分类加载更多
    isCategory_total_page: 0,
    isCategoryPage: 1,

    popPrice: "",
    integral: "积分",

    main_category_page: 1,
    main_category_total: 0,

    isSelfPickCategory: false, //是否为供应商管理的自提点的分类页，#75504；
    deliverId: null,
    point:{},
    isMultiSpecs: false, //多规格商品是否显示会员价
    specsVIPPrc: null, //规格商品会员价
    template_no:true,
    fiveShow:false
  },

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

    if (options.tmpl&& options.tmpl == 'dy') {
      //这是 自提点关联供应商 的分类，该分类页面只显示自提点关联的供应商的商品和平台商品（包含聚合供应链商品），其他供应商商品不显示，没有关联自提点的供应商商品也不显示。
      this.data.isSelfPickCategory = true;
      await this.getNowPackageDeliver();
    }else{
      activeApi = categoryApi;
    }

    try {
      const value = wx.getStorageSync("zoneId");
      if (value) {
        this.setData({
          zoneId: value,
        });
        // Do something with return value
      }
    } catch (e) {
      // Do something when catch error
    }
    watch.setWatcher(this);
    wx.showLoading({
      title: "加载中",
      mask: true,
    });

    // 为了浏览商品返回保持原来的位置
    this.data.isGetCart = false;
    if (this.data.lastItem) {
      this.tabsaData(this.data.lastIndex, this.data.lastItem);
    } else {
      this.getCategoryNew();
    }
  },

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

    const value = wx.getStorageSync("integral");
    if (value) {
      this.setData({
        integral: value,
      });
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if(this.data.deliverId) this.getNowPackageDeliver();
    wx.showShareMenu({
      withShareTicket: false,
      menus: ["shareAppMessage", "shareTimeline"],
    });
    if (this.data.isGetCart && (this.data.category_template == "01" || this.data.category_template == "04" || this.data.category_template == "05")) {
      this.updateData();
    } else {
      this.data.isGetCart = true;
    }
  },

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

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

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

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

  /**
   * 用户点击右上角分享
   */
  onShareTimeline() {
    var value = wx.getStorageSync("yz_uid");
    var mid = "";
    if (value) {
      mid = value;
    }
    return {
      title: this.data.title,
      query: `mid=${mid}`,
    };
  },
  onShareAppMessage: function () {
    var value = wx.getStorageSync("yz_uid");
    var mid = "";
    if (value) {
      mid = value;
    }
    return {
      path: "/packageG/pages/category_v2/category_v2?mid=" + mid,
    };
  },
  onPageScroll: function (e) {
    if (e.scrollTop == 0) {
      this.setData({
        flxShow: false,
      });
    }
  },
  watch: {
    activeName: function (newVal) {
      if (newVal.length != "") {
        this.setData({
          showTitle: [],
        });
      } else {
        let showTitle = this.data.titleInfo;
        this.setData({
          showTitle,
        });
      }
    },
  },
  getMoreCategoryNew() {
    let {
      main_category_page,
      main_category_total
    } = this.data;
    if (main_category_page >= main_category_total) return;
    console.log("加载更多主分类");
    this.data.main_category_page++;
    let urlStr = app.getNetAddresss(activeApi.home);
    let jsons = {
      page: this.data.main_category_page,
    };
    app._getNetWork({
      url: urlStr,
      data: jsons,
      success: (resdata) => {
        let res = resdata.data;
        let nextData = res.data.category.data;
        this.setData({
          onelist: this.data.onelist.concat(nextData)
        });
      }
    });
  },
  bindscrolltolower(e) {
    if (this.data.isLoadMore) {
      this.getMoreData();
    } else {
      console.log("没有更多数据");
      wx.showToast({
        title: "没有更多数据",
        icon: "none",
      });
    }
  },
  bindscrolltolower02(e) {
    if (this.data.isLoadMore) {
      this.getMoreData02(1);
    } else {
      console.log("没有更多数据");
      wx.showToast({
        title: "没有更多数据",
        icon: "none",
      });
    }
  },
  upper(e) {
    this.setData({
      flxShow: false,
    });
  },
  changeScroll(e) {
    this.data.scrollTop = e.detail.scrollTop;
    if (e.detail.scrollTop > 180 && !app._isTextEmpty(this.data.ADUrl)) {
      this.setData({
        flxShow: true,
      });
    } else if (app._isTextEmpty(this.data.ADUrl) && e.detail.scrollTop > 10) {
      this.setData({
        flxShow: true,
      });
    } else if (e.detail.scrollTop < 10) {
      this.setData({
        flxShow: false,
      });
    }
  },
  clickActive(e) {
    // 点击顶部滑动的分类事件
    let sInfo = e.target.dataset.item || e.currentTarget.dataset.item;
    if (!this.data.isRecommend) {
      this.setData({
        ADImg: sInfo.adv_img,
        ADUrl: sInfo.adv_url,
      });
    }
    this.setData({
      secondaryId: sInfo.id,
    });
    if (!app._isTextEmpty(sInfo.has_many_children)) {
      let all = [{
        name: "全部",
        id: sInfo.id,
      },];
      let add_allCategory3 = this.data.category_template != "05"?[...all, ...sInfo.has_many_children]:[...sInfo.has_many_children];
      this.setData({
        threeInfo: add_allCategory3,
        threeId: sInfo.id,
        activatId: sInfo.id,
      });
      console.log(this.data.threeInfo,'sssssss左侧点击二级的时候');
      if(this.data.threeInfo.length > 0 && this.data.category_template == "05"){
        // 模板05，如果点击二级分类下有三级分类，显示三级分类商品,默认显示第一个
        this.setData({
          threeId:this.data.threeInfo[0].id
        });
        this.getData(this.data.threeInfo[0].id);
      }else{
        this.getData(sInfo.id);
      }
      // this.koosThree(sInfo.has_many_children[0].id)
    } else {
      this.setData({
        threeInfo: [],
        activatId: sInfo.id,
      });
      this.getData(sInfo.id);
    }
  },
  tabsa(e) {
    let index = e.currentTarget.dataset.index;
    let item = e.currentTarget.dataset.item;
    // console.log(item, '类型')
    if(this.data.lastIndex == index){
      this.data.fiveShow = !this.data.fiveShow;
    }else{
      this.data.fiveShow = true;
    }
    this.tabsaData(index, item);
    this.setData({
      lastIndex: index,
      lastItem: item,
      fiveShow:this.data.fiveShow
    });
  },
  bpfun() {
    wx.navigateTo({
      url: "/packageB/member/category/brand_v2/brand_v2",
    });
  },
  allList() {
    this.setData({
      active2: true,
      active: 9999,
    });
    this.getCategoryNew("allList");
    //this.getContentlist2()
  },
  tabsaData(n, i) {
    console.log(n,i,'sssssss');
    this.setData({
      "state.adv_img": i.adv_img,
      "state.adv_url": i.small_adv_url,
    });
    this.setData({
      active: n,
      active2: false,
      parent_id: i.id,
    });
    this.getContentlist(i.id);
    if (this.data.category_template == "01" || this.data.category_template == "04" || this.data.category_template == "03" ) {
      this.getData(i.id);
    }
  },
  clickADTo() {
    if (this.data.active2) {
      // console.log(this.data.small_cat_adv_url)
      try {
        wx.navigateTo({
          url: this.data.small_cat_adv_url,
        });
      } catch (err) {
        console.log(err);
      }
    } else {
      try {
        wx.navigateTo({
          url: this.data.state.adv_url,
        });
      } catch (err) {
        console.log(err);
      }
    }
    return;
  },
  getContentlist(id) {
    let that = this;
    let urlStr = app.getNetAddresss(activeApi.children);
    console.log('activeApi.children222');
    urlStr += "&parent_id=" + id;
    urlStr += "&as_id=" + this.data.zoneId;
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            isLoadMore: true,
            page: 1,
          });
          that.setData({
            isRecommend: false,
          });
          that.setData({
            err: false,
          });
          if (that.data.category_template == "01" || that.data.category_template == "03" || that.data.category_template == "04" || that.data.category_template == "05") {
            if (res.data.goods_list.last_page) {
              that.setData({
                total_page: res.data.goods_list.last_page,
              });
            } else {
              that.setData({
                total_page: 0,
              });
            }
            that.setData({
              "contentlist.recommend": res.data.data,
              "contentlist.set": res.data.set,
              "contentlist.member_cart": that.data.cartInfo,
            });
            if (res.data.goods_list.data) {
              // that.setData({
              // 	foodInfo: res.data.goods_list.data
              // })
            } else {
              that.setData({
                foodInfo: [],
              });
            }
            // ------------------------------------------
            console.log(that.data.contentlist);
            let ooo = that.data.contentlist;
            that.setData({
              list: ooo,
            });
            console.log(that.data.list,'activeApi.list');
            // if (res.data.set.cat_level == 2) {
            that.setData({
              ADImg: that.data.state.adv_img,
              ADUrl: that.data.state.adv_url,
              isCategory_total_page: res.data.last_page,
              isCategoryPage: 1,
              isCategoryMore: res.data.last_page > 1 ? true : false,
            });
            // }
            that.setCatagory(that.data.contentlist);
          } else {
            if (res.data.last_page) {
              that.setData({
                total_page: res.data.last_page,
              });
            } else {
              that.setData({
                total_page: 0,
              });
            }
            let contentlist_one = res.data;
            contentlist_one.tjfl = false;
            contentlist_one.set = res.data.set;
            that.setData({
              contentlist_one: contentlist_one,
              list: contentlist_one,
            });
          }
          if (that.data.page < that.data.total_page) {
            that.setData({
              LoadMoreTest: "加载更多",
            });
          } else {
            that.setData({
              LoadMoreTest: "没有更多",
            });
          }
        } else {
          that.setData({
            err: true,
          });
          console.log(res.msg);
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },

  onChange(e) {
    this.setData({
      activeName: e.detail,
    });
  },
  getCategoryNew() {
    let that = this;
    let urlStr = app.getNetAddresss(activeApi.home);
    let jsons = {
      as_id: this.data.zoneId,
    };
    app._getNetWork({
      url: urlStr,
      data: jsons,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            main_category_total: res.data.category.last_page,
            category_template: res.data.category_template ? res.data.category_template.names : "01",
          });
          if(res.data.set.web_design_enable){
            // 页面设计插件轮播 web_design_enable插件是否开启
            that.getwebdesImg();
          }
          // 从yz_basic_info获取新装修设置
          let basic_info = wx.getStorageSync("yz_basic_info");
          // this.isSelfPickCategory为true时，则为供应商自提点分类页，固定为01模板
          if (basic_info && basic_info.home.item.is_decorate === 1&& !that.data.isSelfPickCategory) {
            if (basic_info.home.item.ViewSet.category.is_default != 0) {
              that.setData({
                category_template: basic_info.home.item.ViewSet.category.code.substring(8),
              });
            } else {
              that.setData({
                category_template: "01",
              });
            }
          }
          wx.hideLoading();
          that.setData({
            showCate: true,
          });

          that.setData({
            onelist: res.data.category.data,
            err: false,
            isRecommend: true,
          });
          console.log(that.data.onelist);
          if (that.data.category_template == "01" || that.data.category_template == "03" || that.data.category_template == "04" || that.data.category_template == "05") {
            if (res.data.goods_list.last_page) {
              that.setData({
                total_page: res.data.goods_list.last_page,
              });
            } else {
              that.setData({
                total_page: 0,
              });
            }
            if (that.data.page < that.data.total_page) {
              that.setData({
                LoadMoreTest: "加载更多",
              });
            }
            res.data.recommend.goo = true;
            that.setData({
              cartInfo: res.data.member_cart,
              page: 1,
              isLoadMore: true,
            });
            if (res.data.goods_list.data) {
              that.setData({
                foodInfo: res.data.goods_list.data,
              });
            } else {
              that.setData({
                foodInfo: [],
              });
            }

            if (res.data.set.cat_brand && res.data.set.cat_brand.length > 0) {
              that.setData({
                brandShow: res.data.set.cat_brand,
              });
            }

            if (res.data.set.cat_class && res.data.set.cat_class.length > 0) {
              that.setData({
                categoryShow: res.data.set.cat_class,
              });
              if (that.data.categoryShow != "0" && that.data.onelist.length > 0) {
                console.log('sssssss初始化的时候');
                that.tabsaData(0, that.data.onelist[0]);
              }
            }

            // ------------------------------------------------
            if (that.data.categoryShow == "0") {
              console.log('第一次进入的是推荐分类页面');
              that.setData({
                "contentlist.recommend": res.data.recommend,
                "contentlist.set": res.data.set,
                "contentlist.member_cart": res.data.member_cart,
                list: that.data.contentlist,
                ADImg: res.data.set.cat_adv_img,
                ADUrl: res.data.set.cat_adv_url,
                small_cat_adv_url: res.data.set.small_cat_adv_url,
              });
              that.setCatagory(that.data.contentlist);
            }
          } else {
            that.setData({
              isLoadMore: false,
            });
            let contentlist_one = {};
            contentlist_one.goo = true;
            contentlist_one.dataK = res.data.recommend;
            contentlist_one.tjfl = true;
            contentlist_one.set = res.data.set;
            if (res.data.set.cat_brand && res.data.set.cat_brand.length > 0) {
              that.setData({
                brandShow: res.data.set.cat_brand,
              });
            }
            if (res.data.set.cat_class && res.data.set.cat_class.length > 0) {
              that.setData({
                categoryShow: res.data.set.cat_class,
              });
              if (that.data.categoryShow != "0" && that.data.onelist.length > 0) {
                that.tabsaData(0, that.data.onelist[0]);
              }
            }

            if (that.data.categoryShow == "0") {
              that.setData({
                contentlist_one: contentlist_one,
                list: contentlist_one,
              });
            }
          }
          // console.log('dddddd', that.data.contentlist_one)
        } else {
          wx.hideLoading();
          that.setData({
            err: true,
            showCate: true,
          });
          console.log(res.msg);
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  // 获取更多数据，加载更多
  getMoreData() {
    // 防止多次请求分页数据
    const that = this;
    if (that.data.page >= that.data.total_page) {
      that.setData({
        LoadMoreTest: "没有更多",
      });
      that.setData({
        isLoadMore: false,
      });
      return;
    } else {
      that.setData({
        isLoadMore: true,
      });
      let page = that.data.page;
      page += 1;
      that.setData({
        page,
      });
      let urlStr = app.getNetAddresss(activeApi.goods);
      let jsons = {
        goods_page: that.data.page,
        category_id: that.data.activatId,
      };
      app._getNetWork({
        url: urlStr,
        data: jsons,
        success: function (resdata) {
          var res = resdata.data;
          that.setData({
            isLoadMore: true,
          });
          if (res.result == 1) {
            let foodInfo = that.data.foodInfo;
            foodInfo = foodInfo.concat(res.data.data); // 进行数组拼接
            that.setData({
              foodInfo,
            });
          } else {
            let pages = that.data.page;
            pages -= 1;
            that.setData({
              page: pages,
              isLoadMore: false,
            });
            return;
          }
        },
        fail: function (res) {
          console.log(res);
        },
      });
    }
  },
  // 获取更多数据，加载更多
  getMoreData02(_tag) {
    // 防止多次请求分页数据
    const that = this;
    if (_tag == 1 && that.data.page >= that.data.total_page) {
      that.setData({
        LoadMoreTest: "没有更多",
        isLoadMore: false,
      });
      return;
    } else if (_tag == 0 && that.data.isCategoryPage >= that.data.isCategory_total_page) {
      that.setData({
        isCategoryMore: false,
      });
      return;
    } else {
      that.setData({
        isLoadMore: false,
      });
      let page = _tag == 1 ? that.data.page : that.data.isCategoryPage;
      page += 1;
      if (_tag == 1) {
        that.setData({
          page,
        });
      } else {
        that.setData({
          isCategoryPage: page,
        });
      }

      let urlStr = app.getNetAddresss(activeApi.children);
      console.log('activeApi.children333');
      let jsons = {
        page: _tag == 1 ? that.data.page : that.data.isCategoryPage,
        parent_id: that.data.parent_id,
        as_id: that.data.zoneId,
      };
      app._getNetWork({
        url: urlStr,
        data: jsons,
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            if (_tag == 1) {
              let data = that.data.contentlist_one.data.concat(res.data.data); // 进行数组拼接
              that.setData({
                "contentlist_one.data": data,
                isLoadMore: true,
              });
            } else {
              let data = that.data.list.recommend.concat(res.data.data); // 进行数组拼接
              that.setData({
                "list.recommend": data,
                isCategoryMore: that.data.isCategoryPage >= that.data.isCategory_total_page ? false : true,
              });
            }
          } else {
            let pages = _tag == 1 ? that.data.page : that.data.isCategoryPage;
            pages -= 1;
            if (_tag == 1) {
              that.setData({
                page: pages,
                isLoadMore: false,
              });
            } else {
              that.setData({
                isCategoryPage: page,
              });
            }
            return;
          }
        },
        fail: function (res) {
          console.log("error", res);
        },
      });
    }
  },
  numberLeft(e) {
    let id = e.target.dataset.id || e.currentTarget.dataset.id;
    let num = this.data.goodsCartsTotal;

    Number(num);
    num = Number(num[id].total) - 1;
    this.data.goodsCartsTotal[id].total = num;
    if (this.data.goodsCartsTotal[id].total <= 0) {
      // 小于等于0 清空该商品购物车数量
      this.destroyData(this.data.goodsCarts[id].id);
      return;
    } else {
      this.changeCount(this.data.goodsCarts[id].id, this.data.goodsCartsTotal[id].total);
    }
  },
  numberRight(e) {
    let id = e.target.dataset.id || e.currentTarget.dataset.id;
    let _stock = e.target.dataset.stock || e.currentTarget.dataset.stock;
    let good = e.target.dataset.good || e.currentTarget.dataset.good;
    //价格权限
    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;
    }

    if (_stock == 0) {
      wx.showToast({
        title: "库存为零",
        icon: "none",
      });
      return;
    }

    if (!app._isTextEmpty(this.data.goodsCartsTotal[id])) {
      if (this.data.goodsCartsTotal[id].total >= _stock) {
        console.log("数量超出范围");
        wx.showToast({
          title: "库存不足",
          icon: "none",
        });
        return;
      }
      let obj = this.data.goodsCartsTotal;
      obj = Number(obj[id].total) + 1;
      this.data.goodsCartsTotal[id].total = obj;
    }
    let jsons = {
      goods_id: id,
      total: 1,
    };
    let urlStr = app.getNetAddresss("member.member-cart.store");
    app._getNetWork({
      url: urlStr,
      data: jsons,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          app.globalData.cart_num = res.data.cart_num;
          wx.showToast({
            title: res.msg,
            icon: "none",
          });
          this.updateData();
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
          });
        }
      },
    });
  },
  changeCount(_id, _num) {
    if (_num <= 0) {
      this.destroyData(_id);
      return;
    }
    let json = {
      id: _id,
      num: _num,
    };
    let urlStr = app.getNetAddresss("member.member-cart.updateNumV2");
    app._getNetWork({
      url: urlStr,
      data: json,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          wx.showToast({
            title: res.msg,
            icon: "none",
          });
          this.updateData();
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
          });
          this.setData({
            "goodsCartsTotal[_id].total": 1,
          });
        }
      },
    });
  },
  changeAddCount(e) {
    let _id = e.target.dataset.id || e.currentTarget.dataset.id;
    let _num = e.target.dataset.num || e.currentTarget.dataset.num;
    let index = e.target.dataset.i || e.currentTarget.dataset.i;
    index = Number(index);
    if (_num <= 0) {
      this.destroyData(_id);
      return;
    }
    let json = {
      id: _id,
      num: _num,
    };
    let urlStr = app.getNetAddresss("member.member-cart.updateNumV2");
    app._getNetWork({
      url: urlStr,
      data: json,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          wx.showToast({
            title: res.msg,
            icon: "none",
          });
          if (!app._isTextEmpty(index)) {
            // 规格商品
            let num = this.data.popNum;
            switch (index) {
            case -1:
              num -= 1;
              this.setData({
                popNum: num,
              });
              break;
            case 1:
              num += 1;
              this.setData({
                popNum: num,
              });
              break;
            default:
              console.log("error");
            }
          }
          this.updateData();
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
          });
          this.setData({
            "goodsCartsTotal[_id].total": 1,
          });
        }
      },
    });
  },
  updateData() {
    // 更新购物车数据
    let urlStr = app.getNetAddresss("member.member-cart.index");
    app._getNetWork({
      url: urlStr,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          this.getCart(res.data);
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
          });
        }
      },
    });
  },
  destroyData(_cid) {
    // 清除该购物车商品id
    let urlStr = app.getNetAddresss("member.member-cart.destroy");
    let json = {
      ids: _cid,
    };
    app._getNetWork({
      url: urlStr,
      data: json,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          wx.showToast({
            title: res.msg,
            icon: "none",
          });
          this.updateData();
          this.setData({
            show2: false,
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
          });
        }
      },
    });
  },
  chooseSecondary(e) {
    let sInfo = e.target.dataset.item || e.currentTarget.dataset.item;
    // console.log(sInfo, '数据对象')

    if (!this.data.isRecommend) {
      this.setData({
        ADImg: sInfo.adv_img,
        ADUrl: sInfo.adv_url,
      });
    }
    this.setData({
      secondaryId: sInfo.id,
    });
    if (!app._isTextEmpty(sInfo.has_many_children)) {
      let all = [{
        name: "全部",
        id: sInfo.id,
      },];
      let add_allCategory3 = [...all, ...sInfo.has_many_children];
      this.setData({
        threeInfo: add_allCategory3,
        activatId: sInfo.id,
        threeId: sInfo.id,
      });
      console.log("sssssss", this.data.threeInfo);
      this.getData(sInfo.id);
    } else {
      this.setData({
        threeInfo: [],
      });
      this.getData(sInfo.id);
    }
  },
  koosThree(_tid) {
    this.setData({
      threeId: _tid,
    });
    this.getData(_tid);
  },
  chooseThree(e) {
    let _tid = e.target.dataset.id || e.currentTarget.dataset.id;
    this.setData({
      threeId: _tid,
    });
    this.getData(_tid);
  },
  getData(_id) {
    let jsons = {
      category_id: _id,
      goods_page: 1,
    };
    this.setData({
      activatId: _id,
      activeName: "",
      foodInfo: [],
    });
    let urlStr = app.getNetAddresss(activeApi.goods);
    app._getNetWork({
      url: urlStr,
      data: jsons,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          this.setData({
            page: 1,
            isLoadMore: true,
            total_page: res.data.last_page,
            foodInfo: res.data.data,
          });
          if (res.data.last_page == 1) {
            this.setData({
              LoadMoreTest: "没有更多",
            });
          } else {
            this.setData({
              LoadMoreTest: "加载更多",
            });
          }
          if (!this.data.total_page) {
            this.setData({
              total_page: 0,
            });
          }
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
          });
          console.log(res.msg);
        }
      },
    });
  },
  getCart(goods) {
    this.setData({
      carts: goods,
      goodsCarts: [],
      cartIDs: [],
    });
    let arrObj = {};
    this.data.carts.forEach((item) => {
      arrObj[item.goods_id] = item;
      if (goods && goods.id == item.goods_id) {
        goods.buyNum = item.total;
      }
      if (item.goods_id == this.data.goodsInfo.id && item.option_id == optionsId) {
        this.setData({
          popNum: item.total,
          popCard: item,
        });
      }
      this.data.cartIDs.push(item.id);
    });
    this.setData({
      goodsCarts: arrObj,
    });

    let goodsCartsTotal = this.calculateTotal(this.data.carts);

    this.setData({
      goodsCartsTotal,
    });
  },
  changeblur(e) {
    let value = e.detail.value;
    let id = e.target.dataset.id || e.currentTarget.dataset.id;
    let _stock = e.target.dataset.stock || e.currentTarget.dataset.stock;
    if (value > _stock) {
      let goodsCartsTotals = this.data.goodsCartsTotal;
      wx.showToast({
        title: "商品库存不足",
        icon: "none",
      });
      this.setData({
        goodsCartsTotal: goodsCartsTotals,
      });
      return;
    }
    this.changeCount(id, value);
  },
  // 不同规格的同一商品求和
  calculateTotal(arr) {
    let newArr = [];
    let temp = {};
    let newArr2 = {};
    for (let i in arr) {
      let key = arr[i].goods_id;
      if (temp[key]) {
        // temp[key].goods_id = temp[key].goods_id;
        temp[key].total = temp[key].total + arr[i].total;
      } else {
        temp[key] = {};
        temp[key].goods_id = arr[i].goods_id;
        temp[key].total = arr[i].total;
      }
    }
    for (let k in temp) {
      newArr.push(temp[k]);
    }

    newArr.forEach((item) => {
      newArr2[item.goods_id] = item;
    });

    return newArr2;
  },
  setCatagory(newVal) {
    // 处理点击一级分类时，右侧的二级、三级子分类数据处理
    if (!app._isTextEmpty(newVal.recommend)) {
      let add_allCategory = newVal.recommend;
      if (!this.data.active2 && this.data.category_template != "05") {
        add_allCategory.unshift({
          name: "全部",
          id: this.data.activatId,
          adv_img: this.data.state.adv_img,
          adv_url: this.data.state.adv_url,
        });
      }
      this.setData({
        titleInfo: add_allCategory,
        "list.recommend": add_allCategory,
        "contentlist.recommend": add_allCategory,
        secondaryId: newVal.recommend[0].id,
      });
      // 有三级分类处理
      if (newVal.set.cat_level == "3" && !app._isTextEmpty(newVal.recommend[0].has_many_children)) {
        this.setData({
          threeInfo: newVal.recommend[0].has_many_children,
          threeId: newVal.recommend[0].has_many_children[0].id,
          activatId: this.data.threeId,
          ADImg: newVal.recommend[0].adv_img,
          ADUrl: newVal.recommend[0].adv_url,
        });
        if(this.data.threeId && this.data.category_template == "05"){
          // 模板05，如果有三级分类，右侧商品栏优先显示三级分类商品
          this.getData(this.data.threeId);
        }
      } else {
        this.setData({
          threeInfo: [],
          threeId: null,
          activatId: this.data.secondaryId,
        });
      }
      this.setData({
        activeName: "",
      });
      this.getCart(newVal.member_cart);
    } else {
      this.setData({
        titleInfo: [],
        showTitle: [],
        secondaryId: [],
        threeInfo: [],
        threeId: null,
      });
    }
  },
  // 添加有规格商品到购物车
  addGood(e) {
    let good = e.target.dataset.item || 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
  },
  // 初始化弹窗view
  initPopView() {
    optionsId = "";
    specsManage = [];
    this.setData({
      specid: "",
      popNum: 0,
    });
    if (this.data.goodsInfo.has_option == 1) {
      // 是否有规格
      this.isShowMultiSpecsMemPrice(); //是否需要显示多规格会员价
      this.setData({
        popTitle: this.data.goodsInfo.title,
        popThumb: this.data.goodsInfo.thumb,
        popStock: this.data.goodsInfo.stock,
        popCard: {},
      });
      // 设置默认图片
      // 设置商品名
      // 设置默认库存
      if (!this.data.specid.length) {
        let popPrice = this.data.goodsInfo.min_price + "-" + this.data.goodsInfo.max_price; // 设置默认价格
        if (this.data.goodsInfo.point_goods) {
          popPrice = this.data.goodsInfo.point_goods.min_point + "-" + this.data.goodsInfo.point_goods.max_point; //设置默认价格
        }
        this.setData({
          popPrice: popPrice,
        });
      }
      this.setData({
        goodsDescription: "请选择",
      });
      let goodsDescription;
      for (let i = 0; i < this.data.goodsInfo.has_many_specs.length; i++) {
        goodsDescription = this.data.goodsDescription;
        goodsDescription += "" + this.data.goodsInfo.has_many_specs[i].title;
      }
      this.setData({
        goodsDescription,
      });

      if (!this.data.optionsId) {
        // 默认选择第一个
        for (let i = 0; i < this.data.goodsInfo.has_many_specs.length; i++) {
          if(this.data.goodsInfo.goods_option_ids && this.data.goodsInfo.goods_option_ids.length >= 0){
            for(let j = 0;j < this.data.goodsInfo.has_many_specs[i].has_many_specs_item.length;j++){
              if(this.data.goodsInfo.has_many_specs[i].has_many_specs_item[j].id == Number(this.data.goodsInfo.goods_option_ids[i])){
                this.selectSpecs(this.data.goodsInfo.has_many_specs[i].has_many_specs_item[j],"first", i);
              }
            }
          }else{
            this.selectSpecs(this.data.goodsInfo.has_many_specs[i].has_many_specs_item[0], "first", i);
          }
        }
      }
    } else {
      this.setData({
        goodsDescription: "",
        optionsMaxCount: this.data.goodsInfo.stock,
      });
      // 设置最大购买量
    }
  },
  isShowMultiSpecsMemPrice() {
    //判断是否需要显示多规格会员价【#70785】
    if (this.data.goodsInfo.is_open_micro && Number(this.data.goodsInfo.is_open_micro) == 1 && this.data.goodsInfo.has_option == 1) {
      this.setData({
        isMultiSpecs: true
      });
    } else {
      this.setData({
        isMultiSpecs: false
      });
    }
  },
  // 界面选择规格触发事件
  selectSpecs(e, str, i) {
    let data = {};
    let id = 0;

    if (str == "first") {
      data = e;
      id = e.id;
    } else {
      data = e.target.dataset.item || e.currentTarget.dataset.item;

      id = e.target.dataset.id || e.currentTarget.dataset.id;
    }

    // 处理选择池
    this.manageSpecs(data);

    // 处理规格组合选择状态
    this.setGoodsSpecs(data);

    // 设置选择规格后的 价格、照片、库存
    this.setGoodsSpecsChangeInfo(id);

    // 判断当前购买总量与库存的关系
    this.getMaxCount();
  },
  // 判断当前购买总量与库存的关系
  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,
        });
      }
    }
  },
  // 设置选择规格后的 价格、照片、库存
  setGoodsSpecsChangeInfo(id) {
    let popPrice = "";
    // 根据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)) {
          if (this.data.goodsInfo.point_goods) {
            popPrice = this.data.goodsInfo.point_goods.point_option[i].goods_point; //设置默认价格
          } else {
            popPrice = this.data.goodsInfo.has_many_options[i].product_price; //设置默认价格
          }
          this.setData({
            popPrice: popPrice,
          });
          // 设置默认价格
          // 设置价格
          let popThumb = app._isTextEmpty(this.data.goodsInfo.has_many_options[i].thumb) ? this.data.goodsInfo.thumb : this.data.goodsInfo.has_many_options[i].thumb; // 设置图片
          this.setData({
            popThumb,
            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,
            });
          }
          if (this.data.isMultiSpecs) this.getMemberPrice(optionsId);
          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;
  },
  // 处理选择池
  manageSpecs(data) {
    var specsObject = {};
    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(specs) {
    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(this.data.goodsInfo.has_many_specs[i].has_many_specs_item, specs.id);
      }
    }
  },

  // 处理规格组合选择状态 处理状态 specitem 组合数组(未选中的) id当前选中的ID 根据ID 组合算是否有当前组合
  setGoodsSpecsStatus(specitem, id) {
    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]);
        }
      }
    }

    for (let m = 0; m < options.length; m++) {
      let _specs = options[m].specs.split("_");
      for (let y = 0; y < _specs.length; y++) {
        if (_specs[y] != id && options[m].stock == 0) {
          for (let n = 0; n < specitem.length; n++) {
            if (_specs[y] == specitem[n].id) {
              specitem[n].c = true;
            }
          }
        } else if (_specs[y] != id && options[m].stock > 0) {
          for (let n = 0; n < specitem.length; n++) {
            if (_specs[y] == specitem[n].id) {
              specitem[n].c = false;
            }
          }
        }
      }
    }
  },
  // 弹窗提交确认
  submitAction() {
    let that = this;
    if (specsManage.length < this.data.goodsInfo.has_many_specs.length) {
      // 请选择规格
      this.setData({
        show2: false,
      });
      wx.showToast({
        title: this.data.goodsDescription,
        icon: "none",
      });
      return;
    }
    let urlStr = app.getNetAddresss("member.member-cart.store");
    let json = {
      goods_id: this.data.goodsInfo.id,
      total: 1,
      option_id: optionsId,
    };
    app._getNetWork({
      url: urlStr,
      data: json,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          app.globalData.cart_num = res.data.cart_num;
          wx.showToast({
            title: res.msg,
            icon: "none",
          });
          that.updateData();
          that.setData({
            popNum: that.data.popNum + 1,
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  close() {
    this.setData({
      show2: false,
    });
  },
  gotosearch() {
    let _url = "/packageB/member/category/search_v2/search_v2";
    if(this.data.category_template=='05'){
      // 模板5跳转页面设计搜索页
      wx.navigateTo({
        url: '/packageI/searchPage/searchPage',
      });
      return;
    }
    if (this.options.tmpl&& this.options.tmpl == 'dy') {
      _url = _url + '?tmpl=dy';
    }
    wx.navigateTo({
      url: _url
    });
  },
  gotoGoods(e) {
    let gid = e.target.dataset.id || e.currentTarget.dataset.id;
    let good = e.currentTarget.dataset.good;
    console.log(good);
    if(good.category_option_id){
      wx.navigateTo({
        url: "/packageA/detail_v2/detail_v2?id=" + gid + '&coid='+good.category_option_id,
      });
    }else{
      wx.navigateTo({
        url: "/packageA/detail_v2/detail_v2?id=" + gid,
      });
    }
  },
  async getNowPackageDeliver() {
    //设置该模板的请求接口
    activeApi = {
      home: "plugin.supplier.frontend.category.category-home",
      children: "plugin.supplier.frontend.category.get-children-category",
      goods: "plugin.supplier.frontend.category.get-goods-list-by-category-id"
    };
    //获取自提点信息
    let deliverIDStorage = null;
    try {
      deliverIDStorage = wx.getStorageSync('deliverId'); //获取当前会话是否存储了自提点id
    } catch (e) {
      // Do something when catch error
    }
    if(deliverIDStorage){
      //判断是否有在其他页面更新了自提点id,如果两个id一样则不需要更新请求接口
      if(this.data.deliverId&&this.data.deliverId!=deliverIDStorage){
        this.data.deliverId = deliverIDStorage;
        // 更换了自提点，请求更新分类数据
        this.getCategoryNew();
      }
      return true;
    }else if(!this.options.dyID){
      await this._asyncLocation();
    }
        
    wx.showLoading({
      title: "加载中",
      mask: true,
    });
    return new Promise((resolve, reject) => {
      let _json = {};
      if (this.data.point&&this.data.point.lng) {
        _json = {
          lng: this.data.point.lng||'',
          lat: this.data.point.lat||''
        };
      }
      if (this.options.dyID) {
        _json.deliver_id = this.options.dyID;
      }
      let urlStr = app.getNetAddresss('plugin.package-deliver.frontend.decorate-deliver.getNowPackageDeliver');
      app._postNetWork({
        url: urlStr,
        data: _json,
        success: (resdata) => {
          wx.hideLoading();
          let res = resdata.data;
          if (res.result == 1) {
            this.data.deliverId = res.data.id;
            wx.setStorageSync("deliverId", res.data.id);
            resolve();
          } else {
            wx.showToast({
              title: res.msg,
              duration: 1000,
              icon: 'none'
            });
            reject();
          }
        },
        fail: function (res) {
          wx.hideLoading();
          console.log(res.msg);
        }
      });
    });
  },
  _asyncLocation(){
    return new Promise((resolve, reject) => {
      this._getLocation((mapdata, e)=> {
        let point = app.qqMapTransBMap(
          parseFloat(e.lng),
          parseFloat(e.lat)
        );
        this.data.point = point;
        resolve();
      });
    });
  },
  getMemberPrice(_optionsId) {
    if (!_optionsId) return;
    let specsVIPPrc = 0;
    this.setData({specsVIPPrc});
    let urlStr = app.getNetAddresss("goods.other-info.option-vpi-price");
    urlStr += "&option_id=" + _optionsId;
    app._getNetWork({
      showToastIn: false,
      url: urlStr,
      success: (resdata) => {
        let res = resdata.data;
        if (res.result == 1) {
          specsVIPPrc = res.data.vip_price || null;
        } else {
          specsVIPPrc = null;
        }
        this.setData({specsVIPPrc});
      },
      fail: function (res) {
        specsVIPPrc = null;
        this.setData({specsVIPPrc});
      },
    });
    
  },
  tapUrl(e) {
    let item = e.currentTarget.dataset.item;
    try {
      wx.navigateTo({
        url: item.mini_url,
        fail: ((res) => {
          wx.switchTab({
            url: item.mini_url
          });
        })
      });
    } catch (error) {
      wx.switchTab({
        url: item.mini_url
      });
    }
  },
  getwebdesImg(){
    let urlStr = app.getNetAddresss("plugin.web-design.frontend.carousel.index");
    app._getNetWork({
      url: urlStr,
      success: (resarr)=>{
        let res = resarr.data;
        this.setData({
          webdesImage:res.data
        });
      },
      fail: function (res) {
        wx.showToast({
          title:res.msg,
          icon:'none',
          duration:1000
        });
      },
    });
  }
});