<template>

  <el-form label-width="100px" :model="data" :rules="rules" ref="baseFormRef">
    <el-form-item label="单位名称" prop="orgId" required>
      <!-- <el-autocomplete style="width: 300px" v-model="data.orgName" :fetch-suggestions="querySearch" clearable
        class="inline-input w-50" placeholder="请输入" @select="handleSelect" /> -->
      <el-tree-select   :check-strictly="true" :props="{
        value: 'orgId',
        label: (data: any) => data.orgName,
      }" style="width: 300px" v-model="data.orgId" :data="allOrgs" node-key="orgId" @node-click="handleNodeClick" clearable>

      </el-tree-select>
    </el-form-item>

    <el-form-item label="姓名" prop="nickName" required>
      <el-input v-model="data.nickName" style="width: 300px" :maxlength="15" placeholder="请输入" />
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { QuiskExpose } from "@/helper/mount";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
// import { ElMessage } from "element-plus";
import type { OrganizationType } from '@/request/organization'
import {
  // getOrgListFetch,
  getOrgListFetchList,
  UserType
} from "@/request";

import { ref, reactive, unref, onMounted, watchEffect } from "vue";


const baseFormRef = ref<FormInstance>();

type SelectType = {
  orgName: string,
  orgId: number
  children: SelectType[]
}

const allOrgs = ref<SelectType[]>([]);

const rules = reactive<FormRules>({
  orgId: [
    { required: true, message: "请选择单位名称", trigger: "select" },
  ],
  nickName: [
    { required: true, message: "请输入姓名", trigger: "blur" },
    // { required: true, pattern: /^1[3456789]\d{9}$/, message: "请输入正确手机号", trigger: "blur" },
  ],
},)

const props = defineProps<{
  user: UserType,
  submit: (data: UserType) => Promise<any>;
}>();
const data = ref<Partial<OrganizationType> & Partial<UserType>>({
  nickName: "",
  orgId: undefined,
  password: "",
  status: 0,
  // userId: 0,
  userName: ""
});

onMounted(async () => {

  const data = await getOrgListFetchList()
  console.log('list', data)
  allOrgs.value = data as any as SelectType[]

})

// 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.user) {
    data.value = { ...props.user }
  }
})

const handleNodeClick = (node: SelectType) => {
  data.value.orgId = node.orgId
  data.value.orgName = node.orgName
  console.log('handleNodeClick', node.orgId, node.orgName)
}

defineExpose<QuiskExpose>({
  async submit() {
    if (unref(baseFormRef)) {
      const res = await unref(baseFormRef)?.validate();
      if (res) {
        await props.submit(data.value as any as UserType);
        ElMessage.success('编辑成功！');
      }
    } else {
      throw "";
    }
  },
});
</script>