<template>
  <el-dialog v-model="props.visible" v-if="props.visible" :title="props.cityId ? '编辑' : '新增'" width="600" :close-on-click-modal="false"
    :before-close="dialogClose">
    <el-form ref="formRef" :model="formData" label-width="80px">
      <div class="flex">
        <el-form-item label="上级城市" prop="pid" class="flex-1" :rules="{ required: true, message: '请选择上级城市', trigger: 'change' }">
        <el-tree-select v-model="formData.pid" :data="cityOptions" lazy :load="loadTree" :cacheData="caCheData"
          node-key="id" @node-click="handleNodeClick" :props="treeProps" :check-strictly="true"
          placeholder="上级城市" />
      </el-form-item>
        <el-form-item label="城市级别" prop="level" class="flex-1">
        <el-select v-model="formData.level" clearable placeholder="请选择城市级别">
          <el-option v-for="(item, index) in optionData.cityTypeList" :key="index" :label="item.name"
            :value="item.id" />
        </el-select>
      </el-form-item>
      </div>
      <div class="flex">
        <el-form-item label="城市名称" prop="name" class="flex-1"
          :rules="{ required: true, message: '请输入城市名称', trigger: 'blur' }">
          <el-input v-model="formData.name" placeholder="请输入城市名称" clearable />
        </el-form-item>
        <el-form-item label="城市简称" prop="shortName" class="flex-1"
          :rules="{ required: true, message: '城市简称称', trigger: 'blur' }">
          <el-input v-model="formData.shortName" placeholder="请输入城市简称称" clearable />
        </el-form-item>
      </div>
      <div class="flex">
        <el-form-item label="城市区号" prop="cityCode" class="flex-1"
          :rules="{ required: true, message: '城市区号', trigger: 'blur' }">
          <el-input v-model="formData.cityCode" placeholder="请输入城市区号" clearable />
        </el-form-item>
        <el-form-item label="行政编码" prop="areaCode" class="flex-1"
          :rules="{ required: true, message: '行政编码', trigger: 'blur' }">
          <el-input v-model="formData.areaCode" placeholder="请输入行政编码" clearable />
        </el-form-item>
      </div>
      <div class="flex">
        <el-form-item label="城市经度" prop="lng" class="flex-1"
          :rules="{ required: true, message: '城市经度', trigger: 'blur' }">
          <el-input v-model="formData.lng" placeholder="请输入城市经度" clearable />
        </el-form-item>
        <el-form-item label="城市纬度" prop="lat" class="flex-1"
          :rules="{ required: true, message: '城市纬度', trigger: 'blur' }">
          <el-input v-model="formData.lat" placeholder="请输入城市纬度" clearable />
        </el-form-item>
      </div>
      <div class="flex">
        <el-form-item label="邮政编码" prop="zipCode" class="flex-1">
          <el-input v-model="formData.zipCode" placeholder="请输入邮政编码" clearable />
        </el-form-item>
      </div>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogClose">取消</el-button>
        <el-button :loading="subLoading" type="primary" @click="submit">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import type { FormInstance } from "element-plus";
import { cityAdd, cityUpdate, getCityList, getCityDetail } from '@/api/data/city';
import { onMounted, reactive, ref, shallowRef,nextTick } from "vue";
import { getCityByList } from "@/api/system/user";
import { message } from "@/utils/auth";
import { useLockFn } from "@/utils/useLockFn";
const props = defineProps({
  visible: {
    type: Boolean,
    required: true,
    default: false
  },
  cityId: {
    type: Number,
    required: true,
    default: 0
  },
  parentData: {
    type: Object,
    default: () => {},
  }
});
const optionData = reactive({
  cityTypeList: [{
    id: 0,
    name: '省份'
  },
  {
    id: 1,
    name: '城市'
  },
  {
    id: 2,
    name: '县区'
  },
  {
    id: 3,
    name: '街道'
  }],
});
const emit = defineEmits(["success", "update:visible"]);
const formRef = shallowRef<FormInstance>();


const formData = reactive({
  id: "",
  pid: '',
  level: '',
  name: "",
  cityCode: '',
  areaCode: '',
  parentCode: '',
  zipCode: '',
  shortName: '',
  lng: '',
  lat: ''
});
const caCheData = ref([])
const dialogClose = () => {
  emit("update:visible", false);
};
const treeProps = {
  label: 'name',
  children: 'children',
  isLeaf: 'isLeaf',
}
const cityOptions = ref<any[]>([]);
const menu: any = [{ areaCode: 0, name: "根目录",id:0 }];
const loadTree = async (node: Node, resolve: (data: Tree[]) => void) => {
  if (node.level === 0) {
    return resolve(menu)
  }
  let data = []
  data = await getCityByList(parseInt(node.data.areaCode))
  data.map(item => {
    if(item.level<=3){
      item.isLeaf = false
    } else {
      item.isLeaf = true
    }
  })
  resolve(data)
};
const handleNodeClick = (data: Tree) => {
  formData.pid = data.id
}
const handleSubmit = async () => {
  await formRef.value?.validate();
  if(formData.pid==0){
    formData.parentCode ='0'
  }
  props.cityId ? await cityUpdate(formData) : await cityAdd(formData);
  message("操作成功");
  emit("update:visible", false);
  emit("success",formData.parentCode);
};

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


const setFormData = (data: Record<any, any>) => {
  for (const key in formData) {
    if (data[key] != null && data[key] != undefined) {
      formData[key] = data[key];
    }
  }
  caCheData.value = [{ id: formData.pid, name: data.parentName}]
};

const getDetail = async () => {
  const data = await getCityDetail(
    props.cityId
  );
  setFormData(data);
};

onMounted(() => {
  if (props.cityId) {
    getDetail()
  } else {
    if(props.parentData) {
      formData.pid=props.parentData.id
      formData.parentCode=props.parentData.areaCode
      caCheData.value = [{ id: props.parentData.id, name: props.parentData.name}]   
  }
}
});
</script>
