<template>
    <a-modal :open="modal.open" :title="modal.title" :confirm-loading="modal.confirmLoading" :after-close="onAfterClose"
        @ok="handleOk" @cancel="handleCancel">
        <a-card>
            <a-form ref="formRef" scroll-to-first-error :model="formData" :rules="formRules">
                <a-form-item label="算力点" name="point">
                    <a-input-number v-model:value="formData.point" :precision="2" style="width: 100%;"></a-input-number>
                </a-form-item>
            </a-form>
        </a-card>
    </a-modal>
</template>

<script setup>
import { cloneDeep } from 'lodash-es'
import apis from '@/apis'
import { useForm, useModal } from '@/hooks'

const emit = defineEmits(['ok'])

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

formRules.value = {
    point: { required: true, message: '请输入算力点' }
}

/**
 * 新建
 */
function handleCreate() {
    showModal({
        type: 'create',
        title: '新增算力点',
    })
}

/**
 * 编辑
 */
function handleEdit(record = {}) {
    showModal({
        type: 'edit',
        title: '新增算力点',
    })
    formRecord.value.userId = record.userId
    formData.value = cloneDeep(record)
}

/**
 * 确定
 */
function handleOk() {
    formRef.value
        .validateFields()
        .then(async (values) => {
            try {
                showLoading()
                const params = {
                    ...formData.value,
                }
                let result = null
                switch (modal.value.type) {
                    case 'create':
                        result = await apis.vouchers.addPoint(params).catch(() => {
                            throw new Error()
                        })
                        break
                    case 'edit':
                        result = await apis.vouchers.addPoint(params).catch(() => {
                            throw new Error()
                        })
                        break
                }
                hideLoading()
                if (200 === result?.code) {
                    hideModal()
                    emit('ok')
                }
            } catch (error) {
                hideLoading()
            }
        })
        .catch(() => {
            hideLoading()
        })
}

/**
 * 取消
 */
function handleCancel() {
    hideModal()
}

/**
 * 关闭后
 */
function onAfterClose() {
    resetForm()
}

defineExpose({
    handleCreate,
    handleEdit,
})
</script>

<style lang="less" scoped></style>
