<template>
  <Page name="search-address">
    <template #header>
      <view style="display: flex; align-items: center">
        <view style="flex: 1"><search-bar v-model="searchForm.query" placeholder="请输入需要搜索的地址关键词" auto @confirm="onSearch" /></view>
        <view @click="selectLocation" style="width: 50px; padding-left: 10px; display: flex; align-items: center">
          <span> <u-icon name="map-fill"></u-icon></span>地图
        </view>
      </view>
    </template>
    <template #content>
      <template v-if="list.length === 0 && hisList.length > 0">
        <view class="search-history">历史地址</view>
        <template v-for="(item, index) in hisList">
          <zui-cell :key="index" :title="item.address" :label="`${item.cityName}${item.areaName}`" @click="onSelect(item, index)"></zui-cell>
        </template>
      </template>
      <List ref="list" v-model="list" :api="searchAPI">
        <template v-for="(item, index) in list">
          <zui-cell :key="index" :title="item.name" :label="`${item.cityName}${item.areaName}${item.address}`" @click="onSelect(item, index)"></zui-cell>
        </template>
        <template #empty>
          <view v-if="hisList.length > 0"></view>
          <u-empty v-else icon="https://download.shjiuze.cn/assets/image/empty/list.png" text="暂无数据"></u-empty>
        </template>
      </List>
    </template>
  </Page>
</template>

<script>
import { urlParam } from '@/utils/param';

export default {
  props: {
    getHisFun: Function,
  },
  data() {
    return {
      searchForm: {
        query: '',
      },
      list: [],
      hisList: [],
      lng: '',
      lat: '',
    };
  },
  onLoad(options) {
    this.lng = options.lng || '';
    this.lat = options.lat || '';
    this.queryHis(options.type);
  },
  methods: {
    queryHis(type) {
      if (type === 'getStartLatestAddress') {
        uni.$u.api.freightOrder.getStartLatestAddress({}).then(res => {
          this.hisList = res.result || [];
        });
      }
      if (type === 'getEndLatestAddress') {
        uni.$u.api.freightOrder.getEndLatestAddress({}).then(res => {
          this.hisList = res.result || [];
        });
      }
    },
    searchAPI() {
      if (!this.searchForm.query) {
        return new Promise(resolve => {
          resolve({ result: [], totalCount: 0 });
        });
      }
      return new Promise((resolve, reject) => {
        let params = {
          key: '1b987a62e5685a58cda5933e1bc66044',
          keywords: this.searchForm.query,
        };
        uni.request({
          headers: {
            'Content-Type': 'application/json;charset=UTF-8',
          },
          url: encodeURI(`https://restapi.amap.com/v5/place/text${urlParam(params)}`),
          method: 'GET',
          dataType: 'json',
          success: response => {
            const data = response.data ?? {};
            const pois = data.pois ?? [];
            let result = pois.map(item => {
              const lnglatArr = `${item.location || ''}`.split(',');
              return {
                name: item.name,
                provinceCode: item.pcode,
                provinceName: item.pname,
                areaCode: item.adcode,
                areaName: item.adname,
                cityCode: `${item.adcode}`.substring(0, 4) + '00',
                cityName: item.cityname,
                address: item.adname === item.address && item.name ? item.name : item.address || item.name,
                lng: lnglatArr[0],
                lat: lnglatArr[1],
              };
            });
            resolve({ result: result, totalCount: result.length });
          },
          fail: () => {
            uni.showToast({ title: '没有查询到结果', icon: 'none' });
            resolve({ result: [], totalCount: 0 });
          },
        });
      });
    },
    onSelect(item) {
      uni.$emit('select-detail', item);
      uni.navigateBack();
    },
    // 地图选点
    selectLocation() {
      uni.$once('webview-select', location => {
        this.onSelect(location);
      });
      const url = 'https://zeyi-tms-product.oss-cn-hangzhou.aliyuncs.com/webview/location-wx-freight.html';
      const params = {
        lat: this.lat ? Number(this.lat) : '',
        lng: this.lng ? Number(this.lng) : '',
      };
      uni.navigateTo({ url: `/pages/common/webview?url=${url}&query=${JSON.stringify(params)}` });
    },
  },
};
</script>
<style lang="scss">
.page-search-address {
  &__header {
    padding: 16rpx 32rpx !important;
  }
  .search-history {
    padding: 0 32rpx 32rpx 32rpx;
    font-weight: 500;
    font-size: 32rpx;
  }
  .zui-cell {
    padding: 12rpx 32rpx;
  }
  .zui-cell__label {
    padding-top: 8rpx;
  }
}
</style>
