<template>

  <el-form label-width="100px" :model="data" :rules="rules" ref="baseFormRef">
    <el-form-item label="单位名称" prop="orgName" required>
      <el-input v-model.trim="data.orgName" style="width: 300px" :maxlength="50" placeholder="请输入" />
    </el-form-item>
    <el-form-item label="类型" prop="type" required>
      <!-- <el-input v-model="data.type" style="width: 300px" :maxlength="500" placeholder="请输入" /> -->
      <el-select style="width: 300px" v-model="data.type">
        <el-option :value="Number(key)" :label="type" v-for="(type, key) in OrganizationTypeDesc" />
      </el-select>
    </el-form-item>

    <el-form-item label="行政区划" prop="type">
      <el-cascader style="width: 300px" v-model="selectedValue" :props="lazyProps" :placeholder="'请选择地区'" clearable
        @change="handleChange" lazy />
    </el-form-item>

  </el-form>
</template>

<script setup lang="ts">
import { QuiskExpose } from "@/helper/mount";
import type { FormInstance, FormRules } from "element-plus";
import type { OrganizationType } from "@/request/organization";
import { OrganizationTypeDesc } from '@/store/organization';
import { getProvinces, getCities, getAreas } from '@/request/organization';
import { ref, reactive, unref, watchEffect, onMounted } from "vue";
import { user } from '@/store/user'
import { globalPasswordRex } from "@/util/regex";
import type { CascaderProps } from 'element-plus'
// import areaData from '@/util/area.json';
const selectedValue = ref([])

const baseFormRef = ref<FormInstance>();


const rules = reactive<FormRules>({
  orgName: [
    { required: true, message: "请输入单位名称", trigger: "blur" },
  ],
  type: [
    { required: true, message: "请选择类型", trigger: "change" },
  ],
  contact: [
    { required: true, message: "请输入联系人", trigger: "blur" },
  ],
  userName: [
    { required: true, pattern: /^1[3456789]\d{9}$/, message: "请输入正确手机号", trigger: "blur" },
  ],
  password: [
    { required: true, pattern: globalPasswordRex, message: "请输入8-16位数字、字母大小写组合", trigger: "blur" },
    { required: true, min: 8, message: '密码太短！', trigger: "blur" },
  ],
},)

const props = defineProps<{
  org: OrganizationType,
  submit: (data: OrganizationType) => Promise<any>;
}>();

const data = ref<OrganizationType & {}>({
  ancestors: "",
  contact: "",
  orderNum: 0,
  orgId: 0,
  orgName: "",
  parentId: 0,
  password: "",
  type: null,
  userName: ""
});

const setParentId = () => {
  if (user.value) {
    const isSuper = user.value.roles.filter(item => item.roleKey === "super_admin").length > 0;
    data.value.parentId = isSuper ? 0 : Number(user.value.orgId)
  }
}
watchEffect(() => {
  if (props.org) {
    data.value = { ...props.org }
  }

})


// 动态加载配置
const lazyProps = ref<CascaderProps>({
  lazy: true,

  // 启用懒加载模式
  async lazyLoad(node, resolve) {
    // debugger
    const { level, value } = node; // level: 当前层级（0=省，1=市，2=区）
    console.log('node', node.data)
    const dataRes = await loadData(level, node.data);
    resolve(dataRes);  // 将子节点数据返回给组件
  },
  checkStrictly: true, // 允许选择任意一级（可选）
  label: 'name',    // 显示字段名
  value: 'id',      // 值字段名
  leaf: 'leaf',      // 标识是否为叶子节点（不可再展开）
});


const loadData = async (level, node) => {
  // 根据层级模拟数据
  console.log('level', level, node)

  switch (level) {
    case 0: // 加载省份
      const provinces = await getProvinces();
      const resP = Array.from(provinces as any).map(p => {
        p.leaf = false
        return p
      });
      return resP;
    case 1:
      let cities
      if (node.zx) {
        const areas = await getAreas(node.province, node.city);
        console.log('areas', areas)
      } else {
        cities = await getCities(node.province);
        console.log('cities', node.province, cities);
      }

      return cities
    // break;
    case 2: // 加载区县
      const areas = await getAreas(node.province, node.city)
      console.log('areas', areas)
      return areas.map(a => {
        a.leaf = true
        return a
      })
    default:
      return [];
  }
};

// 处理选择事件
const handleChange = (value: string) => {
  console.log('选中的省市区编码:', value);
};

defineExpose<QuiskExpose>({
  async submit() {

    if (unref(baseFormRef)) {
      setParentId();
      const res = await unref(baseFormRef)?.validate();
      if (res) {
        await props.submit(data.value as any as OrganizationType);
      }
    } else {
      throw "";
    }
  },
});
</script>