<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="'主机名称'" name="name">
                            <a-input :placeholder="'请输入主机名称'" v-model:value="searchFormData.name"></a-input>
                        </a-form-item>
                    </a-col>

                    <a-col v-bind="colSpan">
                        <a-form-item :label="'GPU型号'" name="gpuType">
                            <a-input :placeholder="'请输入GPU型号'" v-model:value="searchFormData.gpuType"></a-input>
                        </a-form-item>
                    </a-col>

                    <a-col v-bind="colSpan">
                        <a-form-item :label="'地区ID'" name="centerID">
                            <a-input :placeholder="'请输入地区ID'" v-model:value="searchFormData.centerID"></a-input>
                        </a-form-item>
                    </a-col>

                    <a-col class="align-right" v-bind="colSpan">
                        <a-space>
                            <a-button @click="handleResetSearch">{{ $t('button.reset') }}</a-button>
                            <a-button ghost type="primary" @click="handleSearch">
                                {{ $t('button.search') }}
                            </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">
                <!-- <x-action-bar class="mb-8-2">
                    <a-button v-action="'add'" type="primary" @click="$refs.editDialogRef.handleCreate()">
                        <template #icon>
                            <plus-outlined></plus-outlined>
                        </template>
                        添加图片
                    </a-button>
                </x-action-bar> -->
                <a-table :columns="columns" :data-source="listData" :loading="loading" :pagination="paginationState"
                    :scroll="{ x: 1000 }" @change="onTableChange">
                    <template #bodyCell="{ column, record }">
                        <template v-if="'banner_type' === column.key">
                            <!--状态-->
                            <a-tag v-if="record.banner_type == 1" color="processing">
                                首页轮播图
                            </a-tag>
                            <!--状态-->
                            <a-tag v-else color="processing">
                                营销活动图
                            </a-tag>
                        </template>

                        <template v-if="'is_recommend' === column.key">
                            <!--状态-->
                            <a-tag v-if="record.banner_type == true" color="processing">
                                启用
                            </a-tag>
                            <!--状态-->
                            <a-tag v-else color="processing">
                                禁用
                            </a-tag>
                        </template>


                        <template v-if="'createAt' === column.key">
                            {{ formatUtcDateTime(record.created_at) }}
                        </template>

                        <template v-if="'action' === column.key">
                            <x-action-button @click="handelEdit(record)" :disabled="record.status === 'DISABLED'">
                                <a-tooltip>
                                    <template #title>
                                        {{ record.status === 'DISABLED' ? '已下架' : '下架主机' }}
                                    </template>
                                    <edit-outlined />
                                </a-tooltip>
                            </x-action-button>
                            <x-action-button @click="handleRemove(record)">
                                <a-tooltip>
                                    <template #title>
                                        {{ $t('pages.system.delete') }}
                                    </template>
                                    <delete-outlined style="color: red;" />
                                </a-tooltip>
                            </x-action-button>
                        </template>
                    </template>
                </a-table>
            </a-card>
        </a-col>
    </a-row>

</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 { statusTypeEnum } from '@/enums/system'
import { usePagination, useForm } from '@/hooks'
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons-vue'
import { useI18n } from 'vue-i18n'
import { disabledDict } from '@/enums/dict'

defineOptions({
    name: 'systemRole',
})
const { t } = useI18n() // 解构出t方法
const columns = [
    { title: '主机名称', dataIndex: 'name', width: 200 },
    { title: '所属地区名称', dataIndex: 'centerName', width: 150 },
    { title: 'cpu类型', dataIndex: 'cpuType', width: 150 },
    { title: 'cpu数量', dataIndex: 'cpuNum', width: 150 },
    { title: '内存', dataIndex: 'memory', width: 120 },
    { title: '内存型号', dataIndex: 'memoryType', width: 200 },
    { title: '系统盘类型', dataIndex: 'systemDiskType', width: 150 },
    { title: '系统盘大小', dataIndex: 'systemDisk', width: 150 },
    { title: '数据盘类型', dataIndex: 'dataDiskType', width: 150 },
    { title: '数据盘大小', dataIndex: 'dataDisk', width: 120 },
    { title: '按时付费价格', dataIndex: 'payOnTime', width: 120 },
    { title: '按日付费价格', dataIndex: 'payOnDay', width: 150 },
    { title: '按周付费价格', dataIndex: 'payOnWeek', width: 150 },
    { title: '按月付费价格', dataIndex: 'payOnMonth', width: 150 },
    { title: '按年付费价格', dataIndex: 'payOnYear', width: 120 },
    {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        width: 150,
        customRender: ({ text }) => disabledDict.getLabel(text) || text,
    },
    {
        title: '是否推荐到首页',
        dataIndex: 'is_recommend',
        width: 150,
        customRender: ({ text }) => (text === true ? '是' : '否')
    },
    { title: '内网IP', dataIndex: 'intranetIP', width: 150 },

    {
        title: '上行带宽',
        key: 'bandWidthUpCombined',
        width: 150,
        customRender: ({ record }) => {
            const value = record.bandWidthUp ?? '--';
            const unit = record.bandWidthUnitUp ?? '';
            return `${value} ${unit}`.trim();
        }
    },
    {
        title: '下行带宽',
        key: 'bandWidthDownCombined',
        width: 150,
        customRender: ({ record }) => {
            const value = record.bandWidthDown ?? '--';
            const unit = record.bandWidthUnitDown ?? '';
            return `${value} ${unit}`.trim();
        }
    },

    { title: t('button.action'), key: 'action', fixed: 'right', width: 120 },
];

const { listData, loading, showLoading, hideLoading, paginationState, searchFormData, resetPagination } =
    usePagination()
const { resetForm } = useForm()

getPageList()

/**
 * 获取用户列表
 * @returns {Promise<void>}
 */
async function getPageList() {
    try {
        showLoading()
        const { pageSize, current } = paginationState
        const { data, total } = await apis.host
            .getHostList({
                pageSize,
                current: current,
                ...searchFormData.value,
            })
            .catch(() => {
                throw new Error()
            })
        hideLoading()
        if (data.length > 0) {
            listData.value = data
            paginationState.total = total
        }
    } catch (error) {
        hideLoading()
    }
}

/**
 * 移除
 */
function handleRemove({ id }) {
    Modal.confirm({
        title: '提示',
        content: '是否删除该主机？',
        okText: t('button.confirm'),
        onOk: () => {
            return new Promise((resolve, reject) => {
                ; (async () => {
                    try {
                        const { success } = await apis.host.delHost(id).catch(() => {
                            throw new Error()
                        })
                        if (config('http.code.success') === success) {
                            resolve()
                            message.success(t('component.message.success.delete'))
                            await getPageList()
                        }
                    } catch (error) {
                        reject()
                    }
                })()
            })
        },
    })
}

// 下架主机
function handelEdit({ id, status }) {
    if (status === 'DISABLED') {
        message.warning('该主机已下架，无法重复操作');
        return;
    }
    Modal.confirm({
        title: '提示',
        content: '是否下架该主机？',
        okText: t('button.confirm'),
        onOk: () => {
            return new Promise((resolve, reject) => {
                ; (async () => {
                    try {
                        const { success } = await apis.host.updateHost(id).catch(() => {
                            throw new Error()
                        })
                        if (config('http.code.success') === success) {
                            resolve()
                            message.success('下架成功')
                            await getPageList()
                        }
                    } catch (error) {
                        reject()
                    }
                })()
            })
        },
    })
}

/**
 * 分页
 */
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></style>
