<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 { 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'
import { SalespersonButtom } from '@/components/SalespersonList'
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
  }
})
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: 'parent_id',
    label: '邀请人',
    component: 'CheckboxGroup',
    formItemProps: {
      slots: {
        default: (data) => {
          return (
            <>
              <SalespersonButtom
                v-model={data.parent_id}
                onChange={(res) => {
                  checkedPareent(res)
                }}
              ></SalespersonButtom>
            </>
          )
        }
      }
    }
  },
  {
    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: 'salesperson_status',
    label: '自定义分成',
    value: false,
    component: 'Switch',
    componentProps: {
      on: {
        change: (val) => {
          if (val) {
            setValues({
              salesperson_commission: 0
            })
            setSchema([
              {
                field: 'salesperson_commission',
                path: 'componentProps.disabled',
                value: false
              }
            ])
          } else {
            setValues({
              salesperson_commission: '默认'
            })
            setSchema([
              {
                field: 'salesperson_commission',
                path: 'componentProps.disabled',
                value: true
              }
            ])
          }
        }
      }
    }
  },
  {
    field: 'salesperson_commission',
    label: '分成(%)',
    value: '默认',
    component: 'Input',
    componentProps: {
      disabled: true,
      type: 'text',
      placeholder: '请输入分成比例'
    }
  },
  {
    field: 'phone',
    label: '手机号',
    component: 'Input',
    componentProps: {
      type: 'number',
      placeholder: '请输入手机号'
    }
  },
  {
    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()],
  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, setSchema } = 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 checkedPareent = async (res: any) => {
  setValues({
    parent_id: res.id
  })
}

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
    }
    if (currentRow.salesperson_status) {
      setSchema([
        {
          field: 'salesperson_commission',
          path: 'componentProps.disabled',
          value: false
        }
      ])
    }
    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>
