<template>
  <div class="edit-popup">
    <popup
        ref="popupRef"
        :title="popupTitle"
        :async="true"
        width="1000px"
        :clickModalClose="true"
        @confirm="handleSubmit"
        @close="handleClose"
    >
      <el-form ref="formRef" :model="formData" label-width="110px" :rules="formRules">
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="formData.mobile" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="业务员名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入业务员名称" />
        </el-form-item>
        <el-form-item label="负责地区" prop="address">
          <el-input v-model="formData.address" placeholder="请输入负责地区" />
        </el-form-item>
        <el-form-item label="坐标" prop="coordinate">
          <el-input v-model="formData.coordinate" placeholder="请输入坐标" />
        </el-form-item>
        <el-form-item label="搜索"  >
          <el-select v-model="formData.search"  filterable remote clearable
                     style="width: 370px"
                     placeholder="请输入关键字搜索" :remote-method="remoteMethod" @change="selectOne">
            <el-option v-for="item in formData.results" :label="item.name" :value="item.name"></el-option>
          </el-select>
        </el-form-item>
        <div style="align-content: center; margin-left: 100px">
          <MapContainer ref="refMap" :search="formData.search" v-model:results="formData.results" />
        </div>
      </el-form>
    </popup>
  </div>
</template>
<script lang="ts" setup>
import type { FormInstance } from 'element-plus'
import {  salesmanEdit, salesmanAdd, salesmanDetail } from '@/api/salesman'
import Popup from '@/components/popup/index.vue'
import feedback from '@/utils/feedback'
import type { PropType } from 'vue'
import MapContainer from "@/components/map/MapContainer.vue";
defineProps({
  dictData: {
    type: Object as PropType<Record<string, any[]>>,
    default: () => ({})
  }
})
const mapValue = ref<any>(null)
const refMap = ref<any>(null)
const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')
const popupTitle = computed(() => {
  return mode.value == 'edit' ? '编辑业务员信息' : '新增业务员信息'
})

const formData = reactive({
  id: '',
  mobile: '',
  name: '',
  address: '',
  coordinate: '',
  search: '',
  results: []
})

const formRules = {
  id: [
    {
      required: true,
      message: '请输入主键',
      trigger: ['blur']
    }
  ],
  mobile: [
    {
      required: true,
      message: '请输入手机号',
      trigger: ['blur']
    }
  ],
  name: [
    {
      required: true,
      message: '请输入业务员名称',
      trigger: ['blur']
    }
  ],
  address: [
    {
      required: true,
      message: '请输入负责地区',
      trigger: ['blur']
    }
  ],
}

const handleSubmit = async () => {
  await formRef.value?.validate()
  const data: any = { ...formData }
  mode.value == 'edit' ? await salesmanEdit(data) : await salesmanAdd(data)
  popupRef.value?.close()
  feedback.msgSuccess('操作成功')
  emit('success')
}

const open = (type = 'add') => {
  mode.value = type
  popupRef.value?.open()
}

const setFormData = async (data: Record<string, any>) => {
  for (const key in formData) {
    if (data[key] != null && data[key] != undefined) {
      //@ts-ignore
      formData[key] = data[key]
    }
  }
}

const getDetail = async (row: Record<string, any>) => {
  const data = await salesmanDetail({
    id: row.id
  })
  setFormData(data)
}

function remoteMethod(str) {
  refMap.value.search(str, (tips) => {
    console.log('%c ======tips======', 'font-size:14px; color:#22ff22;', tips)
    formData.results = tips
    console.log('%c ======formData======', 'font-size:14px; color:#22ff22;', formData)
  })
}


function selectOne(res ){
  console.log('%c ======res======', 'font-size:14px; color:#22ff22;', res)
  refMap.value.selectOne(res)
  mapValue.value = handlePut(res)
  console.log('%c ======mapValue======', 'font-size:14px; color:#22ff22;', mapValue)
  formData.address = res
}

const handlePut = (result) => {
  formData.results.forEach((item: any) => {
    if (result === item.name) {
      let location = item.location ? item.location : "";
      console.log('%c ======item======', 'font-size:14px; color:#22ff22;', item)
      console.log('%c ======location======', 'font-size:14px; color:#22ff22;', location.lat + ',' + location.lng)
      formData.coordinate = (location.lat ? location.lat : '') + ',' + (location.lng ? location.lng : '')
    }
  })
}

const handleClose = () => {
  emit('close')
}

defineExpose({
  open,
  setFormData,
  getDetail
})
</script>
