<template>
  <el-dialog :title="dialogTitle" v-model="dialogVisible" width="800px">
    <el-tabs v-model="tabName">
      <el-tab-pane label="线索信息" name="info">
        <Form
          ref="formRef"
          v-loading="formLoading"
          :rules="rules"
          isCol
          :schema="allSchemas.formSchema"
        />
      </el-tab-pane>
      <el-tab-pane label="跟进信息" name="follow">
        <el-button type="primary" @click="handleAppendFollow">新增跟进人</el-button>
        <el-table :data="followList">
          <el-table-column label="跟进人">
            <template #default="{ row }">
              <el-select v-model="row.followUser" placeholder="选择跟进人" filterable>
                <el-option
                  v-for="item in userOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="nextFollowTime" label="下次跟进时间">
            <template #default="{ row }">
              <el-date-picker v-model="row.nextFollowTime" type="date" placeholder="选择日期时间" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80">
            <template #default="{ $index }">
              <Icon icon="ep:remove-filled" class="text-red-500" @click="handleRemove($index)" />
              <!-- <el-button @click="handleRemove(row, $index)">
                
              </el-button> -->
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="位置信息" name="map">
        <div class="flex justify-between">
          <el-select
            v-model="areaValue"
            filterable
            clearable
            remote
            style="width: 350px"
            reserve-keyword
            placeholder="请输入关键词"
            :remote-method="remoteMethod"
            @change="currentSelect"
          >
            <el-option
              v-for="item in areaList"
              :key="item.id"
              :label="item.name"
              :value="item.name"
              class="one-text"
            >
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.district }}</span>
            </el-option>
          </el-select>
          <el-checkbox v-model="showSchool" :label="true" @change="handleShowSchool"
            >展示场地</el-checkbox
          >
        </div>
        <div id="dialogMap" class="mt-20px" style="height: 400px; width: 100%"></div>
      </el-tab-pane>
    </el-tabs>
    <template #footer>
      <span>
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button :disabled="formLoading" type="primary" @click="handleSave">保 存</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { allSchemas, rules } from '../cluePool.data'
import { formatDate } from '@/utils/formatTime'
import AMapLoader from '@amap/amap-jsapi-loader'
import ImgPostion from '@/assets/imgs/flag/flag_red.png'
import ImgFlag from '@/assets/imgs/flag/position_blue.png'

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formRef = ref() // 表单 Ref

const tabName = ref('info')

const followList = ref([])
const userOptions = ref([])

const areaValue = ref('新天地国际')
const areaList = ref([])

const open = async (type, info) => {
  dialogVisible.value = true
  dialogTitle.value = type == 'create' ? '新增线索' : '修改线索'
  formType.value = type
  // 修改时，设置数据
  if (info) {
    formLoading.value = true
    try {
      const data = { ...info }
      nextTick(() => {
        formRef.value.setValues(data)
      })
    } finally {
      formLoading.value = false
    }
  }
  if (!dialogMap.value) {
    nextTick(() => {
      initMap()
      remoteMethod('新天地国际')
    })
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

function handleSave() {
  console.log('保存')
}

function handleAppendFollow() {
  followList.value.push({
    followUser: undefined,
    nextFollowTime: formatDate(new Date())
  })
}
function handleRemove(index) {
  followList.value.splice(index, 1)
}

// 地图相关
const dialogMap = ref(null)
const aMap = ref(null)
let AutoComplete = ref(null)
let geoCoder = ref(null)
function initMap() {
  AMapLoader.load({
    key: '2ffb0e2ea90b1df0b8be48ed66e18fc8', //设置您的key
    version: '2.0',
    plugins: ['AMap.Geocoder', 'AMap.AutoComplete']
  }).then((AMap) => {
    aMap.value = AMap
    dialogMap.value = new AMap.Map('dialogMap', {
      zoom: 12,
      zooms: [2, 22],
      center: [117.283042, 31.86119]
    })
    AutoComplete.value = new AMap.AutoComplete({
      city: '全国'
    })
    geoCoder.value = new AMap.Geocoder()
    dialogMap.value.on('click', (e) => {
      addmark(e.lnglat.getLng(), e.lnglat.getLat(), AMap)
    })
  })
}

let marker = ref(null)
function addmark(lat, lng, AMap) {
  marker.value && removeMarker()
  marker.value = new AMap.Marker({
    position: new AMap.LngLat(lat, lng),
    zoom: 13,
    icon: ImgPostion
  })
  dialogMap.value.add(marker.value)
  dialogMap.value.setCenter([lat, lng], '', 500)
}
function removeMarker() {
  dialogMap.value.remove(marker.value)
}

const showSchool = ref(false)
const schoolMarkers = ref([])
function handleShowSchool() {
  if (showSchool.value) {
    let marker1 = new aMap.value.Marker({
      map: dialogMap.value,
      position: [117.258001, 31.895216],
      label: {
        content: '慧安驾校桃花社区训练基地',
        direction: 'left'
      },
      icon: ImgFlag,
      // extData: element,
      clickable: true
    })
    let marker2 = new aMap.value.Marker({
      map: dialogMap.value,
      position: [117.286731, 31.902396],
      label: {
        content: '（皖西）瑞星驾校总校（D）',
        direction: 'left'
      },
      icon: ImgFlag,
      // extData: element,
      clickable: true
    })
    schoolMarkers.value = [marker1, marker2]
  } else {
    dialogMap.value.remove(schoolMarkers.value)
  }
}

function remoteMethod(searchValue) {
  if (searchValue !== '') {
    setTimeout(() => {
      AutoComplete.value?.search(searchValue, (status, result) => {
        if (result.tips?.length) {
          areaList.value = result?.tips
        }
      })
    }, 200)
  }
}

function currentSelect(val) {
  const area = areaList.value.find((it) => it.name == val)
  if (area) {
    addmark(area.location?.lng, area.location?.lat, aMap.value)
    dialogMap.value.setCenter([area.location?.lng, area.location?.lat], '', 500)
  }
}
</script>

<style scoped>
:deep() .amap-logo {
  display: none !important;
}

:deep() .amap-copyright {
  display: none !important;
}
</style>
