<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 {
  auditCoupon2Api,
  getCoupon2AuditDetailApi,
} from '#/api/coupon/coupon2';

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

const emit = defineEmits<Emits>();

// To store the row data when modal opens
const auditData = ref<null | Recordable<any>>(null);

// Local ref to track coupon2sype for conditional logic in schema
const currentCoupon2Sype = ref<number | undefined>(undefined);

const computedSchema = computed<VbenFormSchema[]>(() => {
  const schemas: VbenFormSchema[] = [
    {
      label: '优惠券ID',
      fieldName: 'coupon2sid',
      component: 'Input',
      componentProps: {
        disabled: true,
      },
    },
    {
      label: '优惠券代码',
      fieldName: 'coupon2code',
      component: 'Input',
      componentProps: {
        disabled: true,
      },
    },
    {
      label: '审核状态',
      fieldName: 'coupon2sype',
      component: 'RadioGroup',
      componentProps: {
        options: [
          { label: '审核通过', value: 1 },
          { label: '审核不通过', value: 2 },
        ],
        onChange: (value: number | undefined) => {
          currentCoupon2Sype.value = value;
        },
      },
      defaultValue: 1,
      rules: z
        .number({
          invalid_type_error: '请选择审核状态',
          required_error: '请选择审核状态',
        })
        .refine((val) => val === 1 || val === 2, { message: '请选择审核状态' }),
    },
    {
      label: '审核备注',
      fieldName: 'coupon2shbz',
      component: 'Input',
      // @ts-ignore ifShow is working in runtime but type might be missing
      ifShow: ({ values }: { values: Recordable<any> }) =>
        values.coupon2sype === 2,
      componentProps: {
        type: 'textarea',
        placeholder: '请输入审核备注',
        rows: 3,
      },
      rules:
        currentCoupon2Sype.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 = {
      'coupon2sid.value': auditData.value?.coupon2sid,
      coupon2shbz: formValues.coupon2shbz,
      coupon2sype: formValues.coupon2sype,
    };
    await auditCoupon2Api(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 || {}; // Store the row data
      currentCoupon2Sype.value = undefined;
      auditFormApi.resetForm({ values: {} });

      if (auditData.value?.coupon2sid) {
        try {
          const detailData = await getCoupon2AuditDetailApi({
            coupon2sid: auditData.value.coupon2sid,
          });
          const initialValues = { ...auditData.value, ...detailData };
          delete initialValues.coupon2sype;
          delete initialValues.coupon2shbz;
          auditFormApi.setValues(initialValues);
          auditFormApi.setValues({ coupon2sype: undefined, coupon2shbz: '' });
          currentCoupon2Sype.value = undefined;
        } catch (error) {
          console.error('Failed to fetch coupon details for audit', error);
          auditFormApi.resetForm({ values: {} });
          currentCoupon2Sype.value = undefined;
        }
      } else {
        auditFormApi.resetForm({ values: {} });
        currentCoupon2Sype.value = undefined;
      }
    } else {
      // Clear data when modal closes
      auditData.value = null;
      currentCoupon2Sype.value = undefined;
      auditFormApi.resetForm({ values: {} });
    }
  },
});

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

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

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