<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 {
  elevatorRelevancyDeviceInfo,
  elevatorRelevancyDevice,
  elevatorRelevancyDeviceAdd,
  elevatorRelevancyDeviceUpdate,
} from "@/api/basicInfo/evaDeviceRelation";
import { modalRelationSchemas } from "./elevatorRelevancyDevice.data";

defineOptions({ name: "ElevatorRelevancyDeviceModal" });

const emit = defineEmits(["register", "reload"]);
const info = ref<any>({});
const isUpdate = ref<number>(1);
const title = computed<string>(() => {
  return "关联设备";
});

const [registerInnerModal, { modalLoading, closeModal }] = useModalInner(
  async (data: { record?: Recordable; update: number }) => {
    modalLoading(true);
    const { record, update } = data;
    isUpdate.value = update;
    info.value = record;
    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: 24 },
  schemas: modalRelationSchemas,
});

async function handleSubmit() {
  try {
    modalLoading(true);
    const data = await validate();
    const passData = {
      ...data,
      elevatorNum: info.value.elevatorNum,
    };
    await elevatorRelevancyDevice(passData);
    emit("reload");
    closeModal();
    await resetForm();
  } catch (e) {
    console.warn(e);
  } finally {
    modalLoading(false);
  }
}
</script>

<style scoped></style>
