<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>
</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 { ref, reactive, unref, watchEffect } from "vue";
import { user } from '@/store/user'
import { globalPasswordRex } from "@/util/regex";
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 }
  }

})

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>