<template>
  <Page name="search-address">
    <template #header>
      <search-bar v-model="searchForm.query" placeholder="请输入需要搜索的地址关键词" auto @confirm="onSearch" />
    </template>
    <template #content>
      <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.adname}${item.address}`" @click="onSelect(item, index)"></zui-cell>
        </template>
      </List>
    </template>
  </Page>
</template>

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

export default {
  data() {
    return {
      searchForm: {
        query: ''
      },
      list: [],
    }
  },
  methods: {
    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 ?? [];
            resolve({ result: pois, totalCount: pois.length });
          },
          fail: () => {
            uni.showToast({ title: '没有查询到结果', icon: 'none' });
            resolve({ result: [], totalCount: 0 });
          },
        });
      });
    },
    onSelect(item) {
      const params = this.$params;
      if (params.mode === 'select') {
        const lnglatArr = `${item.location || ''}`.split(',');
        const waypoint = {
          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],
        };
        uni.$emit('select-detail', waypoint);
        uni.navigateBack();
      }
    }
  }
}
</script>
