// components/store_popup.js
var e = getApp(),
  a = e.globalData.setting,
  os = a
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    store: {
      type: Number,
      value: 0
    }
  },
  lifetimes: {
    attached: function () {
      // 在组件实例进入页面节点树时执行
      this.init()
    },
    detached: function () {
      // 在组件实例被从页面节点树移除时执行
    },
  },
  /**
   * 组件的初始数据
   */
  data: {
    //门店相关
    ismend: 0,
    is_sec_mend: 0,
    sto_sele_name: "", //选中的门店名称
    sto_sele_id: "", //选中的门店id
    sto_sele_distr: "", //选择的门店的配送方式
    is_show_sto_cat: 1, //是否显示门店分类
    only_pk: null,
    all_sto: null,
    sec_sto: null, //选择了的门店分类
    pickpu_list: null, //读出的所有门店list
    def_pickpu_list: null, //一开始5个门店list
    sec_pick_index: 0, //第二级门店选择ID
    fir_pick_index: 0, //第一级门店选择ID
    all_pick_list: null,//所有的门店先记录起来

    select_store: 0, //选择更多
    index: 1,
    more_store: 0, //选择门店
    sort_store: 0, //门店分类
    choice_sort_store: 0, //选择分类门店
    new_user: 0, //新用户

    def_pick_store: null, // 默认的门店
    fir_def_store: null,  //客户默认的门店的
    lat: null, //维度
    lon: null, //经度

    is_get_local_ok: 0, //获取坐标是否完成
    region_name: "门店分类", //区域的名字
    is_gps: 1,
    open_ind_store: 0, //哪里打开的门店列表的控制属性
    default_store: {}, //创建添加默认门店地址的对象


    openSpecModal: 0,

    is_get_guide: 0,
    keyword: '', //门店搜索
    sec_i: -1,//选中分类门店 下标
    old_all_sto:null, //分类门店数据
  },

  /**
   * 组件的方法列表 
   */
  methods: {
    init() {
      getApp().getConfig2((e) => {
        this.setData({
          bconfig: e,
        });
      })
      this.wait_for_store_config()
      this.set_user_mo_store(() => {
        this.get_sto()
      })
    },
    //开启定位
    wait_for_store_config: function () {
      let th = this
      var t_time = setInterval(function () {
        if (th.data.bconfig == null) false;
        var e = th.data.bconfig;
        if (e && e.is_sort_storage) {
          wx.getLocation({
            type: 'gcj02',
            success: function (res) {
              th.data.lat = res.latitude;
              th.data.lon = res.longitude;
              th.data.is_get_local_ok = 1;
            },
            fail: function (res) {
              if (res.errCode == 2) {
                th.setData({
                  is_gps: 0
                });
                if (th.data.is_gps == 0) {
                  getApp().confirmBox("请开启GPS定位", null, 10000, !1);
                }

              } else {
                th.setData({
                  is_gps: "3"
                });
              }

              th.data.is_get_local_ok = 1;
            }
          })
        } else {
          th.data.is_get_local_ok = 1;
        }
        clearInterval(t_time);
      }, 500)
    },
    set_user_mo_store(func) {
      let th = this;
      let that = th;

      //获取用户的默认门店
      getApp().get_user_store(function (e) {
        if (!e) {
          th.data.fir_def_store = {}; //赋值空对象
          if (func) func();
          return false;
        }

        if (getApp().globalData.is_dj_pk) th.setData({ has_def: 1 })

        var ee = JSON.parse(JSON.stringify(e));
        //--定时器推迟一下--
        setTimeout(function () {
          if (th.data.fir_goods) var g_distr_type = th.data.fir_goods.distr_type;
          //--如果默认门店的配送方式不对，就不能被选择，这里不控制，如果不一样，就说明配送方式不对--
          if (ee.distr_type != 0 && g_distr_type != 0 && ee.distr_type != g_distr_type) {
            ee.is_no_dis = 1;
          }

          var appd = getApp().globalData;
          var w_time = setInterval(function () {
            if (that.data.is_get_local_ok == 0) return false;
            clearInterval(w_time);
            var distance = null;
            var e = JSON.parse(JSON.stringify(ee));

            //如果有开启近距离的话,同时距离优不一样了
            if (that.data.lat != null) {
              //如果经纬度有变化的话
              if (e && appd.lat == that.data.lat && appd.lon == that.data.lon && e.distance > 0) {
                that.set_def_storage(e);
                if (func) func();
              } else {
                //要用接口是获取距离，js的计算不准
                getApp().request.promiseGet("/api/weshop/pickup/list", {
                  data: {
                    store_id: os.stoid,
                    pickup_id: e.pickup_id,
                    lat: th.data.lat,
                    lon: th.data.lon,
                    isstop: 0,
                    is_pos: 1
                  },
                }).then(res => {
                  if (res.data.code == 0) {
                    e = res.data.data.pageData[0];
                    if (e) {
                      e.is_no_dis = ee.is_no_dis;
                      appd.pk_store = e;
                      that.set_def_storage(e);
                    }

                  }
                  if (func) func();
                })
              }
              //e.distance = distance;
              appd.lat = that.data.lat;
              appd.lon = that.data.lon;

            } else {
              if (e) {
                e.distance = null;
                that.set_def_storage(e);
              }
              if (func) func();
            }
          }, 500)
        }, 700)
      })

    },
    //--- 设置一下默认库存的数量 ----
    set_def_storage(ee) {
      var that = this, th = this;
      that.data.fir_def_store = ee;
      that.setData({
        def_pick_store: ee,
        sto_sele_name: ee.pickup_name,
        sto_sele_id: ee.pickup_id,
        sto_sele_distr: ee.distr_type
      })
    },
    //---------拿出门店分类和门店------------
    get_sto() {
      let th = this
      var that = th;
      var self = this;
      var timer_get = setInterval(function () {
        if (th.data.is_get_local_ok == 0) return false;
        var dd = null;

        dd = {
          store_id: os.stoid,
          isstop: 0,
          is_pos: 1,
          pageSize: 2000,
        }

        //如果有距离的话
        if (th.data.lat != null) {
          dd.lat = th.data.lat;
          dd.lon = th.data.lon;
        }

        if (th.data.sele_g && th.data.sele_g.pickup_list) {
          dd.ids = th.data.sele_g.pickup_list
        }

        clearInterval(timer_get);

        //如果会员是有默认的门店话
        if (!th.data.def_pick_store && th.data.fir_def_store) {
          th.setData({ def_pick_store: th.data.fir_def_store });
        }
        wx.showLoading({
          title: '加载中.'
        });
        //----------获取门店----------------
        getApp().request.promiseGet("/api/weshop/pickup/list", {
          data: dd,
        }).then(res => {
          var e = res;
          wx.hideLoading()
          if (e.data.code == 0 && e.data.data && e.data.data.pageData && e.data.data.pageData.length > 0) {

            var his_cate_num = 0;
            for (let i in e.data.data.pageData) {
              let item = e.data.data.pageData[i];
              if (item.category_id > 0) {
                his_cate_num = 1;
                break;
              }
            }
            e.his_cate_num = his_cate_num;

            //如果有开启距离的功能，没有设置默认门店，要用最近的门店作为默认门店
            if (dd.lat && (!th.data.def_pick_store || JSON.stringify(th.data.def_pick_store) == '{}') && th.data.bconfig && th.data.bconfig.is_sort_storage) {
              th.setData({
                def_pick_store: e.data.data.pageData[0],
                sto_sele_name: e.data.data.pageData[0].pickup_name,
                sto_sele_id: e.data.data.pageData[0].pickup_id,
                sto_sele_distr: e.data.data.pageData[0].distr_type
              });
              th.data.fir_def_store = e.data.data.pageData[0];
            }

            //-- 如果有默认选择门店的时候，要把默认门店放在第一位，修改不要配送方式的判断 --
            if (th.data.def_pick_store && JSON.stringify(th.data.def_pick_store) != '{}') {
              for (var k = 0; k < e.data.data.pageData.length; k++) {
                if (e.data.data.pageData[k].pickup_id == th.data.def_pick_store.pickup_id) {
                  e.data.data.pageData.splice(k, 1); //删除
                  break;
                }
              }
              e.data.data.pageData.splice(0, 0, th.data.def_pick_store); //添加
            }

            th.setData({ all_pick_list: e.data.data.pageData });

            setTimeout(function () {

              self.deal_pickup(e, th, os);  //--普通门店排版--
            }, 800)

          }
        })
      }, 200)

    },
    //---点击二级之后的选择---
    choose_for_store: function (e) {
      var index_c = e.currentTarget.dataset.ind;
      var th = this;
      th.setData({
          sec_pick_index: index_c,
          fir_pick_index: index_c
      })

  },
    choose_for_store_fir: function (e) {
      console.log(e);
      var index_c = e.currentTarget.dataset.ind;
      var th = this;
      th.setData({
        fir_pick_index: index_c
      })

    },
    close_popup() {
      this.triggerEvent('closeback',{})
      this.setData({
        store: 0,
        keyword:''
      })
  
    },
    //选择更多门店
    more_store: function () {
      this.setData({
        sort_store: 1
      });
    },
    // 返回按钮
    returns: function () {
      this.setData({
        sort_store: 0,
        choice_sort_store: 0
      });
    },
    //---选择分类门店---
    choice_sort_store: function (e) {
      var index = e.currentTarget.dataset.index;
      var region_name = e.currentTarget.dataset.region;
      var item = this.data.all_sto[index];
      this.setData({
        region_name: region_name,
        sort_store: 0,
        choice_sort_store: 1,
        sec_i: index,
        sec_sto: item,
        sec_pick_index: 0
      });
    },
    //------------处理门店---------------
    deal_pickup(e, th, os) {
      // if (!th.data.sele_g) return false
      wx.hideLoading();
      //单总量超出10个的时候，同时门店有分类
      if (e.data.data.total > 10 && e.his_cate_num) {
        getApp().request.get("/api/weshop/storagecategory/page", {
          data: {
            store_id: os.stoid,
            pageSize: 1000,
            orderField: "sort",
            orderType: 'asc',
          },
          success: function (ee) {
            if (ee.data.code == 0) {
              var check_all_cate = 0;
              if (ee.data.data && ee.data.data.pageData && ee.data.data.pageData.length > 0) {
                for (let i in ee.data.data.pageData) {
                  let item = ee.data.data.pageData[i];
                  if (item.is_show == 1) {
                    check_all_cate = 1;
                    break
                  }
                }
              }
              if (check_all_cate) {
                var sto_cate = ee.data.data.pageData;
                var sto_arr = e.data.data.pageData;
                var newarr = new Array();
                var qita = new Array();


                var is_del_pk = 0;
                //----要进行门店分组--------
                for (var i = 0; i < sto_arr.length; i++) {
                  //找一下这个门店有没有在分类数组内
                  var find2 = 0, find2name = "", sort = 0;
                  is_del_pk = 0;
                  for (var m = 0; m < sto_cate.length; m++) {
                    if (sto_arr[i].category_id == sto_cate[m].cat_id) {
                      if (sto_cate[m].is_show != 1) {
                        is_del_pk = 1;
                        sto_arr.splice(i, 1);
                        i--;
                      } else {
                        find2 = sto_cate[m].cat_id;
                        find2name = sto_cate[m].cat_name;
                        sort = sto_cate[m].sort;
                        is_del_pk = 0;
                      }
                      break;
                    }
                  }
                  if (is_del_pk) continue;

                  if (newarr.length > 0) {
                    var find = 0;
                    //如果有找到，那门店就在这个分组内，否则，分类就要排在其他
                    if (find2 != 0) {
                      for (var ii = 0; ii < newarr.length; ii++) {
                        if (sto_arr[i].category_id == newarr[ii].cat_id) {
                          newarr[ii].s_arr.push(sto_arr[i]);
                          find = 1;
                          break;
                        }
                      }
                      if (find == 0) {
                        var arr0 = new Array();
                        arr0.push(sto_arr[i]);
                        var item = {
                          cat_id: find2,
                          name: find2name,
                          sort: sort,
                          s_arr: arr0
                        };
                        newarr.push(item);
                      }
                    } else {
                      qita.push(sto_arr[i]);
                    }
                  } else {
                    //如果有找到，那门店就在这个分组内，否则，分类就要排在其他
                    if (find2 != 0) {
                      var arr0 = new Array();
                      arr0.push(sto_arr[i]);
                      var item = {
                        cat_id: find2,
                        name: find2name,
                        sort: sort,
                        s_arr: arr0
                      };
                      newarr.push(item);
                    } else {
                      qita.push(sto_arr[i]);
                    }
                  }
                }

                var def_arr = new Array();
                //-- 开始就看10个门店 --
                for (var k = 0; k < 10; k++) {
                  if (k == sto_arr.length) break;
                  def_arr.push(sto_arr[k]);
                }

                th.setData({
                  def_pickpu_list: def_arr,
                  pickpu_list: ee.data.data.pageData
                });


                //门店分类要排序下
                function compare(property) {
                  return function (a, b) {
                    var value1 = a[property];
                    var value2 = b[property];
                    return value1 - value2;
                  }
                }

                if (newarr.length > 0)
                  newarr.sort(compare("sort"));


                //----安排其他的分类-----
                if (qita.length > 0) {
                  var item = {
                    cat_id: -1,
                    name: "其他",
                    s_arr: qita
                  };
                  newarr.push(item);
                }

                var sd = {
                  all_sto: newarr,
                  is_show_sto_cat: 1
                }
                if (!sto_arr || sto_arr.length <= 10) {
                  sd.is_show_sto_cat = -1;
                  sd.only_pk = sto_arr;
                }
                th.setData(sd);

              } else {
                th.setData({
                  is_show_sto_cat: -1,
                  only_pk: e.data.data.pageData
                });
                //-----如果没有默认门店，要取第一个门店作为默认店.此时没有门店分类的情况------
                if (!th.data.def_pick_store) {
                  th.setData({
                    def_pick_store: e.data.data.pageData[0],
                    sto_sele_name: e.data.data.pageData[0].pickup_name,
                    sto_sele_id: e.data.data.pageData[0].pickup_id,
                    sto_sele_distr: e.data.data.pageData[0].distr_type
                  })
                }
              }
            } else {
              th.setData({
                is_show_sto_cat: -1,
                only_pk: e.data.data.pageData
              });
              //-----如果没有默认门店，要取第一个门店作为默认店.此时没有门店分类的情况------
              if (!th.data.def_pick_store) {
                th.setData({
                  def_pick_store: e.data.data.pageData[0],
                  sto_sele_name: e.data.data.pageData[0].pickup_name,
                  sto_sele_id: e.data.data.pageData[0].pickup_id,
                  sto_sele_distr: e.data.data.pageData[0].distr_type
                })
              }

            }
          }
        });
      } else {
        th.setData({
          is_show_sto_cat: 0,
          only_pk: e.data.data.pageData
        });
        //-----如果没有默认门店，要取第一个门店作为默认店------
        if (!th.data.def_pick_store && th.data.bconfig && th.data.bconfig.is_sort_storage) {
          th.setData({
            def_pick_store: e.data.data.pageData[0],
            sto_sele_name: e.data.data.pageData[0].pickup_name,
            sto_sele_id: e.data.data.pageData[0].pickup_id,
            sto_sele_distr: e.data.data.pageData[0].distr_type
          })
        }
      }
    },

    check_def_pk: function () {
      let th = this
      th.data.def_pick_store.is_no_dis = 0;
      var def_pick_store = th.data.def_pick_store
      var sele_g = th.data.sele_g;
      var arr = sele_g.pickup_list.split(',');

      var idx = arr.findIndex(function (e) {
        return e == def_pick_store.pickup_id;
      })

      if (idx == -1) {
        def_pick_store.is_no_dis = 1;
      }
      th.setData({ def_pick_store })

    },
    //获取搜索门店输入的值
    input_store: function (e) {
      this.setData({
        keyword: e.detail.value
      })
    },
    //搜索门店
    searchfn() {
      let choice_sort_store = this.data.choice_sort_store
      if (choice_sort_store == 0) {  //全局搜索
        let all_pick_list = this.data.all_pick_list
        let def_pickpu_list = this.data.def_pickpu_list
        let keyword = this.data.keyword
        if (keyword) {
          let arr = all_pick_list.filter(item => {
            let i = item.pickup_name.indexOf(keyword)
            if (i > -1) {
              return true
            } else {
              return false
            }
          })
          if (arr && arr.length > 0) {
            if (this.data.is_show_sto_cat == 1) {
              this.setData({
                def_pickpu_list: arr
              })
            } else {
              this.setData({
                only_pk: arr
              })
            }
          } else {
            wx.showToast({
              title: '没有搜索到门店',
              icon: 'none',
              duration: 2000
            })
          }
        } else {
          if (this.data.is_show_sto_cat == 1) {
            this.setData({
              def_pickpu_list: all_pick_list.slice(0, 10)
            })
          } else {
            this.setData({
              only_pk: all_pick_list
            })
          }

        }
      } else {   //分类下搜索
        let sec_i = this.data.sec_i
        let all_sto = this.data.all_sto
        let old_all_sto = this.data.old_all_sto
        if (!old_all_sto) {
          this.setData({
            old_all_sto:JSON.parse(JSON.stringify(all_sto))
          })
        }
        let sec_sto = this.data.sec_sto
        let sec_arr = this.data.old_all_sto[sec_i].s_arr
        let keyword = this.data.keyword
        let text = 'sec_sto.s_arr'
        if (keyword) {
          let arr = sec_arr.filter(item => {
            let i = item.pickup_name.indexOf(keyword)
            if (i > -1) {
              return true
            } else {
              return false
            }
          })
          if (arr && arr.length > 0) {
            this.setData({
              [text]: arr
            })
          } else {
            wx.showToast({
              title: '没有搜索到门店',
              icon: 'none',
              duration: 2000
            })
          }
        } else {
          if (this.data.old_all_sto) {          
            this.setData({
              [text]: this.data.old_all_sto[sec_i].s_arr
            })
          }else{
            this.setData({
              [text]: all_sto[sec_i].s_arr
            })
          }
        }


      }
    },
    //确定def_pick为选择的门店
    sure_pick: function (e) {
      
      var th = this;
      var item = null;
      var openindstore = th.data.open_ind_store;
      if (th.data.choice_sort_store == 0) {
        var index = th.data.fir_pick_index;
        if (th.data.is_show_sto_cat == 1) {
          item = th.data.def_pickpu_list[index];
        } else {
          item = th.data.only_pk ? th.data.only_pk[index] : null; //当没有门店分类的时候
        }
      } else {
        var index = th.data.sec_pick_index;
        item = th.data.sec_sto.s_arr[index];
      }

      if (!item) return false;

      // if (!th.data.sele_g) return false;



      this.triggerEvent('callback', item)

      th.setData({
        def_pick_store: item,
        sto_sele_name: item.pickup_name,
        sto_sele_id: item.pickup_id,
        sto_sele_distr: item.distr_type,
        store: 0,
        choice_sort_store: 0,
        fir_pick_index: 0,
        openSpecModal: !0,
      });


    },
  }
})
