<script lang="ts" setup>
import type { Recordable } from '@vben/types';

import type { VbenFormSchema } from '#/adapter/form';

import { computed, reactive, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { ElMessage } from 'element-plus';

import { useVbenForm, z } from '#/adapter/form';
import { auditOrdersApi, getOrdersDetailApi } from '#/api/orders';

interface Emits {
  (event: 'finish'): void;
}

const emit = defineEmits<Emits>();

// 存储行数据
const auditData = ref<null | Recordable<any>>(null);

// 本地ref跟踪审核状态，用于条件逻辑
const currentOrdsesshzt = ref<number | undefined>(undefined);

const computedSchema = computed<VbenFormSchema[]>(() => {
  const schemas: VbenFormSchema[] = [
    {
      label: '订单ID',
      fieldName: 'ordersid',
      component: 'Input',
      componentProps: {
        disabled: true,
      },
    },
    {
      label: '优惠劵id',
      fieldName: 'ordersnumber',
      component: 'Input',
      componentProps: {
        disabled: true,
      },
    },
    {
      label: '产品名称',
      fieldName: 'ordersproductname',
      component: 'Input',
      componentProps: {
        disabled: true,
      },
    },
    {
      label: '审核状态',
      fieldName: 'ordersorderstatus',
      component: 'RadioGroup',
      componentProps: {
        options: [
          { label: '审核通过', value: 2 },
          { label: '审核不通过', value: 3 },
        ],
        onChange: (value: number | undefined) => {
          currentOrdsesshzt.value = value;
        },
      },
      defaultValue: 2,
      rules: z
        .number({
          invalid_type_error: '请选择审核状态',
          required_error: '请选择审核状态',
        })
        .refine((val) => val === 2 || val === 3, { message: '请选择审核状态' }),
    },
    {
      label: '审核备注',
      fieldName: 'ordersshbz',
      component: 'Input',
      // @ts-ignore ifShow在运行时工作，但类型可能缺失
      ifShow: ({ values }: { values: Recordable<any> }) =>
        values.ordersorderstatus === 3,
      componentProps: {
        type: 'textarea',
        placeholder: '请输入审核备注',
        rows: 3,
      },
      rules:
        currentOrdsesshzt.value === 2
          ? z.string().min(1, { message: '审核不通过时，审核备注不能为空' })
          : z.string().optional(),
    },
  ];
  return schemas;
});

const [AuditVForm, auditFormApi] = useVbenForm(
  reactive({
    schema: computedSchema,
    showDefaultActions: false,
  }),
);

async function internalHandleSubmit() {
  const validationResult = await auditFormApi.validate();
  if (!validationResult.valid) {
    return false;
  }
  try {
    const formValues = await auditFormApi.getValues();
    const dataToSubmit = {
      'ordersid.value': auditData.value?.ordersid,
      ordersshbz: formValues.ordersshbz,
      ordersorderstatus: formValues.ordersorderstatus,
    };
    await auditOrdersApi(dataToSubmit as any);
    ElMessage.success('审核操作成功');
    emit('finish');
    return true;
  } catch (error) {
    console.error('表单提交失败', error);
    ElMessage.error('审核操作失败');
    return false;
  }
}

const [Modal, modalApi] = useVbenModal({
  title: '审核订单',
  showCancelButton: true,
  fullscreenButton: false,
  closeOnClickModal: false,
  closeOnPressEscape: false,
  async onConfirm() {
    const success = await internalHandleSubmit();
    if (success) {
      modalApi.close();
    }
  },
  onCancel() {
    modalApi.close();
  },
  async onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const modalData = modalApi.getData();
      auditData.value = modalData?.row || {}; // 存储行数据
      currentOrdsesshzt.value = undefined;
      auditFormApi.resetForm({ values: {} });

      if (auditData.value?.ordersid) {
        try {
          const detailData = await getOrdersDetailApi({
            ordersid: auditData.value.ordersid,
          });
          const initialValues = { ...auditData.value, ...detailData };
          delete initialValues.ordersorderstatus;
          delete initialValues.ordersshbz;
          auditFormApi.setValues(initialValues);
          auditFormApi.setValues({
            ordersorderstatus: undefined,
            ordersshbz: '',
          });
          currentOrdsesshzt.value = undefined;
        } catch (error) {
          console.error('获取订单详情失败', error);
          auditFormApi.resetForm({ values: {} });
          currentOrdsesshzt.value = undefined;
        }
      } else {
        auditFormApi.resetForm({ values: {} });
        currentOrdsesshzt.value = undefined;
      }
    } else {
      // 关闭弹窗时清除数据
      auditData.value = null;
      currentOrdsesshzt.value = undefined;
      auditFormApi.resetForm({ values: {} });
    }
  },
});

function openAuditModal(rowData: Recordable<any>) {
  modalApi.setData({ row: rowData });
  modalApi.open();
}

defineExpose({
  openAuditModal,
});
</script>

<template>
  <Modal>
    <AuditVForm />
  </Modal>
</template>
