<template>
    <x-search-bar class="mb-8-2">
        <template #default="{ gutter, colSpan }">
            <a-form :model="searchFormData" layout="inline">
                <a-row :gutter="gutter">
                    <a-col v-bind="colSpan">
                        <a-form-item label="主机名称/ID" name="machine_name">
                            <a-input placeholder="请输入主机名称/ID" v-model:value="searchFormData.machine_name"></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col v-bind="colSpan">
                        <a-form-item label="内网IP" name="internal_ip">
                            <a-input placeholder="请输入内网IP" v-model:value="searchFormData.internal_ip"></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col class="align-right" v-bind="colSpan">
                        <a-space>
                            <a-button @click="handleResetSearch">重置</a-button>
                            <a-button ghost type="primary" @click="handleSearch">
                                搜索
                            </a-button>
                        </a-space>
                    </a-col>
                </a-row>
            </a-form>
        </template>
    </x-search-bar>
    <a-row :gutter="8" :wrap="false">
        <a-col flex="auto">
            <a-card type="flex">
                <a-table 
                    :columns="columns" :data-source="listData" :loading="loading" :pagination="paginationState"
                    :scroll="{ x: 1400 }"
                    @change="onTableChange">
                    <template #bodyCell="{ column, record }">
                        <!-- 健康状态 -->
                        <template v-if="'health_status' === column.key">
                            <a-tag :color="getHealthStatusColor(record.health_status)">
                                {{ getHealthStatusText(record.health_status) }}
                            </a-tag>
                        </template>

                        <!-- 状态 -->
                        <template v-if="'online_status' === column.key">
                            <a-tag :color="getOnlineStatusColor(record.online_status)">
                                {{ getOnlineStatusText(record.online_status) }}
                            </a-tag>
                        </template>

                        <!-- 主机配置 -->
                        <template v-if="'cpu_config' === column.key">
                            <div>{{ record.cpu_num }}核</div>
                            <div>{{ formatMemory(record.memory) }}</div>
                        </template>

                        <!-- 磁盘空间 -->
                        <template v-if="'disk_space' === column.key">
                            <div v-if="record.disks && record.disks.length > 0">
                                <div v-for="disk in record.disks" :key="disk.disk_path">
                                    {{ disk.disk_path }}: {{ formatDiskSpace(disk.idle) }}/{{ formatDiskSpace(disk.total) }}
                                </div>
                            </div>
                            <div v-else>无磁盘信息</div>
                        </template>

                        <!-- 硬件平台 -->
                        <template v-if="'hardware_platform' === column.key">
                            <div>{{ record.chip_corp?.toUpperCase() || 'NVIDIA' }}</div>
                            <div>{{ record.cpu_arch?.toUpperCase() || 'x86' }}</div>
                        </template>

                        <!-- 算力型号 -->
                        <template v-if="'gpu_info' === column.key">
                            <div>{{ record.gpu_name }}</div>
                            <div>driver={{ record.driver_version }}</div>
                            <div>cuda={{ record.cuda_version }}</div>
                        </template>

                        <!-- 空闲算力 -->
                        <template v-if="'gpu_idle' === column.key">
                            <div>{{ record.gpu?.idle || 0 }}/{{ record.gpu?.total || 0 }}</div>
                        </template>

                        <!-- CPU内存分配 -->
                        <template v-if="'cpu_mem_per_gpu' === column.key">
                            <div>{{ record.cpu_per_gpu }}核/GPU</div>
                            <div>{{ formatMemory(record.mem_per_gpu) }}/GPU</div>
                        </template>

                        <!-- 实例数量 -->
                        <template v-if="'instance_count' === column.key">
                            <div>{{ record.binding_instance_num || 0 }}</div>
                            <div v-if="record.machine_instance_limit > 0">
                                限额: {{ record.machine_instance_limit }}
                            </div>
                        </template>

                        <!-- 录入时间 -->
                        <template v-if="'created_at' === column.key">
                            {{ formatDateTime(record.created_at) }}
                        </template>

                        <!-- 可见性 -->
                        <template v-if="'visibility' === column.key">
                            <a-tag :color="record.user_visible_limit ? 'red' : 'green'">
                                {{ record.user_visible_limit ? '受限' : '无限制' }}
                            </a-tag>
                        </template>

                        <!-- 操作 -->
                        <template v-if="'action' === column.key">
                            <a-space>
                                <a-button type="link" size="small" @click="$refs.editDialogRef.handleEdit(record)">
                                    编辑
                                </a-button>
                                <a-button type="link" size="small" danger @click="handleDownShelf(record)">
                                    下架
                                </a-button>
                                <a-button type="link" size="small" danger @click="handleRemove(record)">
                                    删除
                                </a-button>
                            </a-space>
                        </template>
                    </template>
                </a-table>
            </a-card>
        </a-col>
    </a-row>

    <edit-dialog ref="editDialogRef" @ok="onOk"></edit-dialog>
</template>

<script setup>
import { message, Modal } from 'ant-design-vue'
import { ref } from 'vue'
import apis from '@/apis'
import { formatUtcDateTime } from '@/utils/util'
import { config } from '@/config'
import { usePagination, useForm } from '@/hooks'
import EditDialog from './components/EditDialog.vue'
import { useI18n } from 'vue-i18n'

defineOptions({
    name: 'hostManagement',
})

const { t } = useI18n()

// 表格列定义
const columns = [
    { 
        title: '主机名称/ID', 
        dataIndex: 'machine_name', 
        key: 'machine_name',
        width: 140,
        fixed: 'left'
    },
    { 
        title: '内网IP', 
        dataIndex: 'internal_ip', 
        key: 'internal_ip',
        width: 110
    },
    { 
        title: '健康状态', 
        key: 'health_status',
        width: 100
    },
    { 
        title: '状态', 
        key: 'online_status',
        width: 100
    },
    { 
        title: '主机配置', 
        key: 'cpu_config',
        width: 120
    },
    { 
        title: '磁盘空间(GB)', 
        key: 'disk_space',
        width: 150
    },
    { 
        title: '硬件平台', 
        key: 'hardware_platform',
        width: 120
    },
    { 
        title: '算力型号', 
        key: 'gpu_info',
        width: 200
    },
    { 
        title: '空闲算力', 
        key: 'gpu_idle',
        width: 100
    },
    { 
        title: 'CPU内存分配', 
        key: 'cpu_mem_per_gpu',
        width: 120
    },
    { 
        title: '实例数量', 
        key: 'instance_count',
        width: 100
    },
    { 
        title: '录入时间', 
        key: 'created_at',
        width: 160
    },
    { 
        title: '可见性', 
        key: 'visibility',
        width: 100
    },
    { 
        title: '操作', 
        key: 'action', 
        fixed: 'right', 
        width: 180 
    },
]

// 健康状态映射
const healthStatusMap = {
    0: { text: '正常', color: 'green' },
    1: { text: '警告', color: 'orange' },
    2: { text: '异常', color: 'red' },
    // 可根据实际情况添加更多状态
}

// 在线状态映射（根据图片中的"已上架"状态）
const onlineStatusMap = {
    0: { text: '未上架', color: 'default' },
    1: { text: '上架中', color: 'processing' },
    2: { text: '已上架', color: 'green' },
    3: { text: '下架中', color: 'orange' },
    4: { text: '已下架', color: 'red' },
}

// 工具函数
function getHealthStatusText(status) {
    return healthStatusMap[status]?.text || '未知'
}

function getHealthStatusColor(status) {
    return healthStatusMap[status]?.color || 'default'
}

function getOnlineStatusText(status) {
    return onlineStatusMap[status]?.text || '未知'
}

function getOnlineStatusColor(status) {
    return onlineStatusMap[status]?.color || 'default'
}

// 格式化内存（字节转GB）
function formatMemory(bytes) {
    if (!bytes) return '0G'
    const gb = bytes / (1024 * 1024 * 1024)
    return `${Math.round(gb)}G`
}

// 格式化磁盘空间（字节转GB）
function formatDiskSpace(bytes) {
    if (!bytes) return '0GB'
    const gb = bytes / (1024 * 1024 * 1024)
    return `${Math.round(gb)}GB`
}

// 格式化日期时间
function formatDateTime(dateTimeStr) {
    if (!dateTimeStr) return ''
    try {
        const date = new Date(dateTimeStr)
        return date.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit',
            hour12: false
        }).replace(/\//g, '-')
    } catch (e) {
        return dateTimeStr
    }
}

// 使用分页和数据获取钩子
const { listData, loading, showLoading, hideLoading, paginationState, searchFormData, resetPagination } =
    usePagination()
const { resetForm } = useForm()
const editDialogRef = ref()

getPageList()

/**
 * 获取主机列表
 */
async function getPageList() {
    try {
        showLoading()
        const { pageSize, current } = paginationState
        const { success, data, total } = await apis.resource
            .getHostsList({
                pageSize,
                current: current,
                ...searchFormData.value,
            })
            .catch(() => {
                throw new Error()
            })
        hideLoading()
        if (config('http.code.success') === success) {
            listData.value = data
            paginationState.total = total
        }
    } catch (error) {
        hideLoading()
        message.error('获取主机列表失败')
    }
}

/**
 * 移除/删除主机
 */
function handleRemove({ id, machine_name }) {
    Modal.confirm({
        title: '确认删除',
        content: `确定要删除主机 ${machine_name} 吗？此操作不可恢复。`,
        okText: '确认删除',
        cancelText: '取消',
        okType: 'danger',
        onOk: () => {
            return new Promise((resolve, reject) => {
                ; (async () => {
                    try {
                        const { success } = await apis.resource.deleteHost(id).catch(() => {
                            throw new Error()
                        })
                        if (config('http.code.success') === success) {
                            resolve()
                            message.success('删除成功')
                            await getPageList()
                        }
                    } catch (error) {
                        reject()
                        message.error('删除失败')
                    }
                })()
            })
        },
    })
}

/**
 * 下架主机
 */
function handleDownShelf({ id, machine_name }) {
    Modal.confirm({
        title: '确认下架',
        content: `确定要下架主机 ${machine_name} 吗？`,
        okText: '确认下架',
        cancelText: '取消',
        onOk: () => {
            return new Promise((resolve, reject) => {
                ; (async () => {
                    try {
                        const { success } = await apis.resource.downShelfHost(id).catch(() => {
                            throw new Error()
                        })
                        if (config('http.code.success') === success) {
                            resolve()
                            message.success('下架成功')
                            await getPageList()
                        }
                    } catch (error) {
                        reject()
                        message.error('下架失败')
                    }
                })()
            })
        },
    })
}

/**
 * 分页变化
 */
function onTableChange({ current, pageSize }) {
    paginationState.current = current
    paginationState.pageSize = pageSize
    getPageList()
}

/**
 * 重置搜索
 */
function handleResetSearch() {
    searchFormData.value = {}
    resetPagination()
    getPageList()
}

/**
 * 搜索
 */
function handleSearch() {
    resetForm()
    resetPagination()
    getPageList()
}

/**
 * 编辑完成
 */
async function onOk() {
    await getPageList()
}
</script>

<style lang="less" scoped>
.align-right {
    text-align: right;
}

.mb-8-2 {
    margin-bottom: 8px;
}
</style>