<template>
  <BasicModal
    v-bind="$attrs"
    :title="title"
    @register="registerInnerModal"
    @ok="handleSubmit"
    @cancel="resetForm"
    :width="800"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<script setup lang="ts">
import { BasicModal, useModalInner } from "@/components/Modal";
import { BasicForm, useForm } from "@/components/Form";
import { computed, ref, unref } from "vue";
import {
  relevancyCodeInfo,
  relevancyCodeAdd,
  relevancyCodeUpdate,
} from "@/api/codeManage/codeRelationShip";
import { modalSchemas } from "./relevancyCode.data";
import { departmentTree } from "@/api/system/user";
import { addFullName } from "@/utils/helper/treeHelper";
import { postOptionSelect } from "@/api/system/post";
const postList = ref<Post[]>([]);
defineOptions({ name: "RelevancyCodeModal" });

const emit = defineEmits(["register", "reload"]);

const isUpdate = ref<boolean>(false);
const title = computed<string>(() => {
  return isUpdate.value ? "编辑电梯二维码关联信息;" : "新增电梯二维码关联信息;";
});

const [registerInnerModal, { modalLoading, closeModal }] = useModalInner(
  async (data: { record?: Recordable; update: boolean }) => {
    modalLoading(true);
    const { record, update } = data;
    isUpdate.value = update;
    await initDeptSelect();
    if (update && record) {
      const ret = await relevancyCodeInfo(record.id);
      await setFieldsValue(ret);
    }
    modalLoading(false);
  }
);
/**
 * 初始化部门选择
 */
async function initDeptSelect() {
  // updateSchema
  const deptTree = await departmentTree();
  // 选中后显示在输入框的值 即父节点 / 子节点
  addFullName(deptTree, "label", " / ");
  await updateSchema([
    {
      field: "deptId",
      componentProps: ({ formModel }) => ({
        treeData: deptTree,
        fieldNames: { value: "id", label: "label" },
        treeDefaultExpandAll: true,
        treeLine: { showLeafIcon: false },
        // 选中后显示在输入框的值
        treeNodeLabelProp: "fullName",
        async onSelect(deptId: string | number) {
          /** 根据部门ID加载岗位 */
          const postListResp = await postOptionSelect(deptId);
          postList.value = postListResp;
          /** 变化后需要重新选择岗位 */
          formModel.postIds = [];
        },
      }),
    },
  ]);
}
const [registerForm, { setFieldsValue, resetForm, validate, updateSchema }] = useForm({
  labelWidth: 150,
  showActionButtonGroup: false,
  baseColProps: { span: 12 },
  schemas: modalSchemas,
});

async function handleSubmit() {
  try {
    modalLoading(true);
    const data = await validate();
    if (unref(isUpdate)) {
      await relevancyCodeUpdate(data);
    } else {
      await relevancyCodeAdd(data);
    }
    emit("reload");
    closeModal();
    await resetForm();
  } catch (e) {
    console.warn(e);
  } finally {
    modalLoading(false);
  }
}
</script>

<style scoped></style>
