<template>


    <el-row>
        <span style="text-align: right;">
            <h2>知识图谱</h2>
        </span>
    </el-row>
    <el-row style="margin:15px;">
        <el-button @click="handleRefreshTable">刷新</el-button>
    </el-row>

    <el-row>
        <el-table :data="pageData.records" highlight-current-row @current-change="handleCurrentChange">
            <el-table-column prop="id" label="ID" width="50"></el-table-column>
            <el-table-column prop="job_category" label="工作类型" width="200"></el-table-column>
            <el-table-column prop="job_name" label="工作名称" width="200"></el-table-column>
            <el-table-column prop="job_creator" label="创建人" width="100"></el-table-column>
            <el-table-column prop="status" label="状态" width="100">
                <template v-slot="scope">
                    <el-tag :type="getJobStatusTag(scope.row.status)">{{ formatStatus(scope.row.status) }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="500">
                <template v-slot="scope">
                    <el-menu mode="horizontal">

                        <el-sub-menu index="1">
                            <template #title>操作</template>
                            <el-menu-item index="1-1" @click="handleViewJob(scope.row)">查看</el-menu-item>
                        </el-sub-menu>

                    </el-menu>
                </template>
            </el-table-column>
        </el-table>

    </el-row>
    <el-row style="margin-top:30px;">
        <el-pagination background layout="prev, pager, next" :total="pageData.total" :page-size="pageData.page_size"
            @current-change="handleCurrentPageChange" :current-page.sync="pageData.page">
        </el-pagination>
    </el-row>
    <el-drawer title="工作详情" v-model="showDrawer" :direction="showDrawerDirection">
        <el-tabs type="border-card" v-model="jobDetailsActivateTab">
            <el-tab-pane label="基本信息" name="basic_info">
                <div class="prop_header">任务类型</div>
                <div>{{ currentJob.job_category }}</div>
                <div class="prop_header">任务名称</div>
                <div>{{ currentJob.job_name }}</div>
                <div class="prop_header">创建人</div>
                <div>{{ currentJob.job_creator }}</div>
                <div class="prop_header">创建时间</div>
                <div>{{ formatDate(currentJob.created) }}</div>
                <div class="prop_header">更新时间</div>
                <div>{{ formatDate(currentJob.updated) }}</div>
                <div class="prop_header">日志</div>
                <div><el-input type="textarea" v-model="currentJob.job_logs" :rows="20"></el-input></div>
            </el-tab-pane>
            <el-tab-pane label="文件夹" name="file_browse">
                <el-row>
                    <el-col :span="4">
                        <el-tree :data="jobFileData" :props="jobFileTree" @node-click="handleTreeNodeClick"></el-tree>
                    </el-col>
                    <el-col :span="20">
                        <el-table v-if="jobFileInDir.length > 0" :data="jobFileInDir" highlight-current-row
                            style="width: 100%;">
                            <el-table-column prop="type" label="类型" width="75"></el-table-column>
                            <el-table-column prop="name" label="名称" width="250"></el-table-column>
                            <el-table-column prop="size" label="操作" width="100">
                                <template v-slot="scope">
                                    <a :href="'/api/file/download/' + currentJob?.id + '/' + scope.row.path">下载</a>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-col>
                </el-row>
            </el-tab-pane>
        </el-tabs>


    </el-drawer>

</template>


<script setup lang="ts">

import { ref, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
    getJob,
    getJobs,
    getQueue,
    browseJobFile,
    getJobStatus,
    getJobStatusTag,
    JobSatus,
    deleteJob,
    updateJob,
    updateJobStatus
} from '@/api/AgentApi'
import type { JobData, } from '@/api/AgentApi'
import OCRDialog from '@/dialogs/OCRDialog.vue'
import QueueSelectDialog from '@/dialogs/QueueSelectDialog.vue'
import { ElNotification, ElMessageBox } from 'element-plus'
import { formatTime } from 'element-plus/es/components/countdown/src/utils.mjs'
import { formatDate } from '@/utils/misc'
import { getSessionVar, saveSessionVar } from '@/utils/session'
//从路由参数中获取队列ID

const sessionId = ref<string | undefined>("")
const ocrDialog = ref()
const queueSelectDialog = ref()
const queueId = ref("")
const queueData = ref({ id: "0", queue_category: "", queue_name: "", title: "" })
const showDrawer = ref(false)
const showDrawerDirection = ref('rtl')
const jobDetailsActivateTab = ref('basic_info')
const queueIdNameDict = ref([
    { id: "0", name: "DEFAULT", category: 'SYSTEM', title: "缺省队列", dialog: ocrDialog },
    { id: "1", name: "OCR", category: 'SYSTEM', title: "文档OCR", dialog: ocrDialog },
    { id: "2", name: "OCR_RESULTS", title: "OCR结果校对", category: 'SYSTEM', dialog: null },
    { id: "3", name: "CHUNKS", title: "文本切片队列", category: 'SYSTEM', dialog: null },
    { id: "4", name: "KB_EXTRACT", title: "知识抽取", category: 'SYSTEM', dialog: null },
    { id: "5", name: "KB_BUILD", title: "图谱数据构建", category: 'SYSTEM', dialog: null },
    { id: "6", name: "WORD", title: "WORD文档抽取", category: 'SYSTEM', dialog: ocrDialog },
])

const jobStatusList = ref(JobSatus)
const jobFileTree = ref({
    children: 'children',
    label: 'label'
})
const pageData = ref({ page: 1, pages: 1, page_size: 10, total: 0, records: [] })
const jobFileData = ref([])
const jobFileInDir = ref([])
const currentJob = ref<any>({ id: 0, job_category: "USER", job_name: "", job_creator: "", job_logs: "", updated: "", created: null })
const currentActionJob = ref({ id: 0, job_category: "USER", job_name: "" })

const route = useRoute()
const router = useRouter()
watch(route, (newValue, oldValue) => {
    let para = newValue.params.id as string | undefined
    if (para == undefined) {
        return
    }
    console.log('route changed')
    queueId.value = para
    queueData.value.id = "0"
    loadQueueData()
})

const handleRefreshTable = () => {
    loadQueueData()
}
function formatStatus(status: number) {
    return getJobStatus(status)
}
function loadQueueData() {

    jobFileData.value = []
    jobFileInDir.value = []
    currentJob.value = { id: 0, job_category: "USER", job_name: "" }
    currentActionJob.value = { id: 0, job_category: "USER", job_name: "" }
    // 根据队列ID获取队列数据
    let queue_data = queueIdNameDict.value.find((item) => item.id == queueId.value)

    if (queue_data == undefined) {
        queueData.value = { id: "999", queue_category: 'SYSTEM', queue_name: 'UNKNOWN', title: "未知队列" }
        return
    }
    getQueue(queue_data.category, queue_data.name).then((res) => {
        if (res.records.length == 0) {
            return
        }
        queueData.value.id = res.records[0].id
        queueData.value.queue_category = res.records[0].queue_category
        queueData.value.queue_name = res.records[0].queue_name
        queueData.value.title = queue_data.title
    })
    getJobs(queue_data.category, queue_data.name, pageData.value.page, pageData.value.page_size).then((res) => {
        pageData.value.page = res.meta.page
        pageData.value.pages = res.meta.pages
        pageData.value.total = res.meta.total
        pageData.value.records = res.records

    })
}
function handleTreeNodeClick(data: any) {
    if (data.type == 'dir') {
        browseJobFile({ job_id: currentJob.value.id, path: data.name }).then((res) => {
            jobFileInDir.value = res.records
        })
    }
}
function handleCurrentPageChange(page: number) {
    getJobs(queueData.value.queue_category, queueData.value.queue_name, page).then((res) => {
        pageData.value.page = res.meta.page
        pageData.value.pages = res.meta.pages
        pageData.value.total = res.meta.total
        pageData.value.records = res.records
    })
}
function handleViewJob(job: JobData) {
    if (job == null) {
        return
    }
    router.push({ name: 'graph-mgr', params: { id: job.id } })
}
function handleCurrentChange(data: any) {
    if (data == null) {
        return
    }

    //currentJob.value = data
}
onMounted(() => {
    sessionId.value = getSessionVar("session_id") as string | undefined
    queueId.value = "5"
    loadQueueData()
})
</script>

<style lang="css" scoped>
.prop_header {
    font-weight: bold;
    margin-top: 10px;
    margin-bottom: 5px;
}
</style>