<template>
  <BasicModal @register="registerModal" :title="title" width="800" v-bind="$attrs" destroyOnClose @ok="handleSubmit">
    <BasicForm @register="registerForm">
      <template #equipmentCategoryPicker="{ model, field }">
        <a-input-group compact style="display: flex; width: 100%">
          <a-input v-model:value="model[field]" read-only placeholder="请选择设备类别" style="flex: 1" />
          <a-button type="primary" :disabled="isDetail" @click="openCategorySelect">选择</a-button>
          <a-button v-if="model.equipmentCategoryId && !isDetail" @click="clearCategory">清除</a-button>
        </a-input-group>
      </template>
      <template #equipmentTypePicker="{ model, field }">
        <a-input-group compact style="display: flex; width: 100%">
          <a-input v-model:value="model[field]" read-only placeholder="请先选类别，再选类型" style="flex: 1" />
          <a-button type="primary" :disabled="isDetail || !model.equipmentCategoryId" @click="openTypeSelect">选择</a-button>
          <a-button v-if="model.equipmentTypeId && !isDetail" @click="clearType">清除</a-button>
        </a-input-group>
      </template>
      <template #equipmentPartPicker="{ model, field }">
        <a-input-group compact style="display: flex; width: 100%">
          <a-input v-model:value="model[field]" read-only placeholder="请先选类别，再选部位" style="flex: 1" />
          <a-button type="primary" :disabled="isDetail || !model.equipmentCategoryId" @click="openPartSelect">选择</a-button>
          <a-button v-if="model.equipmentPartId && !isDetail" @click="clearPart">清除</a-button>
        </a-input-group>
      </template>
      <template #equipmentSubPartPicker="{ model, field }">
        <a-input-group compact style="display: flex; width: 100%">
          <a-input v-model:value="model[field]" read-only placeholder="请先选类别与部位，再选小部位" style="flex: 1" />
          <a-button
            type="primary"
            :disabled="isDetail || !model.equipmentCategoryId || !model.equipmentPartId"
            @click="openSubPartSelect"
          >
            选择
          </a-button>
          <a-button v-if="model.equipmentSubPartId && !isDetail" @click="clearSubPart">清除</a-button>
        </a-input-group>
      </template>
    </BasicForm>
    <MesXslEquipmentCategorySelectModal @register="registerCategoryModal" @select="onCategorySelect" />
    <MesXslEquipmentTypeFilterSelectModal @register="registerTypeModal" @select="onTypeSelect" />
    <MesXslEquipmentPartSelectModal @register="registerPartModal" @select="onPartSelect" />
    <MesXslEquipmentSubPartFilterSelectModal @register="registerSubPartModal" @select="onSubPartSelect" />
  </BasicModal>
</template>

<script lang="ts" setup>
  import { computed, ref, unref } from 'vue';
  import { BasicModal, useModalInner, useModal } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { formSchema } from '../MesXslInspectMaintainItem.data';
  import { saveOrUpdate } from '../MesXslInspectMaintainItem.api';
  import MesXslEquipmentCategorySelectModal from '/@/views/xslmes/mesXslEquipmentType/components/MesXslEquipmentCategorySelectModal.vue';
  import MesXslEquipmentPartSelectModal from '/@/views/xslmes/mesXslEquipmentSubPart/components/MesXslEquipmentPartSelectModal.vue';
  import MesXslEquipmentTypeFilterSelectModal from './MesXslEquipmentTypeFilterSelectModal.vue';
  import MesXslEquipmentSubPartFilterSelectModal from './MesXslEquipmentSubPartFilterSelectModal.vue';

  const emit = defineEmits(['register', 'success']);
  const { createMessage } = useMessage();
  const isUpdate = ref(true);
  const isDetail = ref(false);

  const [registerCategoryModal, { openModal: openCategoryModal }] = useModal();
  const [registerTypeModal, { openModal: openTypeModal }] = useModal();
  const [registerPartModal, { openModal: openPartModal }] = useModal();
  const [registerSubPartModal, { openModal: openSubPartModal }] = useModal();

  const [registerForm, { resetFields, setFieldsValue, validate, setProps, getFieldsValue }] = useForm({
    labelWidth: 120,
    schemas: formSchema,
    showActionButtonGroup: false,
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    await resetFields();
    setModalProps({ confirmLoading: false, showCancelBtn: data?.showFooter, showOkBtn: data?.showFooter });
    isUpdate.value = !!data?.isUpdate;
    isDetail.value = !data?.showFooter;
    if (unref(isUpdate)) {
      await setFieldsValue({ ...data.record });
    }
    setProps({ disabled: !data?.showFooter });
  });

  const title = computed(() =>
    !unref(isUpdate) ? '新增点检及保养项目' : unref(isDetail) ? '点检及保养项目详情' : '编辑点检及保养项目',
  );

  function clearEquipmentCascade(from: 'category' | 'type' | 'part') {
    const patch: Recordable = {};
    if (from === 'category') {
      patch.equipmentTypeId = '';
      patch.equipmentTypeName = '';
      patch.equipmentPartId = '';
      patch.equipmentPartName = '';
      patch.equipmentSubPartId = '';
      patch.equipmentSubPartName = '';
    } else if (from === 'type') {
      patch.equipmentTypeId = '';
      patch.equipmentTypeName = '';
    } else if (from === 'part') {
      patch.equipmentPartId = '';
      patch.equipmentPartName = '';
      patch.equipmentSubPartId = '';
      patch.equipmentSubPartName = '';
    }
    setFieldsValue(patch);
  }

  function openCategorySelect() {
    const vals = getFieldsValue();
    openCategoryModal(true, { equipmentCategoryId: vals.equipmentCategoryId });
  }

  function clearCategory() {
    setFieldsValue({
      equipmentCategoryId: '',
      equipmentCategoryName: '',
    });
    clearEquipmentCascade('category');
  }

  function onCategorySelect(payload: { equipmentCategoryId?: string; equipmentCategoryName?: string }) {
    setFieldsValue({
      equipmentCategoryId: payload.equipmentCategoryId || '',
      equipmentCategoryName: payload.equipmentCategoryName || '',
    });
    clearEquipmentCascade('category');
  }

  function openTypeSelect() {
    const vals = getFieldsValue();
    if (!vals.equipmentCategoryId) {
      createMessage.warning('请先选择设备类别');
      return;
    }
    openTypeModal(true, {
      equipmentCategoryId: vals.equipmentCategoryId,
      equipmentTypeId: vals.equipmentTypeId,
    });
  }

  function clearType() {
    clearEquipmentCascade('type');
  }

  function onTypeSelect(payload: { equipmentTypeId?: string; equipmentTypeName?: string }) {
    setFieldsValue({
      equipmentTypeId: payload.equipmentTypeId || '',
      equipmentTypeName: payload.equipmentTypeName || '',
    });
  }

  function openPartSelect() {
    const vals = getFieldsValue();
    if (!vals.equipmentCategoryId) {
      createMessage.warning('请先选择设备类别');
      return;
    }
    openPartModal(true, {
      equipmentCategoryId: vals.equipmentCategoryId,
      equipmentPartId: vals.equipmentPartId,
    });
  }

  function clearPart() {
    clearEquipmentCascade('part');
  }

  function onPartSelect(payload: { equipmentPartId?: string; equipmentPartName?: string }) {
    setFieldsValue({
      equipmentPartId: payload.equipmentPartId || '',
      equipmentPartName: payload.equipmentPartName || '',
      equipmentSubPartId: '',
      equipmentSubPartName: '',
    });
  }

  function openSubPartSelect() {
    const vals = getFieldsValue();
    if (!vals.equipmentCategoryId) {
      createMessage.warning('请先选择设备类别');
      return;
    }
    if (!vals.equipmentPartId) {
      createMessage.warning('请先选择设备部位');
      return;
    }
    openSubPartModal(true, {
      equipmentCategoryId: vals.equipmentCategoryId,
      equipmentPartId: vals.equipmentPartId,
      equipmentSubPartId: vals.equipmentSubPartId,
    });
  }

  function clearSubPart() {
    setFieldsValue({ equipmentSubPartId: '', equipmentSubPartName: '' });
  }

  function onSubPartSelect(payload: { equipmentSubPartId?: string; equipmentSubPartName?: string }) {
    setFieldsValue({
      equipmentSubPartId: payload.equipmentSubPartId || '',
      equipmentSubPartName: payload.equipmentSubPartName || '',
    });
  }

  async function handleSubmit() {
    const values = await validate();
    setModalProps({ confirmLoading: true });
    try {
      await saveOrUpdate(values, isUpdate.value);
      closeModal();
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
