// pages/search_2/search_2.js
var n = 1;
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    istypeclass:false,//是否点击分类进来的
    inputs: "",
    amout: false,
    loading: false,
    allLoaded: true,
    goload: false,
    goods: [],
    order_by: "",
    order_field: "",
    screentitle: ["品牌", "分类", "属性", "高级选项"], //筛选标题
    show: false,
    show1: true,
    show2: false,
    show3: false,
    show4: false,
    select: "",
    brand: {},
    attr: [{
      name: "推荐商品",
      rot: "is_recommand",
      show: true
    },

    {
      name: "新品上市",
      rot: "is_new",
      show: true
    },

    {
      name: "热卖商品",
      rot: "is_hot",
      show: true
    },

    {
      name: "促销商品",
      rot: "is_discount",
      show: true
    },

    {
      name: "限时抢购",
      rot: "limit_buy",
      show: true
    }
    ],
    attrstr: [],
    attrkey: [],
    classification1: [],
    classification2: [],
    // classificationkey: null,
    // classificationkey1: null,
    // classificationkey2: null,
    classificationId: null,
    classificationId1: null,
    classificationId2: null,
    classificationParentIndex: 0,
    typestring: "", //搜索分类id
    namestring: "",
    namekey: null,
    classificationshow: false,
    tagname: [],
    showtagnamekey: null,
    more_show: false,
    shownum: 9000,
    show5: true,
    brandId: "",
    filterId: [],
    nameNotice: false,
    tag: null,
    classifyBol: true,
    zoneId: '',
    coupon: '',
    showcccc: false,
    activeName: '1',
    plugin_id: 0,

    btnFlag: false, // 回到顶部
    btnData: {
      "button_size": 40,
      "over_top": 500,
      "position_location": "right",
      "icon_url": ""
    },

    showHistory: false, // 显示搜索历史
    deliverId: null,
    point:{},
    requestLoading: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    // typestring
    if(options.id!=""&&!isNaN(options.id)){
      this.setData({typestring:options.id,istypeclass:true});
      wx.setNavigationBarTitle({ title: '分类列表' });
    }
    console.log(options.kind);
    try {
      const value = wx.getStorageSync('zoneId');
      if (value) {
        this.setData({
          zoneId: value
        });
        // Do something with return value
      }
    } catch (e) {
      // Do something when catch error
    }
    if (options.fromPage) {
      this.setData({
        fromPage: options.fromPage
      });
    }
    if (options.kind) {
      this.setData({
        kind: 'kind'
      });
    }
    if (options.keyword) {
      this.setData({
        inputs: options.keyword
      });
    }
    if (options.order_field) {
      this.setData({
        order_field: options.order_field
      });
    }
    if (options.order_by) {
      this.setData({
        order_by: options.order_by
      });
    }
    if (options.coupon) {
      this.setData({
        coupon: options.coupon
      });
    }
    if (options.as_id) {
      this.setData({
        zoneId: options.as_id
      });
    }
    if (options.brand_id) {
      this.setData({
        brandId: options.brand_id
      });
    }
    if (options.plugin_id == 1) {
      this.setData({
        plugin_id: options.plugin_id
      });
    }
    if (options.product_attr) {
      let attrStr = options.product_attr.split(",");
      let attr = this.data.attr;
      for (let i = 0; i < attrStr.length; i++) {
        for (let k = 0; k < attr.length; k++) {
          if (attr[k].rot == attrStr[i]) {
            this.setData({
              ['attr[' + k + '].show']: false
            });
            break;
          }
        }

      }
      this.setData({
        attrStr
      });
    }
    if (options.filtering) {
      let filterId = options.filtering.split(",");
      filterId = filterId.map((i) => {
        return parseInt(i);
      });
      this.setData({
        filterId
      });
    }
    if (options.category) {
      this.setData({
        typestring: options.category
      });
    }

    if (options.classificationParentIndex) {
      this.setData({
        classificationParentIndex: parseInt(options.classificationParentIndex),
        activeName: parseInt(options.classificationParentIndex)
      });
    }
    if (options.classificationId1) {
      this.setData({
        classificationId1: parseInt(options.classificationId1)
      });
    }
    if (options.classificationId2) {
      this.setData({
        classificationId2: parseInt(options.classificationId2)
      });
    }

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

    this.getbrand();
    this.getclassification();
    this.getname();
    this.search();
  },
  tapUpper() {
    try {
      wx.navigateBack({
        delta: 1,
        success: (res) => {},
        fail: (res) => {
          wx.reLaunch({
            url: '/packageG/index/index'
          });
        },
        complete: (res) => {},
      });
    } catch (error) {
      wx.reLaunch({
        url: '/packageG/index/index'
      });
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

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

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

  },

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

  },

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

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (!this.data.allLoaded) {
      n++;
      let loading = true;
      this.gotoSearch(n, loading);
    }
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let urlStr = "";

    urlStr += "?keyword=" + this.data.inputs;
    urlStr += "&order_field=" + this.data.order_field;
    urlStr += "&order_by=" + this.data.order_by;
    urlStr += "&coupon=" + this.data.coupon;
    urlStr += "&as_id=" + this.data.zoneId;
    urlStr += "&brand_id=" + this.data.brandId;
    urlStr += "&product_attr=" + this.data.attrstr.toString();
    urlStr += "&filtering=" + this.data.filterId.toString();
    urlStr += "&category=" + this.data.typestring;
    urlStr += "&classificationParentIndex=" + this.data.classificationParentIndex;
    urlStr += "&classificationId1=" + this.data.classificationId1;
    urlStr += "&classificationId2=" + this.data.classificationId2;
    console.log(urlStr);
    return {
      path: "/packageB/member/category/search_v2/search_v2" + urlStr
    };
  },

  // 获取滚动条当前位置
  onPageScroll: function (e) {
    // 节流
    if (e.scrollTop > 80) {
      if (!this.data.btnFlag) {
        this.setData({
          btnFlag: true
        });
      }
    } else {
      if (this.data.btnFlag) {
        this.setData({
          btnFlag: false
        });
      }
    }
  },

  onClose() {
    this.setData({
      show: false
    });
  },

  onChange(event) {
    this.setData({
      activeName: event.detail
    });
  },

  //品牌相关的功能
  getbrand() {
    let that = this;
    let urlStr = app.getNetAddresss("goods.brand.get-brand");
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: {},
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            brand: res.data.data
          });
        }
      },
      fail: function (res) {}
    });
  },
  //分类相关的功能
  getclassification() {
    let that = this;
    let urlStr = app.getNetAddresss("goods.category.search-goods-category");
    app._getNetWork({
      showToastIn: false,
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            classification1: res.data
          });
        }
      },
      fail: function (res) {

      }
    });
  },
  getname() {
    let that = this;
    let urlStr = app.getNetAddresss("goods.filtering.index");
    app._getNetWork({
      showToastIn: false,
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            tagname: res.data
          });
          let tagname = that.data.tagname;
          for (let i = 0; i < tagname.length; i++) {
            for (let y = 0; y < tagname[i].value.length; y++) {
              if (that.data.filterId.includes(tagname[i].value[y].id)) {
                tagname[i].value[y].record = 2;
              } else {
                tagname[i].value[y].record = 1;
              }

            }
          }
          that.setData({
            tagname: tagname
          });
        }
      },
      fail: function (res) {

      }
    });
  },
  search() {
    n = 1;
    this.setData({
      goods: [],
      goload: true
    });
    this.gotoSearch();
  },

  // 点击tag搜索
  serachTag(event) {
    let value = event.detail;
    this.setData({
      inputs: value
    });
    this.search();
  },
  gotoSearch(page = 1, loading = false) {
    // 添加搜索记录
    this.selectComponent("#search_history").appendKeywords(this.data.inputs);
    let that = this;
    let urlStr = "";
    if (this.data.fromPage == '1') {
      urlStr = app.getNetAddresss("plugin.pending-order.frontend.wholesale-area.goods-list");
    } else if(this.options.tmpl && this.options.tmpl == 'dy'){
      urlStr = app.getNetAddresss("plugin.supplier.frontend.category.search-goods");
    }else if(this.options.CommodityRights && this.options.CommodityRights == "CommodityRights"){
      urlStr = app.getNetAddresss("plugin.love-speed-pool.frontend.goods.getList");
    } else {
      urlStr = app.getNetAddresss("goods.goods.search-goods");
    }
    urlStr += "&search[keyword]=" + this.data.inputs;
    urlStr += "&page=" + page;
    urlStr += "&order_field=" + this.data.order_field;
    urlStr += "&order_by=" + this.data.order_by;
    urlStr += "&search[couponid]=" + this.data.coupon;
    urlStr += "&search[as_id]=" + this.data.zoneId;
    urlStr += "&search[brand_id]=" + this.data.brandId;
    urlStr += "&search[product_attr]=" + this.data.attrstr.toString();
    urlStr += "&search[filtering]=" + this.data.filterId.toString();
    urlStr += "&search[category]=" + this.data.typestring;

    if (this.data.plugin_id == 1) {
      // 筛选平台商品
      urlStr += "&search[plugin_id]=0";
    }
    this.setData({
      requestLoading: true
    });
    app._getNetWork({
      showToastIn: false,
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            loading: false,
            allLoaded: false
          });
          // 搜索结果为空
          if (res.data.data.length <= 0) {
            that.setData({
              loading: true,
              allLoaded: true
            });
            return;
          }
          // 如果当前页数大于总页数 就不加载了
          if (res.data.current_page > res.data.last_page) {
            that.setData({
              loading: true,
              allLoaded: true
            });
            return;
          }
          let goods = that.data.goods;
          goods.push(...res.data.data);
          for (let i = 0; i < goods.length; i++) {
            if (parseInt(Number(goods[i].market_price == 0))) {
              goods[i].notMarket_price = 0;
            } else {
              goods[i].notMarket_price = 1;
            }
          }
          that.setData({
            goods: goods,
            requestLoading: false
          });
          try {
            that.setData({
              goods_template: res.data.goods_template
            });
          } catch (err) {
            console.log(err);
          }
          if (!loading) {
            if (that.data.goods_template&&(that.data.goods_template.names == '02' || that.data.goods_template.names == '03')) {
              that.setData({
                showcccc: true,
                classifyBol: false
              });
            }
          }
          if (res.data.data.length < 15) {
            that.setData({
              loading: true,
              allLoaded: true
            });
            return;
          }
        }else{
          that.setData({
            requestLoading: false
          });
        }
      },
      fail: function (res) {

      }
    });
  },
  toggle(e) {
    let idx = e.currentTarget.dataset.idx;
    let order_field = '';
    switch (idx) {
    case 1:
      this.setData({
        hascolor: 1
      });
      if (this.data.colorshow == '1_2') {
        this.setData({
          colorshow: '1_1'
        });
        order_field = 'comment_num';
        this.setData({
          order_field: order_field,
          order_by: 'asc'
        });
      } else {
        this.setData({
          colorshow: '1_2'
        });
        order_field = 'comment_num';
        this.setData({
          order_field: order_field,
          order_by: 'desc'
        });
      }
      break;
    case 2:
      this.setData({
        hascolor: 2
      });
      if (this.data.colorshow == '2_2') {
        this.setData({
          colorshow: '2_1',
        });
        order_field = 'show_sales';
        this.setData({
          order_field: order_field,
          order_by: 'asc'
        });
      } else {
        this.setData({
          colorshow: '2_2',
        });
        order_field = 'show_sales';
        this.setData({
          order_field: order_field,
          order_by: 'desc'
        });
      }
      break;
    case 3:
      this.setData({
        hascolor: 3,
      });
      if (this.data.colorshow == '3_2') {
        this.setData({
          colorshow: '3_1'
        });
        order_field = 'price';
        this.setData({
          order_field: order_field,
          order_by: 'asc'
        });
      } else {
        this.setData({
          colorshow: '3_2'
        });
        order_field = 'price';
        this.setData({
          order_field: order_field,
          order_by: 'desc'
        });
      }
      break;
    }
    if (this.data.goods.length == 0) {
      return;
    }
    n = 1;
    this.setData({
      goods: []
    });
    this.gotoSearch(n);
  },
  classifyBolbtn() {
    if (this.data.showcccc) {
      this.setData({
        showcccc: false,
        classifyBol: true
      });
    } else {
      this.setData({
        showcccc: true,
        classifyBol: false
      });
    }
  },
  inpbtn(e) {
    let val = e.detail.value;
    this.setData({
      inputs: val
    });
  },
  inpbtnclear() {
    this.setData({
      inputs: ''
    });
  },

  showbox() {
    this.setData({
      show: !this.data.show
    });
  },
  changetype(e) {
    let key = e.currentTarget.dataset.key;
    this.setData({
      select: key
    });
    this.resetselect();
    switch (key) {
    case 0:
      this.setData({
        show1: true
      });
      break;
    case 1:
      this.setData({
        show2: true
      });
      break;
    case 2:
      this.setData({
        show3: true
      });
      break;
    case 3:
      this.setData({
        show4: true
      });
      break;
    default:
      break;
    }
  },
  resetselect() {
    this.setData({
      show1: false,
      show2: false,
      show3: false,
      show4: false
    });
  },
  screenbrand(e) {
    let id = e.currentTarget.dataset.id;
    this.setData({
      goods: [],
      brandId: id,
      goload: true,
    });
    this.hidebox();
    this.gotoSearch();
  },
  hidebox() {
    this.setData({
      show: false
    });
  },
  classificationtype(e) {
    let id = e.currentTarget.dataset.id;
    // let key = e.currentTarget.dataset.key;
    this.setData({
      classification2: [],
      typestring: id
    });
    if (this.data.classificationId == id) {
      this.setData({
        classificationId: null
      });
      return;
    } else {
      this.setData({
        classificationId: id
      });
    }
    this.setData({
      classificationId1: null,
      classificationId2: null,
      classificationshow: false
    });
  },
  classificationtype1(e) {
    let id = e.currentTarget.dataset.id;
    // let key = e.currentTarget.dataset.key;
    let parentIndex = e.currentTarget.dataset.parentIndex;

    this.setData({
      typestring: id,
      classificationParentIndex: parentIndex,
      classificationshow: true
    });
    if (this.data.classificationId1 == id) {
      this.setData({
        classificationId1: null
      });
    } else {
      this.setData({
        classificationId1: id
      });
    }

    this.setData({
      classificationId2: null
    });
  },
  classificationtype2(e) {
    let id = e.currentTarget.dataset.id;
    // let key = e.currentTarget.dataset.key;
    if (this.data.typestring == id) {
      this.setData({
        typestring: null
      });
    } else {
      this.setData({
        typestring: id
      });
    }

    if (this.data.classificationId2 == id) {
      this.setData({
        classificationId2: null
      });
    } else {
      this.setData({
        classificationId2: id
      });
    }
  },
  selectattr(e) {
    let key = e.currentTarget.dataset.key;
    console.log(key);
    //属性选择项
    switch (key) {
    case 0:
      this.findstr("is_recommand", key);
      break;
    case 1:
      this.findstr("is_new", key);
      break;
    case 2:
      this.findstr("is_hot", key);
      break;
    case 3:
      this.findstr("is_discount", key);
      break;
    case 4:
      this.findstr("limit_buy", key);
      break;
    }
    if (this.data.attr[key].show) {
      this.setData({
        ['attr[' + key + '].show']: false
      });
    } else {
      this.setData({
        ['attr[' + key + '].show']: true
      });
    }
  },
  //属性相关的功能
  findstr(attrstr, key) {
    let index = this.data.attrstr.indexOf(attrstr);
    if (index + 1) {
      let attrstrD = this.data.attrstr;
      attrstrD.splice(index, 1);
      this.setData({
        attrstr: attrstrD
      });
    } else {
      let attrstrD = this.data.attrstr;
      attrstrD.push(attrstr);
      this.setData({
        attrstr: attrstrD
      });
    }

    let index1 = this.data.attrkey.indexOf(key);
    if (index1 + 1) {
      let attrkey = this.data.attrkey;
      attrkey.splice(index1, 1);
      this.setData({
        attrkey: attrkey
      });
    } else {
      let attrkey = this.data.attrkey;
      attrkey.push(key);
      this.setData({
        attrkey: attrkey
      });
    }
  },
  //标签组相关功能
  showtagname(e) {
    let key = e.currentTarget.dataset.key;
    if (key == this.data.showtagnamekey) {
      this.setData({
        showtagnamekey: null
      });
      return;
    } else {
      this.setData({
        showtagnamekey: key
      });
    }
  },
  selectname(e) {
    let id = e.currentTarget.dataset.id;
    let key1 = e.currentTarget.dataset.key;
    let key2 = e.currentTarget.dataset.keyx;

    if (this.data.tagname[key1].value[key2].record == 1) {
      if (this.data.filterId.includes(id)) {
        return;
      } else {
        let filterId = this.data.filterId;
        filterId.push(id);
        this.setData({
          filterId: filterId
        });
      }
      this.setData({
        ['tagname.[' + key1 + '].value[' + key2 + '].record']: 2
      });
    } else {
      let index = this.data.filterId.indexOf(id);
      let filterId = this.data.filterId;
      filterId.splice(index, 1);
      this.setData({
        filterId: filterId
      });
      this.setData({
        ['tagname.[' + key1 + '].value[' + key2 + '].record']: 1
      });
    }
  },
  resetnames() {
    this.setData({
      namestring: null,
      showtagnamekey: null,
      namekey: null,
      brandId: "",
      attrstr: [],
      filterId: [],
      typestring: "",
      attr: [{
        name: "推荐商品",
        show: true
      },

      {
        name: "新品上市",
        show: true
      },

      {
        name: "热卖商品",
        show: true
      },

      {
        name: "促销商品",
        show: true
      },

      {
        name: "限时抢购",
        show: true
      }
      ],
      classificationkey: null,
      classificationkey1: null,
      classificationkey2: null
    });
    for (let i = 0; i < this.data.tagname.length; i++) {
      for (let y = 0; y < this.data.tagname[i].value.length; y++) {
        if (this.data.tagname[i].value[y].record == 2) {
          this.setData({
            ['tagname.[' + i + '].value[' + y + '].record']: 1
          });
        }
      }
    }
  },
  screen() {
    this.setData({
      goods: [],
      goload: true
    });
    this.hidebox();
    this.gotoSearch();
  },

  focusSearchInput() {
    this.setData({
      showHistory: true
    });
  },
  blurSerachInput() {
    this.setData({
      showHistory: false
    });
  },
  searchBlur() {
    this.setData({
      showHistory: false
    });
  },
  searchfocus() {
    this.setData({
      showHistory: true
    });
  },
  async getNowPackageDeliver() {
    //获取自提点信息
    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.search();
      }
      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();
      });
    });
  }
});
