<template>
    <div class="table-box">
        <ProTable ref="proTable" :columns="columns" :request-api="getTableList">
            <template #tableHeader>
                <el-button v-auth.resourceManage="'add'" type="primary" :icon="CirclePlus" @click="openAddDialog">
                    新增
                </el-button>
            </template>
            <template #operation="scope">
                <el-button
                    v-auth.resourceManage="'play'"
                    type="primary"
                    link
                    :icon="VideoPlay"
                    @click="handlePlay(scope.row)"
                >
                    播放
                </el-button>
                <el-button
                    v-auth.resourceManage="'edit'"
                    type="primary"
                    link
                    :icon="EditPen"
                    @click="openEditDialog(scope.row)"
                >
                    编辑
                </el-button>
            </template>
        </ProTable>
    </div>
    <ResourceManagePopup ref="resourceManagePopup" :refresh-table="proTable?.getTableList" />
    <ResourcePlayerDialog ref="resourcePlayerDialog" />
</template>

<script setup lang="tsx" name="resourceManage">
import { reactive, ref } from 'vue'
import { CirclePlus, EditPen, VideoPlay } from '@element-plus/icons-vue'
import ProTable from '@/components/ProTable/index.vue'
import type { ColumnProps, ProTableInstance } from '@/components/ProTable/interface'
import type { ResourceManage } from '@/api/resourceManage/interface'
import { getResourceManageList, getResourceManagePlayUrl } from '@/api/resourceManage'
import ResourceManagePopup from './components/resourceManagePopup.vue'
import ResourcePlayerDialog from './components/resourcePlayerDialog.vue'

defineOptions({
    name: 'resourceManage'
})

const proTable = ref<ProTableInstance>()
const resourceManagePopup = ref()
const resourcePlayerDialog = ref()

const getTableList = async (params: ResourceManage.ReqResourceManageParams) => {
    return getResourceManageList(params)
}

const formatFileSize = (size?: number) => {
    if (!size && size !== 0) return ''
    if (size < 1024) return `${size} B`
    const kb = size / 1024
    if (kb < 1024) return `${kb.toFixed(2)} KB`
    return `${(kb / 1024).toFixed(2)} MB`
}

const formatDateTime = (value?: string | null) => {
    if (!value) return ''
    const date = new Date(value)
    if (Number.isNaN(date.getTime())) return value
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

const normalizeStreamUrl = (url: string) => {
    if (/^https?:\/\//i.test(url)) return url
    const baseUrl = import.meta.env.VITE_API_URL as string
    const normalizedBase = baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl
    const normalizedUrl = url.startsWith('/') ? url : `/${url}`
    return `${normalizedBase}${normalizedUrl}`
}

const columns = reactive<ColumnProps<ResourceManage.ResResourceManage>[]>([
    { type: 'index', fixed: 'left', width: 70, label: '序号' },
    {
        prop: 'name',
        label: '资源名称',
        minWidth: 160,
        search: { el: 'input' }
    },
    {
        prop: 'fileName',
        label: '文件名',
        minWidth: 220,
        search: { el: 'input' }
    },
    {
        prop: 'fileSize',
        label: '文件大小',
        width: 120,
        render: scope => formatFileSize(scope.row.fileSize)
    },
    {
        prop: 'relativePath',
        label: '路径',
        width: 200,
        showOverflowTooltip: true
    },
    {
        prop: 'remark',
        label: '备注',
        minWidth: 180,
        showOverflowTooltip: true
    },
    {
        prop: 'createTime',
        label: '上传时间',
        width: 180,
        render: scope => formatDateTime(scope.row.createTime)
    },
    { prop: 'operation', label: '操作', fixed: 'right', width: 180 }
])

const openAddDialog = () => {
    resourceManagePopup.value?.open('add')
}

const openEditDialog = (row: ResourceManage.ResResourceManage) => {
    resourceManagePopup.value?.open('edit', row)
}

const handlePlay = async (row: ResourceManage.ResResourceManage) => {
    const { data } = await getResourceManagePlayUrl(row.id)
    resourcePlayerDialog.value?.open(normalizeStreamUrl(data.url))
}
</script>
