<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-select style="width: 300px" v-model="data.orgId" clearable @change="handleSelect">
        <el-option :value="Number(id)" :label="value" v-for="{ value, id } in allOrgs" />
      </el-select>
    </el-form-item>

    <el-form-item label="姓名" prop="nickName" required>
      <el-input v-model="data.nickName" style="width: 300px" :maxlength="500" 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,

  UserType
} from "@/request";

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


const baseFormRef = ref<FormInstance>();

type SelectType = {
  value: string, id: number
}

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 getOrgListFetch({
    pageNum: 1,
    pageSize: 10000,
  })
  // console.log('allOrgs', data.records);
  allOrgs.value = Array.from(data.records).map((item: OrganizationType) => {
    const i: SelectType = { value: item['orgName'], id: item['orgId'] }
    return i
  });

})

// 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 handleSelect = (orgId: number) => {
  const item = Array.from(allOrgs.value).find(i => i.id === orgId)
  if (item) {
    data.value.orgName = item.value
  }
}
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>