// packageE/stores/stores.js
var location = require("../../../mybehaviors/location/location");
var app = getApp();
Component({
  behaviors: [location],
  properties: {
    datas: {
      type: null,
    },
    component_id: {
      type: null,
    },
    U_tabcontrol: {
      type: null,
    },
    btnFlag: {
      type: null,
    },
    bottomShowBolIndex: {
      type: null,
    },
    index: {
      type: null,
    },
    plugin_active: String,
  },
  // 私有数据，可用于模板渲染
  data: {
    emptyImage: "https://mini-app-img-1251768088.cos.ap-guangzhou.myqcloud.com/image.png",
    clientWidth: "375",
    active: "0",

    titleName: [
      {
        id: "business_merchant",
        text: "商家",
        url: "plugin.store-cashier.frontend.store.store.get-store-list-to-page",
      },
      {
        id: "business_discount",
        text: "折扣",
        url: "plugin.universal-card.frontend.store-discount.store-data",
      },
      {
        id: "business_coupon",
        text: "优惠券",
        url: "plugin.store-cashier.frontend.store.aggregate-page.coupon",
      },
      {
        id: "business_goods_gift",
        text: "礼包",
        url: "plugin.store-cashier.frontend.store.aggregate-page.goods-gift",
      },
    ],
    api: "",
    dataJson: {},
    pd_classfy_arr: [],
    pd_date_arr: [],
    //折扣的index
    pd_index: 0,
    pd_date_index: 0,
    //商家数组和分页数据
    shopList0: [],
    isLoadMore0: false,
    page0: 1,
    total_page0: 0,
    //折扣数组和分页数据
    shopList1: [],
    isLoadMore1: false,
    page1: 1,
    total_page1: 0,
    //优惠券数组和分页数据
    shopList2: [],
    isLoadMore2: false,
    page2: 1,
    total_page2: 0,
    //礼包数组和分页数据
    shopList3: [],
    isLoadMore3: false,
    page3: 1,
    total_page3: 0,
    pd_date: {},
    showMun: true,

    openTemplate: 0, //门店列表样式
    datas_style02: {
      "get_number": 999,
      "preview_color": "#f5f5f5",
      "font_size": 14,
      "font_color": "#666666",
      "border_radius": 35,
      "class_font_size": 12,
      "class_font_color": "#f08316",
      "class_bg_color": "#fff",
      "class_border_radius": 5,
      "location_font_size": 14,
      "location_font_color": "#666666",
      "discount_font_size": 10,
      "discount_title_color": "#ffffff",
      "discount_font_color": "#666666",
      "discount_list": [
        "1",
        "2",
        "3",
        "4"
      ],
      "tag_font_size": 10,
      "tag_font_color": "#fff",
      "tag_bg_color": "#f08316",
      "tag_border_color": "#f08316",
      "tag_border_radius": 5,
      "show_goods": true,
      "tab_list": [],
      "tab_bg_color": "#ffffff",
      "tab_color": "#333333",
      "tab_active_color": "#ff8400"
    } //门店列表样式
  },

  lifetimes: {
    // 生命周期函数，可以为函数，或一个在methods段中定义的方法名
    attached() {
      let language = wx.getStorageSync("langIndex");
      this.setData({
        language: language.en,
      });
    },
    moved() {},
    detached() {},
  },

  // 生命周期函数，可以为函数，或一个在methods段中定义的方法名
  attached() {},
  // 此处attached的声明会被lifetimes字段中的声明覆盖
  ready() {
    if (this.data.datas.discount_list.indexOf("1") > -1) {
      this.setData({
        showMun: true,
      });
    } else if (this.data.datas.discount_list.indexOf("1") < 0) {
      this.setData({
        showMun: false,
      });
    }
    this.setData({
      clientWidth: wx.getSystemInfoSync().windowWidth,
    });
    this._getLocation((res) => {
      console.log(res)
      if (this.data.U_tabcontrol) {
        this.chooseTab(" ", "business_merchant");
      } else {
        if (this.data.datas.tab_list.indexOf("1") > -1) {
          this.chooseTab(" ", "business_merchant");
        } else if (this.data.datas.tab_list.indexOf("2") > -1) {
          this.chooseTab(" ", "business_discount");
        } else if (this.data.datas.tab_list.indexOf("3") > -1) {
          this.chooseTab(" ", "business_coupon");
        } else if (this.data.datas.tab_list.indexOf("4") > -1) {
          this.chooseTab(" ", "business_goods_gift");
        }
      }
    },(err)=>{
      //拒绝定位
      if (this.data.U_tabcontrol) {
        this.chooseTab(" ", "business_merchant");
      } else {
        if (this.data.datas.tab_list.indexOf("1") > -1) {
          this.chooseTab(" ", "business_merchant");
        } else if (this.data.datas.tab_list.indexOf("2") > -1) {
          this.chooseTab(" ", "business_discount");
        } else if (this.data.datas.tab_list.indexOf("3") > -1) {
          this.chooseTab(" ", "business_coupon");
        } else if (this.data.datas.tab_list.indexOf("4") > -1) {
          this.chooseTab(" ", "business_goods_gift");
        }
      }
    });
    console.log(wx.getStorageSync("address-point"),'sssssssssssssss')
  },

  pageLifetimes: {
    // 组件所在页面的生命周期函数
    show() {},
    hide() {},
    resize() {},
  },
  methods: {
    // 跳转到店铺
    toRouter(e) {
      let item = e.currentTarget.dataset.item;
      if (item.specify_show == 1) {
        wx.navigateTo({
          url: "/packageC/o2o/o2oStore/o2oStore?store_id=" + item.id + "&fromHome=1",
        });
      } else {
        if (item.store_decorate == 1) {
          wx.navigateTo({
            url: "/packageG/o2o/HomeSeller/HomeSeller?store_id=" + item.id,
          });
        } else {
          wx.navigateTo({
            url: "/packageC/o2o/HomeSeller/HomeSeller?store_id=" + item.id,
          });
        }
      }
    },
    toClassify(e) {
      let id = e.currentTarget.dataset.id;
      wx.navigateTo({
        url: "/packageC/o2o/o2oCategory/o2oCategory?id=" + id + "&city=" + this.data.city + "&point=" + JSON.stringify(this.data.point),
      });
    },
    
    toGoods(e) {
      let item = e.currentTarget.dataset.item;
      wx.navigateTo({
        url: "/packageA/detail_v2/detail_v2?id=" + item.goods_id,
      });
    },
    //特权折扣--搜索--门店分类
    pdClassfySearch(e) {
      let index = e.currentTarget.dataset.index;
      let id = e.currentTarget.dataset.id;
      //1.改变选中状态
      this.setData({
        pd_index: index,
      });
      //2.修改搜索参数--门店分类
      this.setData({
        pd_category_id: id,
      });
      //3.初始化分页数据
      this.pdInitData();
      //4.执行搜索返回数据（带上日期的搜索值）
      this.getPdData();
    },
    //特权折扣--分页
    pdInitData() {
      this.setData({
        isLoadMore1: false,
        page1: 1,
        total_page1: 0,
        shopList1: [],
      });
    },
    //特权折扣--搜索--日期
    pdDateSearch(e) {
      let index = e.currentTarget.dataset.index;
      let date = e.currentTarget.dataset.date;
      //1.改变选中状态
      this.setData({
        pd_date_index: index,
      });
      //2.修改搜索参数--日期
      this.setData({
        pd_date: date,
      });
      //3.初始化分页数据
      this.pdInitData();
      //4.执行搜索返回数据（带上门店分类的搜索值）
      this.getPdData();
    },
    //领取优惠券
    getCoupon(e) {
      let id = e.currentTarget.dataset.id;
      let urlStr = app.getNetAddresss("plugin.store-cashier.frontend.store.coupon-get");
      app._getNetWork({
        url: urlStr,
        data: {
          coupon_id: id,
        },
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            wx.showModal({
              title: "提示",
              content: "领取成功",
              showCancel: false,
              success(res) {},
            });
          } else {
            wx.showToast({
              title: res.msg,
              icon: "none",
              duration: 1500,
            });
          }
        },
        fail: function (res) {
          console.log(res);
        },
      });
    },
    //跳转至门店首页
    gotoShop(e) {
      let id = e.currentTarget.dataset.id;
      wx.navigateTo({
        url: "/packageC/o2o/o2oStore/o2oStore?store_id=" + id,
      });
    },
    // 打开地图
    goToAdress(e) {
      let latitude = e.currentTarget.dataset.items.latitude;
      let longitude = e.currentTarget.dataset.items.longitude;
      let store_name = e.currentTarget.dataset.items.store_name;
      let point = app.BMapTransqqMap(parseFloat(longitude), parseFloat(latitude));
      wx.openLocation({
        latitude: point.lat,
        longitude: point.lng,
        scale: 18,
        name: store_name,
      });
    },
    getMoreList() {
      let that = this;
      let point;
      //获取更多数据
      this.setData({
        [`isLoadMore${this.data.tab}`]: false,
      });
      if (this.data[`page${this.data.tab}`] >= this.data[`total_page${this.data.tab}`]) {
        return;
      } else {
        this.data[`page${this.data.tab}`] = this.data[`page${this.data.tab}`] + 1;
        switch (this.data.tab) {
        case 0:
          point = app.qqMapTransBMap(parseFloat(this.data.point.lng), parseFloat(this.data.point.lat));
          this.setData({
            dataJson: {
              lng: point.lng ? point.lng : "",
              lat: point.lat ? point.lat : "",
              city_name: this.data.city,
              page: this.data.page0,
            },
          });
          break;
        case 2:
          this.setData({
            dataJson: {
              page: this.data.page2,
            },
          });
          break;
        case 3:
          this.setData({
            dataJson: {
              page: this.data.page3,
            },
          });
          break;
        }
        let urlStr = app.getNetAddresss(that.data.api);
        app._getNetWork({
          url: urlStr,
          data: that.data.dataJson,
          success: function (resdata) {
            var res = resdata.data;
            if (res.result == 1) {
              if (that.data.tab !== 1) {
                that.setData({
                  [`shopList${that.data.tab}`]: that.data[`shopList${that.data.tab}`].concat(res.data.data),
                  [`total_page${that.data.tab}`]: res.data.last_page,
                });
              }
              if (that.data[`page${that.data.tab}`] >= that.data[`total_page${that.data.tab}`]) {
                that.setData({
                  [`isLoadMore${that.data.tab}`]: false,
                });
              } else {
                that.setData({
                  [`isLoadMore${that.data.tab}`]: true,
                });
              }

              if (that.data.tab == 0) {
                if (that.data[`shopList${that.data.tab}`].length > that.data.datas.get_number) {
                  that.data[`shopList${that.data.tab}`].splice(that.data.datas.get_number, that.data[`shopList${that.data.tab}`].length - that.data.datas.get_number);
                  console.log(that.data[`shopList${that.data.tab}`],'aaaaaaaaa')
                  that.setData({
                    [`shopList${that.data.tab}`]: that.data[`shopList${that.data.tab}`],
                    [`isLoadMore${that.data.tab}`]: false,
                  });
                }
              }
              that.triggerEvent("setLoadMore", {
                isLoadMore: that.data[`isLoadMore${that.data.tab}`],
              });
              // console.log(that.data.shopList0)
            } else {
              that.setData({
                [`page${that.data.tab}`]: [`page${that.data.tab}`] - 1,
                [`isLoadMore${that.data.tab}`]: false,
              });
            }
          },
          fail: function (res) {
            console.log(res);
          },
        });
      }
    },
    onClick(e) {
      if (e.detail.title == "商家") {
        this.setData({
          active: 0,
        });
        this.chooseTab("", "business_merchant");
      } else if (e.detail.title == "折扣") {
        this.setData({
          active: 1,
        });
        this.chooseTab("", "business_discount");
      } else if (e.detail.title == "优惠券") {
        this.setData({
          active: 2,
        });
        this.chooseTab("", "business_coupon");
      } else if (e.detail.title == "礼包") {
        this.setData({
          active: 3,
        });
        this.chooseTab("", "business_goods_gift");
      }
    },
    chooseTab(key, index) {
      // 找到对应的索引
      function pFn(p) {
        return p.id == index;
      }
      this.setData({
        tab: this.data.titleName.findIndex(pFn),
      });
      console.log(this.data.tab, this.data.titleName, "this.data.titleName");
      this.setData({
        api: this.data.titleName[this.data.tab].url,
      });
      let type = this.data.titleName[this.data.tab].id;
      this.setData({
        [`isLoadMore${this.data.tab}`]: false,
        [`total_page${this.data.tab}`]: 0,
        [`page${this.data.tab}`]: 1,
      });
      if (type === "business_merchant") {
        let point = app.qqMapTransBMap(parseFloat(this.data.point.lng), parseFloat(this.data.point.lat));
        this.setData({
          dataJson: {
            lng: point.lng ? point.lng : "",
            lat: point.lat ? point.lat : "",
            city_name: this.data.city,
            page: this.data.page0,
          },
        });
      } else {
        switch (type) {
        case "business_discount":
          this.setData({
            dataJson: {
              page: this.data.page1,
            },
          });
          break;
        case "business_coupon":
          this.setData({
            dataJson: {
              page: this.data.page2,
            },
          });
          break;
        case "business_goods_gift":
          this.setData({
            dataJson: {
              page: this.data.page3,
            },
          });
          break;
        }
      }
      this.getList();
    },
    getList() {
      let that = this;
      // console.log(this.data.api,"api")
      let urlStr = app.getNetAddresss(that.data.api);
      app._getNetWork({
        url: urlStr,
        data: this.data.dataJson,
        success: (resdata) => {
          var res = resdata.data;
          if (res.result == 1) {
            if (that.data.tab === 1) {
              that.setData({
                pd_classfy_arr: res.data.store_category,
                pd_date_arr: res.data.date_time,
              });
              //赋初值日期和门店分类id
              that.setData({
                pd_category_id: res.data.store_category[0].id,
                pd_date: res.data.date_time[0],
              });
              that.getPdData();
            } else {
              that.setData({
                [`shopList${that.data.tab}`]: res.data.data,
                [`total_page${that.data.tab}`]: res.data.last_page,
              });
            }
            if (that.data[`total_page${that.data.tab}`] <= 1) {
              that.setData({
                [`isLoadMore${that.data.tab}`]: false,
              });
            } else {
              that.setData({
                [`isLoadMore${that.data.tab}`]: true,
              });
            }

            if (that.data.tab == 0) {
              if (that.data[`shopList${that.data.tab}`].length > that.data.datas.get_number) {
                that.data[`shopList${that.data.tab}`].splice(that.data.datas.get_number, that.data[`shopList${that.data.tab}`].length - that.data.datas.get_number);
                that.setData({
                  [`shopList${that.data.tab}`]: res.data.data,
                  [`isLoadMore${that.data.tab}`]: false,
                });
              }
            }

            if (res.data.hasOwnProperty("store_list_style")) {
              that.setData({
                openTemplate: res.data.store_list_style || 0
              });
            }
            // console.log(this.data[`shopList${that.data.tab}`], "aa");
          } else {
            // wx.showToast({
            // 	icon: 'none',
            // 	title: res.msg,
            // 	duration: 1500
            // })
            console.log(res.msg);
          }
          // console.log(that.data.shopList0)
        },
        fail: function (res) {
          console.log(res);
          wx.showToast({
            title: res.msg,
            duration: 1000,
            icon: "none",
          });
        },
      });
    },
    getPdData() {
      let that = this;
      let point = app.qqMapTransBMap(parseFloat(this.data.point.lng), parseFloat(this.data.point.lat));
      let json = {
        lng: point.lng,
        lat: point.lat,
        city_name: this.data.city,
        page: this.data.page1,
        week: this.data.pd_date.week_num,
        category_id: this.data.pd_category_id,
        day: this.data.pd_date.day,
      };
      let urlStr = app.getNetAddresss("plugin.universal-card.frontend.store-discount.privilege");
      app._getNetWork({
        url: urlStr,
        data: json,
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            that.setData({
              total_page1: res.data.last_page,
              shopList1: res.data.data,
            });
            if (that.data.total_page1 <= 1) {
              that.setData({
                isLoadMore1: false,
              });
            } else {
              that.setData({
                isLoadMore1: true,
              });
            }
          } else {
            that.setData({
              isLoadMore1: false,
            });
          }
        },
        fail: function (res) {
          console.log(res);
        },
      });
    },
  },
});
