<template>
    <a-modal :open="modal.open" :title="modal.title" :confirm-loading="modal.confirmLoading" :after-close="onAfterClose"
        @ok="handleOk" @cancel="handleCancel" width="800px">
        <a-card>
            <div style="width: 100%;text-align: right;">
                <a-button type="primary" style="margin-bottom: 10px;"
                    @click="$refs.computeDialogRef.handleCreate(record)">添加</a-button>
            </div>
            <a-table :columns="columns" :data-source="listData" :loading="loading" bordered
                :pagination="paginationState" :scroll="{ x: 1000 }" row-key="id" @change="onTableChange">
                <template #bodyCell="{ column, record }">
                    <template v-if="'action' === column.key">
                        <x-action-button @click="$refs.computeDialogRef.handleEdit(record)">编辑</x-action-button>
                        <x-action-button @click="handleDelete(record)"><span
                                style="color: red;">删除</span></x-action-button>
                    </template>
                </template>
            </a-table>
        </a-card>
        <compute-dialog ref="computeDialogRef" @ok="onComputeOk" />
    </a-modal>
</template>

<script setup>
import { cloneDeep } from 'lodash-es'
import apis from '@/apis'
import { useForm, useModal } from '@/hooks'
import { ref } from 'vue'
import ComputeDialog from './ComputeDialog.vue'
import dayjs from 'dayjs'
import { message, Modal } from 'ant-design-vue'
const emit = defineEmits(['ok'])
const { modal, showModal, hideModal, showLoading, hideLoading } = useModal()
const { formRef, formRules, formRecord, formData, resetForm } = useForm()
const listData = ref([])
formData.value.computingCards = []
const computeDialogRef = ref()
formRules.value = {
    // name: { required: true, message: '请输入标题' },
}
const columns = [
    {
        title: '地区ID',
        dataIndex: 'centerID',
        key: 'centerID',
        width: 100,
    },
    {
        title: '核心数',
        dataIndex: 'coreNum',
        key: 'coreNum',
        align: 'center',
        width: 100,
    },
    {
        title: 'GPU数量',
        dataIndex: 'gpuNum',
        key: 'gpuNum',
        align: 'center',
        width: 100,
    },
    {
        title: 'GPU类型',
        dataIndex: 'gpuType',
        key: 'gpuType',
        width: 100,
    },
    {
        title: '主机ID',
        dataIndex: 'hostID',
        key: 'hostID',
        width: 100,
    },
    {
        title: '显存 (GB)',
        dataIndex: 'vram',
        key: 'vram',
        align: 'center',
        width: 120,
        customRender: ({ value }) => (value !== undefined ? `${value} GB` : '-'),
    },
    {
        title: '是否使用',
        dataIndex: 'isUse',
        key: 'isUse',
        align: 'center',
        width: 100,
        customRender: ({ value }) => (value ? '是' : '否'),
    },
    {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        width: 120,
        customRender: ({ value }) => {
            if (value === 'active') return '启用';
            if (value === 'inactive') return '停用';
            return value || '-';
        },
    },
    {
        title: '描述',
        dataIndex: 'description',
        key: 'description',
        ellipsis: true,
        width: 200,
    },
    { title: '操作', key: 'action', width: 120, fixed: 'right', },
]

/**
 * 新建
 */
function handleCreate(record = {}) {
    showModal({
        type: 'create',
        title: '计算卡列表',
    })
    formRecord.value.hostId = record.id
    getDataList()
}
function getDataList() {
    try {
        apis.host.getComputeCardList().then((res) => {
            if (true === res.success) {
                listData.value = res.data
            }
        })
    } catch (error) {
    }
}
/**
 * 编辑
 */
function handleEdit(record = {}) {
    showModal({
        type: 'edit',
        title: '编辑',
    })
    formRecord.value = record
    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.host.createComputeCard(params).catch(() => {
                            throw new Error()
                        })
                        break
                    case 'edit':
                        result = await apis.host.updatePage(formRecord.value.id, params).catch(() => {
                            throw new Error()
                        })
                        break
                }
                hideLoading()
                if (true === result?.success) {
                    hideModal()
                    emit('ok')
                }
            } catch (error) {
                hideLoading()
            }
        })
        .catch(() => {
            hideLoading()
        })
}

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

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

/**
 * 删除
 */
function handleDelete({ id }) {
    Modal.confirm({
        title: '删除提示',
        content: '确认删除？',
        onOk: () => {
            return new Promise((resolve, reject) => {
                ; (async () => {
                    try {
                        const { code } = await apis.host.delComputeCard(id).catch(() => {
                            throw new Error()
                        })
                        if (config('http.code.success') === code) {
                            resolve()
                            message.success('删除成功')
                            await getDataList()
                        }
                    } catch (error) {
                        reject()
                    }
                })()
            })
        },
    })
}
defineExpose({
    handleCreate,
    handleEdit,
})
</script>

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