<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    destroyOnClose
    :title="title"
    :width="MODAL_WIDTH"
    :maxHeight="modalContentMaxHeight"
    wrap-class-name="mes-xsl-equipment-ledger-modal"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm">
      <template #processOperationPicker="{ 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="openProcessSelect">选择</a-button>
          <a-button v-if="model.processOperationId && !isDetail" @click="clearProcess(model)">清除</a-button>
        </a-input-group>
      </template>
      <template #manufacturerPicker="{ 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="openManufacturerSelect('manufacturer')">选择</a-button>
          <a-button v-if="model.manufacturerId && !isDetail" @click="clearManufacturer(model)">清除</a-button>
        </a-input-group>
      </template>
      <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(model)">清除</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" @click="openTypeSelect">选择</a-button>
          <a-button v-if="model.equipmentTypeId && !isDetail" @click="clearType(model)">清除</a-button>
        </a-input-group>
      </template>
      <template #factoryPicker="{ 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="openManufacturerSelect('factory')">选择</a-button>
          <a-button v-if="model.factoryId && !isDetail" @click="clearFactory(model)">清除</a-button>
        </a-input-group>
      </template>
    </BasicForm>
    <MesXslProcessOperationSelectModal @register="registerProcessModal" @select="onProcessSelect" />
    <MesXslManufacturerSelectModal
      @register="registerManufacturerModal"
      :modal-title="manufacturerModalTitle"
      @select="onManufacturerSelect"
    />
    <MesXslEquipmentCategorySelectModal @register="registerCategoryModal" @select="onCategorySelect" />
    <MesXslEquipmentTypeSelectModal @register="registerTypeModal" @select="onTypeSelect" />
  </BasicModal>
</template>

<script lang="ts" setup>
  import { computed, ref, unref, onMounted } from 'vue';
  import { BasicModal, useModalInner, useModal } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from '../MesXslEquipmentLedger.data';
  import { fetchNextLedgerNo, saveOrUpdate } from '../MesXslEquipmentLedger.api';
  import MesXslProcessOperationSelectModal from '/@/views/xslmes/mesXslEquipmentCategory/components/MesXslProcessOperationSelectModal.vue';
  import MesXslManufacturerSelectModal from './MesXslManufacturerSelectModal.vue';
  import MesXslEquipmentCategorySelectModal from '/@/views/xslmes/mesXslEquipmentType/components/MesXslEquipmentCategorySelectModal.vue';
  import MesXslEquipmentTypeSelectModal from './MesXslEquipmentTypeSelectModal.vue';

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

  /** 弹窗宽度；须配合 wrap-class-name 覆盖全局 .ant-modal{width:520px} */
  const MODAL_WIDTH = 1200;

  /** 仅纵向滚动（像素高度，供 ModalWrapper 使用）；在基准高度上缩短 20% */
  const MODAL_HEIGHT_SCALE = 0.8;
  const modalContentMaxHeight = ref(Math.round(600 * MODAL_HEIGHT_SCALE));

  onMounted(() => {
    const base = Math.min(800, Math.max(480, window.innerHeight - 220));
    modalContentMaxHeight.value = Math.round(base * MODAL_HEIGHT_SCALE);
  });
  const manufacturerPickTarget = ref<'manufacturer' | 'factory'>('manufacturer');

  const manufacturerModalTitle = computed(() =>
    manufacturerPickTarget.value === 'factory' ? '选择所属工厂' : '选择设备厂家',
  );

  const [registerProcessModal, { openModal: openProcessModal }] = useModal();
  const [registerManufacturerModal, { openModal: openManufacturerModal }] = useModal();
  const [registerCategoryModal, { openModal: openCategoryModal }] = useModal();
  const [registerTypeModal, { openModal: openTypeModal }] = useModal();

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

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    await resetFields();
    setModalProps({
      width: MODAL_WIDTH,
      confirmLoading: false,
      showCancelBtn: data?.showFooter,
      showOkBtn: data?.showFooter,
    });
    isUpdate.value = !!data?.isUpdate;
    isDetail.value = !data?.showFooter;
    if (unref(isUpdate)) await setFieldsValue({ ...data.record });
    else {
      try {
        const nextNo = await fetchNextLedgerNo();
        await setFieldsValue({ equipmentStatus: '0', enabledFlag: '1', ledgerNo: nextNo });
      } catch {
        await setFieldsValue({ equipmentStatus: '0', enabledFlag: '1', ledgerNo: '' });
      }
    }
    setProps({ disabled: !data?.showFooter });
  });

  const title = computed(() =>
    !unref(isUpdate) ? '新增设备台账' : unref(isDetail) ? '设备台账详情' : '编辑设备台账',
  );

  function openProcessSelect() {
    const v = getFieldsValue();
    openProcessModal(true, { processOperationId: v?.processOperationId });
  }

  function openManufacturerSelect(target: 'manufacturer' | 'factory') {
    manufacturerPickTarget.value = target;
    const v = getFieldsValue();
    openManufacturerModal(true, {
      manufacturerId: target === 'factory' ? v?.factoryId : v?.manufacturerId,
    });
  }

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

  function openTypeSelect() {
    const v = getFieldsValue();
    openTypeModal(true, { equipmentTypeId: v?.equipmentTypeId });
  }

  function onProcessSelect(payload: Recordable) {
    setFieldsValue({
      processOperationId: payload.processOperationId,
      processOperationName: payload.processOperationName,
    });
  }

  function onManufacturerSelect(payload: Recordable) {
    if (manufacturerPickTarget.value === 'factory') {
      setFieldsValue({
        factoryId: payload.manufacturerId,
        factoryName: payload.manufacturerName,
      });
    } else {
      setFieldsValue({
        manufacturerId: payload.manufacturerId,
        manufacturerName: payload.manufacturerName,
      });
    }
  }

  function onCategorySelect(payload: Recordable) {
    setFieldsValue({
      equipmentCategoryId: payload.equipmentCategoryId,
      equipmentCategoryName: payload.equipmentCategoryName,
    });
  }

  function onTypeSelect(payload: Recordable) {
    setFieldsValue({
      equipmentTypeId: payload.equipmentTypeId,
      equipmentTypeName: payload.equipmentTypeName,
      equipmentCategoryId: payload.equipmentCategoryId || getFieldsValue()?.equipmentCategoryId,
      equipmentCategoryName: payload.equipmentCategoryName || getFieldsValue()?.equipmentCategoryName,
    });
  }

  function clearProcess(model: Recordable) {
    model.processOperationId = '';
    model.processOperationName = '';
  }

  function clearManufacturer(model: Recordable) {
    model.manufacturerId = '';
    model.manufacturerName = '';
  }

  function clearFactory(model: Recordable) {
    model.factoryId = '';
    model.factoryName = '';
  }

  function clearCategory(model: Recordable) {
    model.equipmentCategoryId = '';
    model.equipmentCategoryName = '';
  }

  function clearType(model: Recordable) {
    model.equipmentTypeId = '';
    model.equipmentTypeName = '';
  }

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

<style lang="less">
  /* 覆盖 jeecg components/Modal/src/index.less 中 .ant-modal { width: 520px } */
  .ant-modal-wrap.mes-xsl-equipment-ledger-modal > .ant-modal,
  .mes-xsl-equipment-ledger-modal .ant-modal {
    width: min(1200px, calc(100vw - 48px)) !important;
    max-width: min(1200px, calc(100vw - 48px)) !important;
  }

  .mes-xsl-equipment-ledger-modal {

    .scroll-container .scrollbar__wrap {
      overflow-x: hidden !important;
      overflow-y: auto !important;
    }

    .scrollbar__view > div {
      overflow-x: hidden;
    }
  }
</style>
