<template>
    <a-modal :open="modal.open" :title="modal.title" :width="640" :confirm-loading="modal.confirmLoading"
        :after-close="onAfterClose" :cancel-text="cancelText" :ok-text="okText" @ok="handleOk" @cancel="handleCancel">
        <a-form ref="formRef" :model="formData" :rules="formRules">
            <a-card class="mb-8-2">
                <a-row :gutter="24">
                    <a-col :span="24">
                        <a-form-item label="审核结果" name="check">
                            <a-radio-group v-model:value="formData.check" :options="[
                                { label: '通过', value: true },
                                { label: '不通过', value: false },
                            ]" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-item label="审核不通过理由" name="fail_reason">
                            <a-textarea v-model:value="formData.fail_reason" :disabled="formData.check === true" />
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-card>
        </a-form>
    </a-modal>
</template>

<script setup>
import { message } from 'ant-design-vue'
import { ref, computed } from 'vue'
import apis from '@/apis'
import { useForm, useModal } from '@/hooks'
import { useI18n } from 'vue-i18n'

const emit = defineEmits(['ok'])
const { t } = useI18n()

const { modal, showModal, hideModal, showLoading, hideLoading } = useModal()
const { formData, formRef, resetForm } = useForm()

const cancelText = ref(t('button.cancel'))
const okText = ref(t('button.confirm'))

// 初始化表单数据
formData.value = {
    check: true,
    fail_reason: '',
    id: null,
}

// 动态校验规则：使用 validator
const validateFailReason = (rule, value, callback) => {
    if (formData.value.check === false) {
        if (!value || value.trim() === '') {
            callback(new Error('请选择不通过时，必须填写不通过理由'))
        } else {
            callback()
        }
    } else {
        // 通过时不需要校验
        callback()
    }
}

// 表单规则
const formRules = computed(() => ({
    check: [{ required: true, message: '请选择审核结果' }],
    fail_reason: [{ validator: validateFailReason, trigger: 'blur' }],
}))

/**
 * 编辑（审核）
 */
async function handleEdit(id) {
    showModal({
        type: 'edit',
        title: '用户审核',
    })
    formData.value.id = id
    // 可选：如果需要回显原数据，可在此处调用 API 获取详情并赋值
    // 比如：formData.value = await fetchCertificationDetail(id)
}

/**
 * 确定
 */
async function handleOk() {
    try {
        await formRef.value.validateFields()
        showLoading()

        const params = {
            check: formData.value.check,
            fail_reason: formData.value.check ? null : formData.value.fail_reason?.trim(),
        }

        const result = await apis.certifications.updateCertifications(formData.value.id, params)

        hideLoading()
        if (result?.success) {
            message.success('操作成功')
            hideModal()
            emit('ok')
        }
    } catch (error) {
        hideLoading()
        // validateFields 失败会抛出异常，但已被 catch，无需额外处理
    }
}

function handleCancel() {
    hideModal()
}

function onAfterClose() {
    resetForm()
    // 重置表单数据（可选）
    formData.value = {
        check: true,
        fail_reason: '',
        id: null,
    }
}

defineExpose({
    handleEdit,
})
</script>