<template>
  <BasicModal
    v-bind="$attrs"
    :title="title"
    @register="registerInnerModal"
    @ok="handleSubmit"
    @cancel="resetForm"
    :width="1200"
  >
    <template #footer>
      <div v-if="isUpdate !== 3">
        <a-button type="default" @click="handleCancle">取消</a-button>
        <a-button type="primary" @click="handleSubmit">确认</a-button>
      </div>
    </template>
    <BasicForm @register="registerForm">
      <template #getLatLng="{ model, field }"
        ><GetLatLng @getLatLng="getLatLng" v-model:isUpdate="isUpdate"></GetLatLng>
      </template>
    </BasicForm>
  </BasicModal>
</template>

<script setup lang="ts">
import { BasicModal, useModalInner } from "@/components/Modal";
import { BasicForm, useForm } from "@/components/Form";
import { computed, reactive, ref, unref } from "vue";
import { infoInfo, infoAdd, infoUpdate } from "@/api/basicInfo/elevator";
import { modalSchemas } from "./info.data";
import { GetLatLng } from "@/components/GetLatLng";
import { departmentTree } from "@/api/system/user";
import { addFullName } from "@/utils/helper/treeHelper";
import { postOptionSelect } from "@/api/system/post";
import { buildingInfoList } from "@/api/basicInfo/buildingsInfo";
import { houseInfoList } from "@/api/basicInfo/areaInfo";
import { employInfoList } from "@/api/basicInfo/userEmploy";
import { infoList } from "@/api/basicInfo/tenement";
import { maintenanceInfoList } from "@/api/basicInfo/maintenance";
defineOptions({ name: "InfoModal" });

const emit = defineEmits(["register", "reload"]);
const postList = ref<Post[]>([]);
const isUpdate = ref<number>(1);
const title = computed<string>(() => {
  return isUpdate.value === 1
    ? "编辑电梯基础信息;"
    : isUpdate.value === 2
    ? "新增电梯基础信息;"
    : "查看电梯基础信息";
});
const customTitle = ref<string>("选择小区");

const [registerInnerModal, { modalLoading, closeModal }] = useModalInner(
  async (data: { record?: Recordable; update: number }) => {
    modalLoading(true);
    const { record, update } = data;
    isUpdate.value = update;
    await initDeptSelect();
    await initBuildTree();
    await initHouseTree();
    await initEmployTree();
    await initTenementTree();
    await initMaintanceTree();
    if (isUpdate.value === 3) {
      setProps({ disabled: true });
    } else {
      setProps({ disabled: false });
    }
    if ((update === 1 || update === 3) && record) {
      const ret = await infoInfo(record.id);
      console.log(ret, "ret");
      // 确保useScenario转换为字符串类型，如果它原本是数字
      ret.useScenario =
        typeof ret.useScenario === "number" ? String(ret.useScenario) : ret.useScenario;
      ret.energyType =
        typeof ret.energyType === "number" ? String(ret.energyType) : ret.energyType;

      await setFieldsValue(ret);
    }
    modalLoading(false);
  }
);

async function initBuildTree() {
  await updateSchema([
    {
      field: "buildingId",
      component: "ApiSelect",
      componentProps: ({ formModel }) => ({
        api: buildingInfoList,
        labelInValue: true,
        labelField: "name",
        valueField: "id",
        placeholder: "请选择楼宇",
        afterFetch: (res) => {
          return res.rows;
        },
        onSelect: (e: any) => {
          console.log(e, "e");
          setFieldsValue({ buildingId: e.value, buildingName: e.label });
        },
      }),
    },
  ]);
}

async function initHouseTree() {
  await updateSchema([
    {
      field: "houseId",
      component: "ApiSelect",
      componentProps: ({ formModel }) => ({
        api: houseInfoList,
        labelInValue: true,
        labelField: "name",
        valueField: "id",
        placeholder: "请选择小区",
        afterFetch: (res) => {
          return res.rows;
        },
        onSelect: (e: any) => {
          console.log(e, "e");
          setFieldsValue({ houseId: e.value, houseName: e.label });
        },
      }),
    },
  ]);
}
async function initEmployTree() {
  await updateSchema([
    {
      field: "employId",
      component: "ApiSelect",
      componentProps: ({ formModel }) => ({
        api: employInfoList,
        labelInValue: true,
        labelField: "name",
        valueField: "id",
        placeholder: "请选择使用单位",
        afterFetch: (res) => {
          return res.rows;
        },
        onSelect: (e: any) => {
          console.log(e, "e");
          setFieldsValue({ employId: e.value, employName: e.label });
        },
      }),
    },
  ]);
}

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 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 });
        },
      }),
    },
  ]);
}
/**
 * 初始化部门选择
 */
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 = [];
        },
      }),
    },
  ]);
}

function handleCancle() {
  closeModal();
  resetForm();
}
const [
  registerForm,
  { setFieldsValue, resetForm, validate, updateSchema, setProps },
] = useForm({
  labelWidth: 200,
  showActionButtonGroup: false,
  baseColProps: { span: 12 },
  schemas: modalSchemas,
});
const getLatLng = (data) => {
  console.log(data, "data");
  setFieldsValue({ lat: data.lat, lng: data.lng });
};
async function handleSubmit() {
  try {
    modalLoading(true);
    const data = await validate();
    if (isUpdate.value === 1) {
      await infoUpdate(data);
    } else {
      await infoAdd(data);
    }
    emit("reload");
    closeModal();
    await resetForm();
  } catch (e) {
    console.warn(e);
  } finally {
    modalLoading(false);
  }
}
</script>

<style scoped></style>
