<template>
  <BasicModal
    v-bind="$attrs"
    :title="title"
    @register="registerInnerModal"
    @ok="handleSubmit"
    @cancel="resetForm"
    :width="1200"
  >
    <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 {
  elevatorRelevancyDeviceInfo,
  elevatorRelevancyDeviceAdd,
  elevatorRelevancyDeviceUpdate,
} from "@/api/basicInfo/evaDeviceRelation";
import { modalSchemas } from "./elevatorRelevancyDevice.data";
import { maintenanceInfoList } from "@/api/basicInfo/maintenance";
import { infoList } from "@/api/basicInfo/tenement";
defineOptions({ name: "ElevatorRelevancyDeviceModal" });
import { departmentTree } from "@/api/system/user";
import { addFullName } from "@/utils/helper/treeHelper";
import { postOptionSelect } from "@/api/system/post";
const postList = ref<Post[]>([]);
const emit = defineEmits(["register", "reload"]);

const isUpdate = ref<number>(1);
const title = computed<string>(() => {
  return isUpdate.value === 1
    ? "编辑电梯设备关联;"
    : isUpdate.value === 2
    ? "新增电梯设备关联;"
    : "查看电梯设备关联";
});
async function initTenementTree() {
  await updateSchema([
    {
      field: "tenementId",
      component: "ApiSelect",
      componentProps: ({ formModel }) => ({
        api: infoList,
        labelInValue: true,
        labelField: "name",
        valueField: "id",
        placeholder: "请选择物业单位",
        afterFetch: (res) => {
          return res.rows;
        },
        onSelect: (e: any) => {
          console.log(e, "e");
          setFieldsValue({ tenementId: e.value, tenementName: e.label });
        },
      }),
    },
  ]);
}
/**
 * 初始化部门选择
 */
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 = [];
        },
      }),
    },
  ]);
}
async function initMaintanceTree() {
  await updateSchema([
    {
      field: "maintenanceId",
      component: "ApiSelect",
      componentProps: ({ formModel }) => ({
        api: maintenanceInfoList,
        labelInValue: true,
        labelField: "name",
        valueField: "id",
        placeholder: "请选择维保单位",
        afterFetch: (res) => {
          return res.rows;
        },
        onSelect: (e: any) => {
          console.log(e, "e");
          setFieldsValue({ maintenanceId: e.value, maintenanceName: e.label });
        },
      }),
    },
  ]);
}
const [registerInnerModal, { modalLoading, closeModal }] = useModalInner(
  async (data: { record?: Recordable; update: number }) => {
    modalLoading(true);
    const { record, update } = data;
    isUpdate.value = update;
    await initTenementTree();
    await initMaintanceTree();
    await initDeptSelect();
    if (isUpdate.value === 3) {
      setProps({ disabled: true });
    } else {
      setProps({ disabled: false });
    }
    if ((update === 1 || update === 3) && record) {
      const ret = await elevatorRelevancyDeviceInfo(record.id);
      await setFieldsValue(ret);
    }
    modalLoading(false);
  }
);

const [
  registerForm,
  { setFieldsValue, resetForm, validate, setProps, updateSchema },
] = useForm({
  labelWidth: 150,
  showActionButtonGroup: false,
  baseColProps: { span: 12 },
  schemas: modalSchemas,
});

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

<style scoped></style>
