<template>
  <span v-if="props.mode === 'look'">
    {{ text || '-' }}
  </span>
  <el-input
    v-else
    v-model="text"
    :type="formItem?.inputState"
    :disabled="disabled"
    readonly
    placeholder="点击右侧图标选择地址"
    @change="change"
  >
    <template #suffix>
      <el-icon class="el-input__icon cursor-pointer" @click="handleClick">
        <location />
      </el-icon>
    </template>
  </el-input>

  <Dialog
    v-model="dialogVisible"
    title="点位选择"
    width="800px"
    maxHeight="600px"
    class="map-dialog"
  >
    <div class="map-contain">
      <el-autocomplete
        v-model="searchText"
        style="width: 500px"
        fit-input-width
        placeholder="请输入"
        :fetch-suggestions="querySearch"
        :trigger-on-focus="false"
        clearable
        class="inline-input"
        @select="handleSelect"
      />
      <div id="map"></div>
      <div class="tip" v-if="model?.value"
        >当前选择位置：<span>{{ model?.value }}</span></div
      >
    </div>

    <template #footer>
      <BaseButton type="primary" @click="handleSave">确定</BaseButton>
      <BaseButton @click="handleClose">关闭</BaseButton>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { AutocompleteData } from 'element-plus'
import { Dialog } from '../../../../components/Dialog'
import AMapLoader from '@amap/amap-jsapi-loader'
import { onMounted } from 'vue'

import { ref, nextTick, watch, computed } from 'vue'

const emits = defineEmits(['update:modelValue'])

// let map = null;
let AMap = null

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  formItem: {
    type: Object,
    default: () => {}
  },
  formData: {
    type: Object,
    default: () => {}
  },
  mode: {
    type: String,
    default: 'add'
  },
  disabled: {
    type: Boolean,
    default: false
  }
})
// 点位数据
const mapData = computed(() => {
  return (props.modelValue && JSON.parse(props.modelValue)) || {}
})

const text = ref('')
// 最后绑定的数据
const model = ref()

watch(
  () => props.modelValue,
  (val) => {
    if (val) {
      text.value = mapData.value.value
      model.value = mapData.value
    }
  },
  {
    immediate: true
  }
)

const change = (val) => {
  if (val) {
    if (!model.value) {
      model.value = {}
    }
    model.value.value = val
  } else model.value = null

  emits('update:modelValue', (model.value && JSON.stringify(model.value)) || '')
}
// 弹窗地图部分
const dialogVisible = ref(false)
const map = ref()
const cityCode = window.CITY_CODE

const initMap = () => {
  console.log('initmap')
  //@ts-ignore
  window._AMapSecurityConfig = {
    // securityJsCode: "2bf102f50b193a7b1e67ad563a98ad76"
    securityJsCode: 'fb811f3c271a305025b0f95fd4817635'
  }

  AMapLoader.load({
    // key: "147364b1245d25e8df44278a4bb1e96a", // 申请好的Web端开发者Key，首次调用 load 时必填
    key: 'c73bccc87d2ae5998db5acf2d183128f', // 申请好的Web端开发者Key，首次调用 load 时必填
    // version: "1.4.15", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: ['AMap.Scale', 'AMap.PlaceSearch', 'AMap.AutoComplete', 'AMap.Geocoder'], //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
    AMapUI: {
      // 是否加载 AMapUI，缺省不加载
      // version: "1.1", // AMapUI 版本
      // plugins: ["misc/PathSimplifier"] // 需要加载的 AMapUI ui插件
    }
  })
    .then((aAMap) => {
      AMap = aAMap
      map.value = new AMap.Map('container', {
        // 设置地图容器id
        viewMode: '3D', // 是否为3D地图模式
        zoom: 11 // 初始化地图级别
        // center: currentLocation.value
        //     ? currentLocation.value
        //     : [116.397428, 39.90923] // 初始化地图中心点位置
      })
    })
    .catch((error) => {
      console.log(error, 'map error!!!!!')
    })
}

// 图标
const marker = ref()
const handleClick = () => {
  dialogVisible.value = true
  nextTick(() => {
    map.value = new AMap.Map('map', {
      resizeEnable: true,
      zoom: 14
    })
    map.value.on('complete', () => {
      console.log('地图加载完成！!')
      // 设置图标
      marker.value = new AMap.Marker()

      if (mapData.value.lnglat) {
        setMarker(mapData.value.lnglat)
        panTo(mapData.value.lnglat)
      }
    })
    // 地图点击
    map.value.on('click', (val) => {
      regeoCode([val.lnglat.lng, val.lnglat.lat])
    })
  })
}
// 设置地图图标
const setMarker = (lnglat) => {
  // 移除上一个
  map.value.remove(marker.value)
  map.value.add(marker.value)
  marker.value && marker.value.setPosition(lnglat)
}
// 地图移动到固定位置
const panTo = (lnglat) => {
  map.value.panTo(lnglat)
}

const address = ref('')

// 根据经纬度反查地址信息
const regeoCode = (lnglat: string | number[]) => {
  AMap.plugin('AMap.Geocoder', () => {
    const geocoder = new AMap.Geocoder({
      city: cityCode, //默认：“全国”
      radius: 1000 //范围，默认：500
    })

    setMarker(lnglat)

    geocoder.getAddress(lnglat, (status, result) => {
      if (status === 'complete' && result.regeocode) {
        const {
          formattedAddress,
          addressComponent: { towncode }
        } = result.regeocode
        address.value = formattedAddress

        model.value = {
          value: address.value,
          lnglat: lnglat,
          district_no: towncode.slice(0, 9)
        }
      } else {
        console.log('根据经纬度查询地址失败')
      }
    })
  })
}
// ** 搜索部分
const searchText = ref('')
const querySearch = async (queryString: string): Promise<AutocompleteData> => {
  if (!queryString) return []
  const res = await searchAddress(queryString)
  return res as AutocompleteData
}
// 选择搜索地址
const handleSelect = (item) => {
  // model.value = item

  panTo(item.lnglat)
  setMarker(item.lnglat)

  regeoCode(item.lnglat)
}
// 地址搜索
const searchAddress = (keywords) => {
  return new Promise((resolve) => {
    AMap.plugin(['AMap.PlaceSearch'], function () {
      //构造地点查询类
      const placeSearch = new AMap.PlaceSearch({
        pageSize: 10, // 单页显示结果条数
        pageIndex: 1, // 页码
        city: '3600' // 兴趣点城市
        // citylimit: true, //是否强制限制在设置的城市内搜索
      })
      //关键字查询
      placeSearch.search(keywords, (status, result) => {
        console.log(status, result)
        if (status === 'complete') {
          const data = result.poiList.pois.map((i) => {
            return {
              value: `${i.name} - ${i.address}`,
              lnglat: [i.location.lng, i.location.lat]
            }
          })
          resolve(data)
        } else {
          resolve([])
        }
      })
    })
    // AMap.plugin('AMap.AutoComplete', function () {
    //   // 实例化Autocomplete
    //   const autoOptions = {
    //     city: cityCode
    //   }
    //   const autoComplete = new AMap.AutoComplete(autoOptions)
    //   autoComplete.search(keywords, (status, result) => {
    //     // 搜索成功时，result即是对应的匹配数据
    //     if (status === 'complete') {
    //       const data = result.tips
    //         .filter((i) => i.id && i.location)
    //         .map((i) => {
    //           return {
    //             value: `${i.name} - ${i.district}${i.address}`,
    //             lnglat: [i.location.lng, i.location.lat]
    //           }
    //         })
    //       resolve(data)
    //     } else {
    //       resolve([])
    //     }
    //   })
    // })
  })
}

onMounted(() => {
  if (!map.value) {
    initMap()
  }
})

const handleSave = () => {
  dialogVisible.value = false
  text.value = address.value
  address.value = ''
  searchText.value = ''
  emits('update:modelValue', JSON.stringify(model.value))
}
const handleClose = () => {
  dialogVisible.value = false
  address.value = ''
  searchText.value = ''
  map.value && map.value.remove(marker.value)
}
</script>

<style lang="less" scoped>
.map-dialog {
  .map-contain {
    width: 100%;
    height: 100%;
    position: relative;
    :deep(.el-input__wrapper) {
      box-shadow: 0 0 0 1px var(--el-input-border-color, var(--el-border-color)) inset !important;
    }

    :deep(.inline-input) {
      position: absolute;
      left: 16px;
      top: 16px;
      z-index: 99;
      width: 300px;
    }

    .tip {
      position: absolute;
      bottom: 16px;
      right: 16px;
      background-color: #fff;
      padding: 0 8px;
      border-radius: 4px;

      span {
        color: var(--el-color-primary);
      }
    }
  }

  #map {
    width: 100%;
    height: 100%;
  }
}
</style>
<style>
.map-dialog .el-scrollbar__view {
  height: 100%;
}
</style>
