// packageG/independent_store/index/index.js
const app = getApp();
Page({
  externalClasses: ['tabs'],
  data: {
    mainInfo: {},
    page_id: "",
    clientWidth: "375",
    btnFlag: false,
    store_components: [],
    store_pageInfo: {},
    bottom_info: {},
    foot_type: "",
    bottomShowBol: false,
    bottomShowBolIndex: 0,

    store_id: '',
    albumList: [], // 相册列表
    tabList: [], // tab导航列表
    storeInfo: '',
    coupons: [],
    swiperIndex: 0,
    showMoreAlbum: false,
    active: 'store_info',
    showServicePopup: false, // 客服弹框
    contactPerson: {}, // 联系人

    U_tabcontrol: true,
    isLoadMore: true,
    goodsData: {
      "preview_color": "#f5f5f5",
      "sort_style": {
        "choose_icon": "2"
      },
      "padding_top": 0,
      "padding_bottom": 0,
      "padding_left": 10,
      "padding_right": 10,
      "item_radius": 5,
      "show_shadow": false,
      "show_border": false,
      "border_color": "#BFB7B7",
      "good_tag": {
        "choose_icon": "0",
        "image": ""
      },
      "button_type": "3",
      "button_title": "立即购买",
      "button_bg_color": "#ff2c29",
      "button_color": "#ffffff",
      "content_list": [
        "1",
        "3",
        "4",
        "7"
      ],
      "show_price_text": false,
      "disable_good": "0",
      "goods_type": "list"
    },
    navigationBarTitle:'',
  },

  onLoad: function (options) {
    if (options.scene) {
      let {
        store_id
      } = this.sceneDecode(options.scene);
      app.globalData.STORE_ID = store_id;
      this.setData({
        store_id
      });
    }
    if (options.store_id) {
      app.globalData.STORE_ID = options.store_id;
      this.setData({
        store_id: options.store_id
      });
    }
    if (!this.data.store_id) {
      wx.redirectTo({
        url: '/packageG/independent_store/access_tip/access_tip',
      });
      return;
    }
    this.getData();
  },

  onShow: function () {

  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.setData({
      bottomShowBol: true,
    });

    if (this.data.decorate_isLoadMore) {
      this.getMorePluginData();
    }
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title:this.data.navigationBarTitle
    };
  },
  // 获取滚动条当前位置
  onPageScroll: function (e) {
    if (this.data.store_components && this.data.store_components.length > 0) {
      // 节流
      if (e.scrollTop > 80) {
        if (!this.data.btnFlag) {
          this.setData({
            btnFlag: true,
          });
        }
      } else {
        if (this.data.btnFlag) {
          this.setData({
            btnFlag: false,
          });
        }
      }

      if (this.data.bottomShowBol) {
        this.setData({
          bottomShowBol: false,
        });
      }
    }
  },

  // 解析二维码
  sceneDecode(scene) {
    scene = decodeURIComponent(scene);
    let paramArr = scene.split(",");
    const senceValues = {};

    paramArr.forEach((item, index) => {
      let key = item.split("=")[0];
      let value = item.split("=")[1];
      senceValues[key] = value;
    });
    return senceValues;
  },
  getData() {
    wx.showLoading({
      title: "加载中",
    });
    let strUlr = app.getNetAddresss("plugin.store-alone-temp.frontend.home.home-page");
    app._getNetWork({
      url: strUlr,
      data: {
        store_id: this.data.store_id
      },
      success: (respone) => {
        wx.hideLoading();
        if (respone.data.result !== 1) {
          app.tips(respone.data.msg);
          wx.redirectTo({
            url: '/packageG/independent_store/access_tip/access_tip',
          });
          return;
        }

        // 开启门店装修
        let resData = respone.data;
        if (resData.data.store_decorate && resData.data.store_decorate.datas) {
          this.setData({
            mainInfo: resData.data.store_info,
            page_id: resData.data.store_decorate.id,
            store_components: resData.data.store_decorate.datas,
            store_pageInfo: resData.data.store_decorate.page_info,
            foot_type: resData.data.store_decorate.foot_type,
          });

          // 装修的底部有三种情况
          if (resData.data.store_decorate.foot_type == -1) {
            // 不显示
            this.setData({
              bottom_info: {},
            });
          } else if (resData.data.store_decorate.foot_type == 1) {
            // 显示默认
            if (!resData.data.store_decorate.foot_id || !resData.data.store_decorate.foot_id.page_info) {
              // 显示系统默认
              this.setData({
                bottom_info: {},
              });
            } else {
              // 显示列表设置的默认
              this.setData({
                bottom_info: JSON.parse(resData.data.store_decorate.foot_id.page_info),
              });
            }
          } else if (resData.data.store_decorate.foot_type == 2) {
            // 显示自定义的底部导航
            if (!resData.data.store_decorate.foot_id || resData.data.store_decorate.foot_id instanceof Array) {
              this.setData({
                bottom_info: {},
              });
            } else {
              this.setData({
                bottom_info: JSON.parse(resData.data.store_decorate.foot_id.page_info),
              });
            }
          }
          this.data.navigationBarTitle = ( this.data.store_pageInfo.page_title || respone.data.data.store_info.store_name || "商家");
          wx.setNavigationBarTitle({
            title: this.data.navigationBarTitle,
          });
          wx.setNavigationBarColor({
            backgroundColor: this.data.store_pageInfo.preview_color,
            frontColor: this.data.store_pageInfo.font_color == 1 ? "#ffffff" : "#000000",
            animation: {
              duration: 400,
              timingFunc: "easeIn",
            },
          });
          return;
        }

        // 没有装修走默认
        let res = respone.data.data;
        res.nav.nav.unshift({
          code: "store_info",
          name: "商家信息"
        });
        if (res.photo && res.photo.length == 6) {
          res.photo.push({});
        }
        this.setData({
          albumList: res.photo || [],
          storeInfo: res.store_info,
          tabList: res.nav.nav,
          coupons: res.store_info.coupon,
        });
        if (this.data.tabList.length > 1) {
          if (this.data.tabList[1].code === 'recommend_goods') {
            this.setData({
              ["goodsData.list"]: res.nav.data
            });
          }
        }
        this.data.navigationBarTitle = this.data.storeInfo.store_name;
        wx.setNavigationBarTitle({
          title:  this.data.navigationBarTitle
        });
      },
      fail(err) {
        wx.hideLoading();
      }
    });
  },

  changeTab(e) {
    this.setData({
      active: e.detail.name
    });
    this.data.isLoadMore = true;

    // this.getPlugins("plugin.store-alone-temp.frontend.home.nav-data", {
    //  page: 1, code: this.data.active, store_id: app.globalData.STORE_ID
    // }, this.data.active);
  },
  getPlugins(url, json, plugin_active) {
    let urlStr = app.getNetAddresss(url);
    app._getNetWork({
      url: urlStr,
      data: json,
      success: (resdata) => {
        let res = resdata.data;
        if (res.result == 1) {
          if (plugin_active === 'recommend_goods') {
            this.setData({
              ["goodsData.list"]: res.data.data
            });
          }
        }
      }
    });
  },

  getMorePluginData() {
    this.data.isLoadMore = false;
    let plugin_active = this.data.active;
    if (plugin_active === 'recommend_goods') {
      let recommendGoods = this.selectComponent("#recommend_goods");
      recommendGoods.loadMoreMemberData();
    }
  },

  setLoadMore(event) {
    this.setData({
      isLoadMore: event.detail.isLoadMore
    });
  },

  goToAdress() {
    let latitude = this.data.storeInfo.latitude;
    let longitude = this.data.storeInfo.longitude;
    let store_name = this.data.storeInfo.store_name;
    let point = app.BMapTransqqMap(parseFloat(longitude), parseFloat(latitude));
    wx.openLocation({
      latitude: point.lat,
      longitude: point.lng,
      scale: 18,
      name: store_name,
    });
  },

  // 轮播图
  swiperChange(e) {
    this.setData({
      swiperIndex: e.detail.current
    });
    if (this.data.albumList[0].label_data_count > 6 && e.detail.current === 5) {
      this.setData({
        showMoreAlbum: true
      });
    } else if (this.data.albumList[0].label_data_count > 6 && e.detail.current === 6) {
      // 最后多一个直接跳转
      this.setData({
        swiperIndex: 5
      });
      this.goStoreAlbums();
    } else {
      this.setData({
        showMoreAlbum: false
      });
    }
  },

  collectCoupons(e) {
    let coupon = e.currentTarget.dataset.item;
    if (coupon.api_availability == 3) {
      return;
    }
    let strUlr = app.getNetAddresss("coupon.member-coupon.get-coupon");
    wx.showLoading({
      title: "loading"
    });
    app._postNetWork({
      url: strUlr,
      data: {
        coupon_id: coupon.id
      },
      success: (resdata) => {
        wx.hideLoading();
        var res = resdata.data;
        if (res.result == 1) {
          wx.showToast({
            title: '领取成功',
            icon: 'none',
            duration: 2000
          });
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 2000
          });
        }
      },
      fail() {
        wx.hideLoading();
      }
    });
  },

  // 客服弹框
  showServicePopup() {
    this.setData({
      showServicePopup: true
    });
  },

  closeServicePopup() {
    this.setData({
      showServicePopup: false
    });
  },

  // 通讯录
  showContactPopup(e) {
    this.setData({
      'contactPerson.mobile': e.currentTarget.dataset.mobile,
      'contactPerson.name': e.currentTarget.dataset.name,
      showContactPopup: true,
    });
  },
  contactStaff(e) {
    this.setData({
      'contactPerson.mobile': e.detail.mobile,
      'contactPerson.name': e.detail.name,
      showContactPopup: true,
    });
  },
  callPhone() {
    wx.makePhoneCall({
      phoneNumber: this.data.contactPerson.mobile,
    });
  },
  copyPhone() {
    wx.setClipboardData({
      data: this.data.contactPerson.mobile,
      success(res) {},
      fail(err) {
        wx.showToast({
          title: '复制失败',
          icon: 'none'
        });
      }
    });
  },
  addPhone() {
    wx.addPhoneContact({
      firstName: this.data.contactPerson.name,
      mobilePhoneNumber: this.data.contactPerson.mobile,
    });
  },
  closeContactPopup(e) {
    this.setData({
      showContactPopup: false
    });
  },

  // 拨打电话
  phoneCall(e) {
    let {
      mobile
    } = e.currentTarget.dataset;
    mobile && wx.makePhoneCall({
      phoneNumber: mobile,
    });
  },
  gotoChat(evt) {
    let url = evt.currentTarget.dataset.cservice + "&store_id=" + this.data.store_id;
    wx.navigateTo({
      url: url,
      fail: (err) => {
        app.tips("客服路由出错");
      }
    });
  },
  goStoreAlbums() {
    wx.navigateTo({
      url: '/packageG/independent_store/store_album/store_album?store_id=' + this.data.store_id,
    });
  },
  goCouponStore() {
    wx.navigateTo({
      url: '/packageD/coupon/coupon_store',
    });
  },
  goO2oStore(event) {
    let type = event.currentTarget.dataset.type;
    if (type === 'comment') {
      wx.navigateTo({
        url: `/packageC/o2o/o2oStore/o2oStore?store_id=${this.data.store_id}&activeType=comment`,
      });
    } else {
      wx.navigateTo({
        url: `/packageC/o2o/o2oStore/o2oStore?store_id=${this.data.store_id}`,
      });
    }

  },

});