<script setup lang="tsx">
import { Form, FormSchema } from '@/components/Form'
import { UpImgButtom } from '@/components/UpFile'
import { useForm } from '@/hooks/web/useForm'
import { PropType, watch, ref, onMounted, unref, reactive, nextTick } from 'vue'
import { useValidator } from '@/hooks/web/useValidator'
import { cloneDeep } from 'lodash-es'
import { ElAutocomplete, FormRules,ElSelect,ElOption } from 'element-plus'
import { getConfigKey, getMapSearch } from '@/api/system/admin'
import { mapAddressData } from '@/api/system/admin/types'
// import { UserList } from '@/components/UserList'
// import { BaseButton } from '@/components/Button'
import { StoreButtom } from '@/components/StoreList'
import { getRoleListApi } from '@/api/system/role'
import { getUnitList } from '@/api/goods'

interface op {
  label: string
  value: number
}
const mapKey = ref('')
const roleList = ref([])
const areaList = ref<op[]>([])

const actionAddress = ref<mapAddressData>()
const { required } = useValidator()
const center = ref({ lat: 28.655759, lng: 121.420808 })
const geometries = ref([{ styleId: 'marker', position: { lat: 28.655759, lng: 121.420808 } }])
// const userDetail = ref<any>()

const checkedUser = async (res: any) => {
  setValues({
    wid: res.id
  })
  console.log(res, '选择仓库')
}
const rules = reactive<FormRules>({
  name: [required('请填写门店名称')],
  // uid: [required('请选择绑定用户')],
  introduction: [required('请填写门店简介')],
  phone: [required('请填写联系号码')],
  logo: [required('请选择logo')],
  slide_images: [required('请选择推荐图')],
  manager_name: [required('请填写店长名称')],
  valid_range: [required('请填写有效距离')],
  roles: [required('请选择角色')],
  configure_id: [required('请选择区域')],
  store_account: [
    {
      required: true,
      message: '请填写登录账号'
    }
  ],
  store_password: [
    {
      required: true,
      message: '请输入登录密码'
    }
  ],
  true_password: [
    {
      required: true,
      validator: (_, val, callback) => {
        // console.log(item)
        getFormData().then((formData) => {
          if (!val) return callback()
          if (formData.store_password !== val) {
            callback(new Error('两次密码不一致'))
          } else {
            callback()
          }
        })
      }
    }
  ],
  detailed_address: [
    {
      required: true,
      validator: (_, val, callback) => {
        // console.log(actionAddress.value, val, 'actionAddress.value')
        if (!actionAddress.value || !val) {
          callback(new Error('请选择地址'))
        } else {
          callback()
        }
      }
    }
  ]
})
onMounted(async () => {
  const res = await getConfigKey('tengxun_map_key')
  if (res) {
    mapKey.value = res.data.tengxun_map_key
  }
  let required = true
  if (props.currentRow) {
    required = false
  }
  if (props.currentRow && props.currentRow.latitude) {
    center.value = {
      lat: props.currentRow.latitude,
      lng: props.currentRow.longitude
    }
    geometries.value = [
      {
        styleId: 'marker',
        position: { lat: props.currentRow?.latitude, lng: props.currentRow?.longitude }
      }
    ]
  }
  const data = await getRoleListApi({ page: 1, limit: 100, type: 2 })
  roleList.value = data.data.list.map((item) => {
    return {
      value: item.id,
      label: item.role_name
    }
  })
  const data1 = await getUnitList({ page: 1, limit: 100, type: 'area',pid: 0})
  // areaList.value = data1.data.list.map((item) => {

  //   return {
  //     value: item.id,
  //     label: item.name,
  //   }
  // })
  data1.data.list.forEach(element => {
    if (element.children.length == 0) {
      areaList.value.push({
        value: element.id,
        label: element.name,
      })
    } else {
      areaList.value.push({
        value: element.id,
        label: element.name,
      })
      element.children.forEach(element1 => {
        areaList.value.push({
          value: element1.id,
          label: '|__' + element1.name,
        })
      });
    }
  });
  console.log(areaList,'areaListareaListareaListareaList')
  await nextTick()
  await nextTick()
  if (rules && rules.store_account) {
    rules.store_account[0].required = required
  }
  if (rules && rules.store_password) {
    rules.store_password[0].required = required
  }
  if (rules && rules.true_password) {
    rules.true_password[0].required = required
  }
})

const props = defineProps({
  currentRow: {
    type: Object as PropType<any>,
    default: () => null
  }
})

const selectAddress = (item: mapAddressData) => {
  console.log(item,'item')
  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,
    address: item.address,
    detailed_address: item.label
  })

  actionAddress.value = item
  center.value = {
    lng: item.lng,
    lat: item.lat
  }
  geometries.value = [{ styleId: 'marker', position: { lat: item.lat, lng: item.lng } }]
}
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 formSchema = ref<FormSchema[]>([
  {
    field: 'wid',
    label: '关联仓库',
    component: 'CheckboxGroup',
    formItemProps: {
      slots: {
        default: (data) => {
          return (
            <>
              <StoreButtom
                v-model={data.wid}
                onChange={(res) => {
                  checkedUser(res)
                }}
              ></StoreButtom>
            </>
          )
        }
      }
    }
  },
  {
    field: 'name',
    label: '门店名称',
    component: 'Input',
    componentProps: {
      placeholder: '请输入门店名称'
    }
  },
  {
    field: 'type',
    label: '类型',
    component: 'Select',
    value: 1,
    componentProps: {
      options: [
        {
          label: '自营',
          value: 1
        },
        {
          label: '加盟',
          value: 2
        },
        {
          label: '仓库',
          value: 3
        }
      ]
    }
  },
  {
    field: 'manager_name',
    label: '店长',
    component: 'Input',
    componentProps: {
      placeholder: '请输入店长名称'
    }
  },
  {
    field: 'phone',
    label: '联系电话',
    component: 'Input',
    componentProps: {
      placeholder: '请输入联系电话'
    }
  },
  {
    field: 'store_account',
    label: '登录账号',
    component: 'Input',
    componentProps: {
      strength: true,
      placeholder: '请输入登录账号'
    }
  },
  {
    field: 'store_password',
    label: '登录密码',
    component: 'InputPassword',
    componentProps: {
      strength: true,
      placeholder: '请输入登录密码'
    }
  },
  {
    field: 'true_password',
    label: '重复登录密码',
    component: 'InputPassword',
    componentProps: {
      strength: true,
      placeholder: '请输入登录密码'
    }
  },
  // {
  //   field: 'true_pwd',
  //   label: '确认密码',
  //   component: 'InputPassword',
  //   componentProps: {
  //     strength: true,
  //     placeholder: '请输入重复输入登录密码'
  //   }
  // },

  {
    field: 'logo',
    label: '门店LOGO',
    component: 'CheckboxGroup',
    formItemProps: {
      slots: {
        default: (data) => {
          return (
            <>
              <UpImgButtom v-model={data.logo}></UpImgButtom>
            </>
          )
        }
      }
    }
  },
  {
    field: 'slide_images',
    label: '推荐图',
    component: 'CheckboxGroup',
    formItemProps: {
      slots: {
        default: (data) => {
          return (
            <>
              <UpImgButtom num={3} v-model={data.slide_images}></UpImgButtom>
            </>
          )
        }
      }
    }
  },
  {
    field: 'introduction',
    label: '简介',
    component: 'Input',
    colProps: {
      span: 24
    },
    componentProps: {
      type: 'textarea',
      rows: 2,
      placeholder: '请输入门店简介'
    }
  },
  // loss sale
  {
    field: 'loss_sale',
    label: '负库存销售',
    component: 'Switch'
  },
  {
    field: 'product_status',
    label: '自主添加商品',
    component: 'Switch'
  },
  {
    field: 'product_verify_status',
    label: '商品免审核',
    component: 'Switch'
  },
  {
    field: 'is_show',
    label: '是否显示',
    component: 'Switch'
  },
  {
    field: 'valid_range',
    label: '有效距离（km）',
    component: 'Input',
    componentProps: {
      placeholder: '请输入有效距离'
    }
  },
  {
    field: 'roles',
    label: '角色',
    component: 'Select',
    formItemProps: {
      slots: {
        default: (data) => {
          return (
            <>
              <ElSelect
                v-model={data.roles}
                placeholder="请选择角色"
                size="large"
                style="width: 240px"
              >
                {
                  roleList.value.map((item: {value: number,label: string}) => {
                    return (
                      <>
                        <ElOption value={item.value} label={item.label}></ElOption>
                      </>
                    )
                  })
                }
              </ElSelect>
            </>
          )
        }
      }
    }
  },
  {
    field: 'configure_id',
    label: '区域',
    component: 'Select',
    formItemProps: {
      slots: {
        default: (data) => {
          return (
            <>
              <ElSelect
                v-model={data.configure_id}
                placeholder="请选择区域"
                size="large"
                style="width: 240px"
              >
                {
                  areaList.value.map((item: {value: number,label: string}) => {
                    return (
                      <>
                        <ElOption value={item.value} label={item.label}></ElOption>
                      </>
                    )
                  })
                }
              </ElSelect>
            </>
          )
        }
      }
    }
  },
  {
    field: 'receiver_uid',
    label: '店长UID',
    component: 'Input',
    componentProps: {
      placeholder: '请输入店长UID'
    }
  },
  {
    field: 'appid',
    label: 'CBBappId',
    component: 'Input',
    componentProps: {
      placeholder: '请输入CBBappId'
    }
  },
  {
    field: 'appsecret',
    label: 'CBBappsecret',
    component: 'Input',
    componentProps: {
      placeholder: '请输入CBBappsecret'
    }
  },
  {
    field: 'huifu_id',
    label: '汇付ID',
    component: 'Input',
    componentProps: {
      placeholder: '请输入汇付'
    }
  },
  {
    field: 'auth_code',
    label: '授权码',
    component: 'Input',
    componentProps: {
      placeholder: '请输入授权码'
    }
  },
  {
    field: 'auth_code_end_time',
    label: '授权码有效期',
    component: 'Input',
    componentProps: {
      placeholder: '请输入授权码有效期'
    }
  },
  {
    field: 'detailed_address',
    label: '省市区地址',
    colProps: {
      span: 24
    },
    component: 'Input',
    formItemProps: {
      slots: {
        default: (data) => {
          return (
            <>
              <ElAutocomplete
                v-model={data.detailed_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',
    label: 'id',
    hidden: true,
    component: 'Input'
  }
])

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

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

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
  }
)

defineExpose({
  submit
})
</script>

<template>
  <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>
</template>
