<template>
  <a-modal
    v-model:visible="props.visible"
    :title="props.cityId ? '编辑' : '新增'"
    width="600px"
    @cancel="dialogClose"
  >
    <a-form ref="formRef" :model="formData" :label-col="{ style: { width: '80px' } }">
      <div class="flex">
        <a-form-item
          label="上级城市"
          name="pid"
          class="flex-1"
          :rules="{ required: true, message: '请选择上级城市', trigger: 'change' }"
        >
          <a-tree-select
            v-model:value="formData.pid"
            :tree-data="cityOptions"
            :load-data="loadTree"
            @select="handleNodeClick"
            :dropdownMatchSelectWidth="false"
            :fieldNames="{ children: 'children', label: 'name', value: 'id' }"
            placeholder="上级城市"
          />
        </a-form-item>
        <a-form-item label="城市级别" name="level" class="flex-1">
          <a-select v-model:value="formData.level" allow-clear placeholder="请选择城市级别">
            <a-select-option
              v-for="(item, index) in optionData.cityTypeList"
              :key="index"
              :value="item.id"
              >{{ item.name }}</a-select-option
            >
          </a-select>
        </a-form-item>
      </div>
      <div class="flex">
        <a-form-item
          label="城市名称"
          name="name"
          class="flex-1"
          :rules="{ required: true, message: '请输入城市名称', trigger: 'blur' }"
        >
          <a-input v-model:value="formData.name" placeholder="请输入城市名称" allow-clear />
        </a-form-item>
        <a-form-item
          label="城市简称"
          name="shortName"
          class="flex-1"
          :rules="{ required: true, message: '城市简称称', trigger: 'blur' }"
        >
          <a-input v-model:value="formData.shortName" placeholder="请输入城市简称称" allow-clear />
        </a-form-item>
      </div>
      <div class="flex">
        <a-form-item
          label="城市区号"
          name="cityCode"
          class="flex-1"
          :rules="{ required: true, message: '城市区号', trigger: 'blur' }"
        >
          <a-input v-model:value="formData.cityCode" placeholder="请输入城市区号" allow-clear />
        </a-form-item>
        <a-form-item
          label="行政编码"
          name="areaCode"
          class="flex-1"
          :rules="{ required: true, message: '行政编码', trigger: 'blur' }"
        >
          <a-input v-model:value="formData.areaCode" placeholder="请输入行政编码" allow-clear />
        </a-form-item>
      </div>
      <div class="flex">
        <a-form-item
          label="城市经度"
          name="lng"
          class="flex-1"
          :rules="{ required: true, message: '城市经度', trigger: 'blur' }"
        >
          <a-input v-model:value="formData.lng" placeholder="请输入城市经度" allow-clear />
        </a-form-item>
        <a-form-item
          label="城市纬度"
          name="lat"
          class="flex-1"
          :rules="{ required: true, message: '城市纬度', trigger: 'blur' }"
        >
          <a-input v-model:value="formData.lat" placeholder="请输入城市纬度" allow-clear />
        </a-form-item>
      </div>
      <div class="flex">
        <a-form-item label="邮政编码" name="zipCode" class="flex-1">
          <a-input v-model:value="formData.zipCode" placeholder="请输入邮政编码" allow-clear />
        </a-form-item>
      </div>
    </a-form>
    <template #footer>
      <span class="dialog-footer">
        <a-button @click="dialogClose">取消</a-button>
        <a-button :loading="subLoading" type="primary" @click="submit"> 确定 </a-button>
      </span>
    </template>
  </a-modal>
</template>
<script lang="ts" setup>
  import type { FormInstance } from 'ant-design-vue';
  import { cityAdd, cityUpdate, getCityDetail } from '@/api/data/city';
  import { onMounted, reactive, ref, shallowRef, nextTick } from 'vue';
  import { getCityByList } from '@/api/system/user';
  import { message } from 'ant-design-vue';
  import { useLockFn } from '@/utils/useLockFn';

  /**
   * 定义参数变量
   */
  const emit = defineEmits(['success', 'update:visible']);
  const formRef = shallowRef<FormInstance>();

  /**
   * 定义接收的参数
   */
  const props = defineProps({
    visible: {
      type: Boolean,
      required: true,
      default: false,
    },
    cityId: {
      type: Number,
      required: true,
      default: 0,
    },
    parentData: {
      type: Object,
      default: () => {},
    },
    itemData: {
      type: Object,
      default: () => {},
    },
  });

  /**
   * 定义选项数据
   */
  const optionData = reactive({
    cityTypeList: [
      {
        id: 0,
        name: '省份',
      },
      {
        id: 1,
        name: '城市',
      },
      {
        id: 2,
        name: '县区',
      },
      {
        id: 3,
        name: '街道',
      },
      {
        id: 4,
        name: '居委会',
      },
    ],
  });

  /**
   * 定义表单参数
   */
  const formData = reactive({
    id: '',
    pid: 0,
    level: '',
    name: '',
    cityCode: '',
    areaCode: '',
    parentCode: '',
    zipCode: '',
    shortName: '',
    lng: '',
    lat: '',
  });
  const caCheData = ref([]);
  const parentCode = ref({});

  /**
   * 关闭窗体
   */
  const dialogClose = () => {
    formData.pid = 0;
    emit('update:visible', false);
  };

  /**
   * 加载树结构
   */
  const cityOptions = ref([{ id: 0, name: '根目录', areaCode: 0, children: [] }]);
  const loadTree = async (treeNode) => {
    return new Promise((resolve: any) => {
      // if(treeNode.dataRef.children){
      //   resolve()
      //   return
      // }
      getCityByList(parseInt(treeNode.areaCode)).then((res) => {
        treeNode.dataRef.children = res;
        cityOptions.value = [...cityOptions.value];
      });
      resolve();
    });
  };

  /**
   * 执行节点点击事件
   */
  const handleNodeClick = (data, node, extra) => {
    parentCode.value = node;
  };

  /**
   * 执行提交表单
   */
  const handleSubmit = async () => {
    await formRef.value?.validate();
    if (formData.pid == 0) {
      formData.parentCode = '0';
    }
    props.cityId ? await cityUpdate(formData) : await cityAdd(formData);
    message.success('操作成功');
    emit('update:visible', false);
    emit('success', parentCode.value);
  };

  const { isLock: subLoading, lockFn: submit } = useLockFn(handleSubmit);

  /**
   * 设置表单数据
   * @param data 参数
   */
  const setFormData = (data: Record<any, any>) => {
    for (const key in formData) {
      if (data[key] != null && data[key] != undefined) {
        formData[key] = data[key];
      }
    }
    parentCode.value = { areaCode: formData.parentCode };
    caCheData.value = [{ id: formData.pid, name: data.parentName }];
  };

  /**
   * 获取详情
   */
  const getDetail = async () => {
    const data = await getCityDetail(props.cityId);
    setFormData(data);
  };

  /**
   * 钩子函数
   */
  onMounted(() => {
    if (props.parentData) {
      cityOptions.value[0].children.push(props.parentData);
    }
    if (props.cityId) {
      getDetail();
      formData.pid = props.itemData.pid;
    } else if (props.itemData) {
      formData.pid = props.itemData.id;
    }
  });
</script>
