<script setup lang="ts">
import { computed, ref } from 'vue';
import { $t } from '@vben/locales';
import { cloneDeep } from '@vben/utils';
import { useVbenModal, type VbenFormProps } from '@vben/common-ui';
import { useVbenForm } from '#/adapter/form';
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';
import {
  procurementApplicationUpdate,
  procurementApplicationInfo,
} from '#/api/property/assetManage/procurementApplication';
import type { ProcurementApplicationForm } from '#/api/property/assetManage/procurementApplication/model';

const emit = defineEmits<{ reload: [] }>();

const title = computed(() => '采购审批');

// 存储完整的申请数据
const fullApplicationData = ref<ProcurementApplicationForm>({});

const [BasicForm, formApi] = useVbenForm({
  commonConfig: {
    labelWidth: 80,
    componentProps: {
      class: 'w-full',
    },
  },
  schema: [
    {
      label: '审核状态',
      fieldName: 'state',
      component: 'RadioGroup',
      componentProps: {
        options: [
          { label: '通过', value: '1' },
          { label: '驳回', value: '2' },
        ],
      },
      rules: 'required',
    },
    {
      label: '审核意见',
      fieldName: 'auditOpinion',
      component: 'Textarea',
      componentProps: {
        rows: 4,
        placeholder: '请输入审核意见',
      },
      rules: 'required',
    },
  ],
  showDefaultActions: false,
  wrapperClass: 'grid-cols-1',
});

const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
  {
    initializedGetter: defaultFormValueGetter(formApi),
    currentGetter: defaultFormValueGetter(formApi),
  },
);

const [BasicModal, modalApi] = useVbenModal({
  class: 'w-[500px]',
  fullscreenButton: false,
  onBeforeClose,
  onClosed: handleClosed,
  onConfirm: handleConfirm,
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null;
    }
    modalApi.modalLoading(true);
    const { id } = modalApi.getData() as { id?: number | string };
    if (id) {
      // 获取完整的申请数据
      const record = await procurementApplicationInfo(id);
      fullApplicationData.value = cloneDeep(record);

      // 设置表单默认值
      await formApi.setValues({
        id,
        state: '',
        auditOpinion: '',
      });
    }
    await markInitialized();
    modalApi.modalLoading(false);
  },
});

async function handleConfirm() {
  try {
    modalApi.lock(true);
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }

    // 获取审核表单数据
    const auditData = await formApi.getValues();

    // 合并完整数据，只更新审核相关字段
    const updateData = {
      ...fullApplicationData.value,
      state: auditData.state,
      auditOpinion: auditData.auditOpinion,
    };

    await procurementApplicationUpdate(updateData);
    resetInitialized();
    emit('reload');
    modalApi.close();
  } catch (error) {
    console.error(error);
  } finally {
    modalApi.lock(false);
  }
}

async function handleClosed() {
  await formApi.resetForm();
  resetInitialized();
  fullApplicationData.value = {};
}
</script>

<template>
  <BasicModal :title="title">
    <BasicForm />
  </BasicModal>
</template>
