import { connect } from 'herculex';
import { listMerchantStores, merchantQueryConfig } from '../../../services';
import { history } from '../../../utils';
/**
 * @Auther: 陈林(wb-cl445194)
 * @Date: 2021/4/8 10:22 上午
 * @Description: 商家列表
 */

const wait = (time = 0) => new Promise(resolve => setTimeout(resolve, time));

Component(connect({
  mapStateToProps: {
    titleBarHeight: state => state.$global.titleBarHeight
  }
})({
  props: {
    componentData: {}
  },
  data: {
    emptyFooter: [{
      text: '刷新'
    }],
    showPopup: false,
    regions: [],
    serviceTypes: [],
    regionNameColor: '#999',
    simpleMarkers: [],
    footer: null,
    list: [],
    scrollIntoView: '',
    isShowMap: false,
    isShowList: false,
    serviceTypeCode: undefined,
    serviceTypeName: undefined,
    regionCode: undefined,
    regionName: undefined,
    searchName: undefined,
    curUserLongitude: undefined,
    curUserLatitude: undefined,
    cityCode: undefined,
    enableScroll: 'auto',
    enableTouchMove: true,
    autoToBottom: true
  },

  async didMount() {
    const location = await this.getLocation();
    await this.setFooter();
    await this.fetchQuery(location);
    await this.setComponentVisible();
  },

  methods: {
    onScroll() {
      this.onTouchEnd();

      if (!this.data.enableTouchMove) {
        return;
      }

      this.setData({
        enableTouchMove: false
      });
    },

    async onTouchEnd() {
      clearTimeout(this.timer);
      this.timer = setTimeout(() => {
        this.setData({
          enableTouchMove: true
        });
      }, 100);
    },

    setFooter() {
      const {
        windowWidth
      } = my.getSystemInfoSync();
      this.setData({
        footer: {
          top: '100vh',
          middle: '45vh',
          bottom: windowWidth * 150 / 750
        }
      });
    },

    async moveToLocation() {
      await wait(500);
      const map = my.createMapContext('map');

      if (map) {
        map.showsCompass({
          isShowsCompass: 0
        });
        map.moveToLocation();
      }
    },

    async setComponentVisible() {
      const {
        showBlocks = ''
      } = this.props.componentData.componentExtInfo || {};
      const isShowMap = showBlocks.includes('map');
      this.setData({
        isShowMap,
        isShowList: showBlocks.includes('list')
      });
      !isShowMap && this.map.toTop();
    },

    getLocation() {
      return new Promise(resolve => {
        my.getLocation({
          type: 1,
          success: result => {
            resolve(result);
          },
          fail: () => {
            my.alert({
              title: '定位失败',
              success: () => {
                my.navigateBack();
              }
            });
          }
        });
      });
    },

    saveMapRef(ref) {
      this.map = ref;
    },

    saveRef(ref) {
      this.flatList = ref;
    },

    // 点击地图标记
    async onMarkerTap({
      markerId
    }) {
      await this.setData({
        scrollIntoView: ''
      });
      await this.setData({
        enableScroll: 'on',
        scrollIntoView: markerId
      });
      await wait(300);
      this.setData({
        enableScroll: 'auto'
      });
    },

    // 搜索此区域
    async onSearchMap({
      latitude,
      longitude
    }) {
      await this.setData({
        curUserLongitude: longitude,
        curUserLatitude: latitude,
        serviceTypeCode: '',
        serviceTypeName: '',
        searchName: ''
      });
      this.onRefreshList();
    },

    onShowPopup() {
      this.setData({
        showPopup: true
      });
    },

    onHidePopup() {
      this.setData({
        showPopup: false
      });
    },

    async onChangeRegionName({
      currentTarget: {
        dataset: {
          record
        }
      }
    }) {
      const {
        regions
      } = this.data;
      const {
        regionName
      } = record;
      await this.setData({
        regionName,
        regionCode: regions.find(item => item.regionName === regionName).regionCode,
        regionNameColor: '#1677ff'
      });
      this.onHidePopup();
      this.onRefreshList();
    },

    onChangeSearchName(value) {
      this.setData({
        searchName: value
      });
    },

    async onConfirmSearchName() {
      this.onRefreshList();
    },

    async onChangeServiceTypeCode({
      currentTarget: {
        dataset: {
          record
        }
      }
    }) {
      await this.setData({
        serviceTypeCode: record.serviceTypeCode,
        serviceTypeName: record.serviceTypeName
      });
      await this.onRefreshList();
    },

    async onRefreshList() {
      if (this.flatList) {
        await this.setData({
          list: []
        });
        await this.flatList.refresh();
      } else {
        const {
          curUserLongitude,
          curUserLatitude
        } = this.data;
        const [err, result] = await listMerchantStores({
          currentPage: 1,
          pageSize: 10,
          curUserLongitude,
          curUserLatitude
        });
        !err && this.setListAndSimpleMarkers(result.list);
      }
    },

    async fetchQuery(location) {
      await this.setData({
        curUserLongitude: location.longitude,
        curUserLatitude: location.latitude,
        cityCode: location.cityAdcode
      });
      const [, result] = await merchantQueryConfig({
        curUserLongitude: location.longitude,
        curUserLatitude: location.latitude,
        cityCode: location.cityAdcode
      });

      if (result) {
        const firstRegion = result.regions[0] || {
          regionName: '默认区域',
          regionCode: ''
        };
        this.setData({
          regions: result.regions,
          regionName: firstRegion.regionName,
          regionCode: firstRegion.regionCode,
          serviceTypes: result.serviceTypes
        });
      }
    },

    async setListAndSimpleMarkers(resultList) {
      this.autoToLocation(resultList[0]);

      if (!resultList.length) {
        return;
      }

      const {
        list
      } = this.data;
      const newList = list.concat(resultList);
      const simpleMarkers = [];
      newList.forEach(item => {
        const id = `id${Math.random().toString(26).substr(2)}`;
        item.id = id;
        simpleMarkers.push({
          id,
          latitude: Number(item.merchantStoreLatitude),
          longitude: Number(item.merchantStoreLongitude)
        });
      });
      await this.setData({
        list: newList,
        simpleMarkers
      });
    },

    // 自动定位到地图
    async autoToLocation(firstData) {
      // 第一次加载的时候执行
      if (!this.oneAutoToLocation) {
        this.oneAutoToLocation = true;

        if (firstData) {
          await wait(500); // 第一次执行需要等待
        } else {
          await this.moveToLocation();
        }
      }

      const map = my.createMapContext('map');

      if (!map || !firstData) {
        return;
      }

      await this.setData({
        autoToBottom: false
      });
      map.moveToLocation({
        longitude: firstData.merchantStoreLongitude,
        latitude: firstData.merchantStoreLatitude
      });
      await wait(200);
      this.setData({
        autoToBottom: true
      });
    },

    async onFetchData(currentPage, pageSize) {
      const {
        serviceTypeCode,
        serviceTypeName,
        regionCode,
        regionName,
        searchName,
        curUserLongitude,
        curUserLatitude,
        cityCode
      } = this.data;
      const [err, result] = await listMerchantStores({
        currentPage,
        pageSize,
        serviceTypeCode,
        serviceTypeName,
        regionCode,
        regionName,
        searchName,
        curUserLongitude,
        curUserLatitude,
        cityCode
      });

      if (err) {
        throw new Error('err');
      }

      this.setListAndSimpleMarkers(result.list);
      return {
        total: result.pagination.total
      };
    },

    toDetail({
      currentTarget: {
        dataset: {
          record
        }
      }
    }) {
      const {
        merchantStoreCode,
        merchantStoreName
      } = record;
      history.push({
        pageType: 'merchant-detail-component',
        title: '商家详情',
        query: {
          merchantStoreCode,
          merchantStoreName
        }
      });
    }

  }
}));