<script setup lang="tsx">
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { PropType, watch, ref, onMounted, unref } from 'vue'
import { useValidator } from '@/hooks/web/useValidator'
import { cloneDeep } from 'lodash-es'
import { ElInputTag, ElAutocomplete } from 'element-plus'
import { getMapSearch } from '@/api/system/admin'
import { UpImgButtom } from '@/components/UpFile'
import { mapAddressData } from '@/api/system/admin/types'
import { getConfigKey } from '@/api/system/admin'
import { UserButtom } from '@/components/UserList'

const { required, phone } = useValidator()
const mapKey = ref('')
onMounted(async () => {
  const res = await getConfigKey('tengxun_map_key')
  if (res) {
    mapKey.value = res.data.tengxun_map_key
  }
})
const props = defineProps({
  currentRow: {
    type: Object as PropType<any>,
    default: () => null
  },
  groupList: {
    type: Array,
    default: () => [{ label: '无', value: 0 }]
  }
})
const formSchema = ref<FormSchema[]>([
  {
    field: 'uid',
    label: '用户',
    component: 'CheckboxGroup',
    formItemProps: {
      slots: {
        default: (data) => {
          return (
            <>
              <UserButtom
                v-model={data.uid}
                onChangeUser={(res) => {
                  checkedUser(res)
                }}
              ></UserButtom>
            </>
          )
        }
      }
    }
  },
  {
    field: 'group_id',
    label: '所属组',
    component: 'Select',
    componentProps: {
      placeholder: '请选择组',
      options: props.groupList
    }
  },
  {
    field: 'name',
    label: '姓名',
    component: 'Input',
    componentProps: {
      placeholder: '请输入姓名'
    }
  },
  {
    field: 'avatar',
    label: '头像',
    component: 'CheckboxGroup',
    componentProps: {
      placeholder: '选择头像'
    },
    formItemProps: {
      slots: {
        default: (data) => {
          return (
            <>
              <UpImgButtom v-model={data.avatar}></UpImgButtom>
            </>
          )
        }
      }
    }
  },
  {
    field: 'phone',
    label: '手机号',
    component: 'Input',
    componentProps: {
      type: 'number',
      placeholder: '请输入手机号'
    }
  },
  {
    field: 'gender',
    label: '性别',
    component: 'Select',
    value: 0,
    componentProps: {
      placeholder: '请选择性别',
      options: [
        {
          label: '保密',
          value: 0
        },
        {
          label: '男',
          value: 1
        },
        {
          label: '女',
          value: 2
        }
      ]
    }
  },

  {
    field: 'birth_day_time',
    label: '出生日期',
    component: 'DatePicker'
  },

  {
    field: 'start_job_year',
    label: '就业年份',
    component: 'Input',
    componentProps: {
      placeholder: '例子：2014'
    }
  },

  {
    field: 'tag_list',
    label: '标签',
    colProps: {
      span: 24
    },
    component: 'CheckboxGroup',
    formItemProps: {
      slots: {
        default: (data) => {
          return (
            <>
              <ElInputTag
                v-model={data.tag_list}
                tagEffect="light"
                tagType="primary"
                clearable
              ></ElInputTag>
            </>
          )
        }
      }
    }
  },
  {
    field: 'detail_address',
    label: '省市区地址',
    colProps: {
      span: 24
    },
    component: 'Input',
    formItemProps: {
      slots: {
        default: (data) => {
          return (
            <>
              <ElAutocomplete
                v-model={data.detail_address}
                value-key="label"
                onSelect={(val: any) => {
                  selectAddress(val)
                }}
                fetch-suggestions={(val, cb) => {
                  searchAddress(val, cb)
                }}
              >
                {{
                  default: ({ item }) => {
                    return (
                      <>
                        <div class="lh-none mt-10px">{item.label}</div>
                        <div class="font-size-12px lh-none  mt-5px pb-10px b-b-solid b-b-light b-b-1px">
                          {item.address}
                        </div>
                      </>
                    )
                  }
                }}
              </ElAutocomplete>
            </>
          )
        }
      }
    }
  },
  {
    field: 'province',
    label: '省份',
    component: 'Input',
    hidden: true
  },
  {
    field: 'city',
    label: '市',
    hidden: true,
    component: 'Input'
  },
  {
    field: 'area',
    label: '区',
    hidden: true,
    component: 'Input'
  },
  {
    field: 'longitude',
    label: '经度',
    hidden: true,
    component: 'Input'
  },
  {
    field: 'latitude',
    label: '纬度',
    hidden: true,
    component: 'Input'
  },
  {
    field: 'id',
    hidden: true,
    component: 'Input'
  }
])

const rules = ref({
  uid: [required('请选择用户')],
  avatar: [required('请上传头像')],
  phone: [required('请填写手机号'), phone()],
  birth_day_time: [required('请选择出生日期')],
  detail_address: [
    {
      required: true,
      validator: (_, val, callback) => {
        if (!actionAddress.value || !val) {
          callback(new Error('请选择地址'))
        } else {
          callback()
        }
      }
    }
  ],
  name: [required('请填写等级名称')]
})

const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose } = formMethods

const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    const formData = await getFormData()
    return formData
  }
}

defineExpose({
  submit
})
const checkedUser = async (res: any) => {
  setValues({
    uid: res.uid,
    name: res.real_name,
    avatar: [res.avatar],
    birth_day_time: res.birthday,
    phone: res.phone,
    gender: res.sex || 0
  })
}
const actionAddress = ref<mapAddressData>()
const searchAddress = async (queryString: string, cb: (arg: any) => void) => {
  if (queryString) {
    const { data } = await getMapSearch({
      key: unref(mapKey),
      keyword: queryString
    })
    cb(
      data.map((item): mapAddressData => {
        return {
          adcode: item.adcode,
          label: item.title,
          address: item.address,
          lng: item.location.lng,
          lat: item.location.lat,
          province: item.province,
          city: item.city,
          district: item.district
        }
      })
    )
  }
}
const selectAddress = (item: mapAddressData) => {
  if (!item || !item.adcode || !item.lng || !item.lat) {
    console.error('Invalid input item:', item)
    return
  }

  const adcodeStr = String(item.adcode).padStart(6, '0') // 确保 adcode 至少有6位
  const province = adcodeStr.slice(0, 2)
  const city = adcodeStr.slice(2, 4)
  const area = adcodeStr

  setValues({
    province: `${province}`,
    city: `${province}${city}00000000`,
    area: `${area}000000`,
    longitude: item.lng,
    latitude: item.lat
  })

  actionAddress.value = item
  center.value = {
    lng: item.lng,
    lat: item.lat
  }
  geometries.value = [{ styleId: 'marker', position: { lat: item.lat, lng: item.lng } }]
}
const center = ref({ lat: 28.655759, lng: 121.420808 })
const geometries = ref([{ styleId: 'marker', position: { lat: 28.655759, lng: 121.420808 } }])

watch(
  () => props.currentRow,
  async (value) => {
    if (!value) return
    const currentRow = cloneDeep(value)
    actionAddress.value = {
      adcode: currentRow.area,
      label: currentRow.detail_address,
      lng: currentRow.longitude,
      lat: currentRow.latitude
    }
    setValues(currentRow)
  },
  {
    deep: true,
    immediate: true
  }
)
</script>

<template>
  <div class="flex flex-col">
    <Form :rules="rules" @register="formRegister" :schema="formSchema" />
    <TlbsMap
      v-if="mapKey"
      ref="map"
      :api-key="mapKey"
      :zoom="15"
      :center="center"
      :control="{
        scale: {},
        zoom: {
          position: 'topRight'
        }
      }"
    >
      <TlbsMultiMarker
        :geometries="geometries"
        :styles="{
          marker: {
            width: 20,
            height: 30,
            anchor: { x: 10, y: 30 }
          }
        }"
      />
    </TlbsMap>
  </div>
</template>
<style lang="less" scoped>
:deep(.el-table__row) {
  .list {
    width: 50px;
    text-align: center;
  }
}
</style>
