import getLocationInfo from '../../utils/getLocationInfo';
import { defaultInternalEventEmitter } from '../../utils/staticVariable';
import { getDetail, getStoreStyle, getJumpStoreId } from '../../services/store';
import { connect } from 'herculex';
const app = getApp();
Component(connect({
  mapStateToProps: {
    cityCode: state => state.$global.cityCode,
    mktCode: state => state.$global.mktCode,
    componentList: state => state.componentList
  }
})({
  props: {
    componentData: {}
  },
  data: {
    store: null,
    bgImg: '',
    color: ''
  },
  methods: {
    onNavBgHeight(height) {
      this.commitGlobal && this.commitGlobal({
        headB2bHight: height
      });
    },

    onChangeStore(e) {
      const {
        cityCode,
        storeId
      } = e;
      this.commitGlobal && this.commitGlobal({
        cityCode,
        globalShopId: storeId,
        globalShop: { ...e
        }
      });
    },

    onSelectStore(storeItem) {
      this.loadData(storeItem.storeId).then(() => {
        const {
          store
        } = this.data;

        if (store) {
          this.onChangeStore(store);
          defaultInternalEventEmitter.dispatchEvent('onChangeStore', store);
        }
      });
    },

    async onGetLocation() {
      await this.loadData(); // 获取位置授权后附近门店和优惠券需刷新

      const {
        store
      } = this.data;

      if (store) {
        this.onChangeStore(store); // 优惠券和店铺在同一个页面中，店铺加载完毕后事件，因为优惠券依赖店铺.

        defaultInternalEventEmitter.dispatchEvent('onReadyStore');
      }
    },

    setPopup(ref) {
      this.$popup = ref;
    },

    setLocationTip(locationTip) {
      this.$locationTip = locationTip;
    },

    async handleSwitchStore() {
      const {
        cityCode
      } = this.data;

      if (cityCode) {
        this.$popup.show();
        return;
      }

      await getLocationInfo();
      this.$locationTip.show(false);
      await this.onGetLocation();
      this.$popup.show();
    },

    handleMakePhoneCall() {
      const {
        store
      } = this.data;

      if (!store) {
        return;
      }

      const {
        contactMobile: phone
      } = store;

      if (phone) {
        my.makePhoneCall({
          number: phone
        });
      }
    },

    handleNavigate() {
      const {
        store
      } = this.data;

      if (!store) {
        return;
      }

      const {
        storeName: name,
        address,
        latitude,
        longitude
      } = store;
      my.openLocation({
        name,
        address,
        latitude: Number(latitude),
        longitude: Number(longitude)
      });
    },

    async loadData(storeId = '') {
      const {
        shopType = 'ALL'
      } = this.props.componentData.componentExtInfo || {};
      const {
        cityCode
      } = this.data;
      const {
        regionData,
        store = {}
      } = app.globalData;
      const {
        latitude,
        longitude,
        selectedLocation
      } = regionData || {};
      const {
        detail = {}
      } = store;
      const {
        launchOptions: {
          query = {}
        } = {}
      } = app.globalData;
      const {
        options = {}
      } = this.$page;
      const productId = query.productId || options.productId || '';
      app.globalData.launchOptions.query = {};
      let jumpStoreId = '';
      let skuId = '';

      if (productId) {
        // 外部跳转
        const {
          shopId = '',
          skuId: newSkuId = ''
        } = (await getJumpStoreId({
          productId,
          latitude,
          longitude
        })) || {};
        jumpStoreId = shopId;
        skuId = newSkuId;
        this.commitGlobal && this.commitGlobal({
          jumpSkuId: skuId
        });
      }

      return getDetail({
        storeId: jumpStoreId || storeId || detail.storeId,
        shopType,
        coordinate: latitude && longitude ? {
          latitude,
          longitude
        } : undefined,
        cityCode: selectedLocation ? selectedLocation.cityCode : cityCode
      }).then(res => {
        if (!res) {
          return;
        }

        app.globalData.store = {
          detail: res
        }; // 切换店铺重置步行，距离较远，有可能不会调用success
        // `undefined` not work?

        this.setData({
          walk: '',
          store: res
        });

        if (longitude && latitude) {
          my.calculateRoute({
            startLat: Number(res.latitude),
            startLng: Number(res.longitude),
            endLng: Number(longitude),
            endLat: Number(latitude),
            success: ({
              duration
            }) => {
              const walk = formatDuration(duration);

              if (walk) {
                this.setData({
                  walk
                });
              }
            }
          });
        }
      }).then(() => {
        // 依赖店铺详情数据，图片和描述影响高度
        // 基础库1.x无this.createSelectorQuery
        (this.createSelectorQuery || my.createSelectorQuery)().select('#store-container').boundingClientRect().exec(([rect]) => {
          if (rect && 'height' in rect) {
            const {
              height
            } = rect;
            this.setData({
              navBgHeight: height
            });
            app.globalData.store.detailHeight = height;
            this.onNavBgHeight(height);
          }
        });
      }).catch(() => {
        this.props.onErrorCallback && this.props.onErrorCallback('business');
      });
    },

    async getStyle() {
      const {
        detailPageBackground,
        themeColor
      } = await getStoreStyle();
      this.setData({
        bgImg: detailPageBackground || undefined,
        color: themeColor || undefined
      });
    }

  },

  didMount() {
    const {
      showRegion
    } = app.globalData;
    const {
      cityCode,
      mktCode,
      componentList
    } = this.data;
    const hasMkt = componentList.find(item => item.componentType === 'voucherComponent');

    if (!cityCode && !mktCode && showRegion !== 'Y' && !hasMkt) {
      // 无位置授权，开启位置授权
      getLocationInfo().then(() => {
        this.onGetLocation();
      }, // 拒绝位置授权
      () => {
        this.$locationTip.show();
        this.onGetLocation();
        this.props.onErrorCallback && this.props.onErrorCallback('location');
      });
    }

    this.getStyle();
  },

  didUpdate(prevProps, prevData) {
    if (!prevData.cityCode && this.data.cityCode) {
      // 有位置授权
      this.onGetLocation();
    }
  },

  didUnmount() {
    // 防止优惠券页面或者切换门店数据数据共享
    // app.globalData.store.detail = undefined;
    if (app.globalData.store) {
      app.globalData.store.detailHeight = undefined;
    }
  }

}));
/**
 * 格式化步行时间.
 *
 * @param duration 时间，单位秒.
 * @returns `1天5小时14分钟`, `5小时14分钟`, `14分钟`.
 */

function formatDuration(duration) {
  if (typeof duration !== 'number') {
    return '';
  }

  let minute = parseInt((duration / 60).toString(), 10);
  let hour = 0;
  let day = 0;

  if (minute >= 60) {
    hour = Math.floor(minute / 60);
    minute %= 60;
  }

  if (hour >= 24) {
    day = Math.floor(hour / 24);
    hour %= 24;
  }

  let walk = '';

  if (day) {
    walk += `${day}天`;
  }

  if (hour) {
    walk += `${hour}小时`;
  }

  if (minute || !walk && minute === 0) {
    walk += `${minute === 0 ? 1 : minute}分钟`;
  }

  return walk;
}