<template>
    <OCRDialog ref="ocrDialog" :title="'OCR任务'" :queue_category="queueData.queue_category"
        :queue_name="queueData.queue_name" @success="jobCreated"></OCRDialog>
    <QueueSelectDialog ref="queueSelectDialog" :title="'选择队列'" @success="jobMoved" :queue_data="queueIdNameDict">
    </QueueSelectDialog>
    <TextViewDialog ref="textViewDialog" :title="'查看文件'" :content="textViewData"></TextViewDialog>
    <el-row>
        <span style="text-align: right;">
            <h2>工作队列- {{ queueData.title }} </h2>
        </span>
    </el-row>
    <el-row style="margin:15px;">
        <el-button v-if="allowCreateJob" type="primary" @click="handleCreateJob">新建工作</el-button>
        <el-button @click="handleRefreshTable">刷新</el-button>
    </el-row>

    <el-row>
        <el-table :data="pageData.records" height="650" 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-menu-item index="1-2" @click="handlePutJobIntoQueue(scope.row)">移入队列</el-menu-item>
                            <el-menu-item index="1-3" @click="handleDeleteJob(scope.row)">删除</el-menu-item>
                        </el-sub-menu>
                        <el-sub-menu index="4">
                            <template #title>变更状态</template>
                            <template v-for="item in jobStatusList">
                                <el-menu-item v-if="item.could_be_set" index="4-{{item.id}}"
                                    @click="handleJobSetStatus(scope.row, item.value)">{{ item.label }}</el-menu-item>
                            </template>
                        </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" size="45%">
        <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" style="border-right: 1px solid #CDCDCD;">
                        <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="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 + '?path=' + encodeURIComponent(scope.row.path)">下载</a>
                                    <a @click="handleViewFile(currentJob, 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 } from 'vue-router'
import {
    getJob,
    getJobs,
    getQueue,
    browseJobFile,
    getJobStatus,
    getJobStatusTag,
    JobSatus,
    deleteJob,
    updateJob,
    updateJobStatus,
    getFileContent
} from '@/api/AgentApi'
import type { JobData, } from '@/api/AgentApi'
import OCRDialog from '@/dialogs/OCRDialog.vue'
import QueueSelectDialog from '@/dialogs/QueueSelectDialog.vue'
import TextViewDialog from '@/dialogs/TextViewDialog.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<any>("")
const ocrDialog = ref()
const allowCreateJob = ref(false)
const queueSelectDialog = ref()
const textViewDialog = ref()
const queueId = ref<any>("")
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: null },
    { 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 },
])
var textViewContent = "hello"
const textViewData = ref(textViewContent)
const jobStatusList = ref(JobSatus)
const jobFileTree = ref({
    children: 'children',
    label: 'display_name'
})
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: "" })
const currentActionJob = ref({ id: 0, job_category: "USER", job_name: "" })

const route = useRoute()

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 handleCreateJob = () => {
    if (queueData.value.id == "0") {
        ElNotification.info({
            title: '消息',
            message: '工作队列数据正在加载，请稍候再试',
        })
        return
    }
    let queue_data = queueIdNameDict.value.find((item) => item.id == queueId.value)
    if (queue_data == undefined) {
        return
    }
    // console.log(queue_data)
    if (queue_data.dialog != undefined) {
        // console.log(queue_data.dialog)
        queue_data.dialog.showDialog()
    }
}
const handleViewFile = (job: any, path: string) => {
    // console.log("handleViewFile")
    const url = '/api/file/view/' + job?.id + '?path=' + encodeURIComponent(path)
    // console.log(url)
    getFileContent(url).then((res) => {
        // console.log(res)
        textViewData.value = res.records[0].content
        textViewDialog.value.showDialog(true)
    })
}
const handleRefreshTable = () => {
    loadQueueData()
}
function formatStatus(status: number) {
    return getJobStatus(status)
}
function formatFolderName(name: string) {

    var translate: any = {
        logs: "日志",
        results: "结果", chunks: "切片", files: "文件",
        ocr_output: "文本转换结果", kb_extract: "知识抽取", kb_build: "知识构建",
        upload: '文件上传', output: '输出'
    }
    // console.log(translate[name])
    if (name in translate) {
        return translate[name] as string
    }
    return name
}
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
    }

    if (queue_data.dialog != null) {
        // console.log("queue_data.dialog is allowed")
        allowCreateJob.value = true
    } else {
        allowCreateJob.value = false
    }
    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 jobMoved() {
    queueSelectDialog.value.showDialog(null, false)
    var filterdJobs = pageData.value.records.filter((item: JobData) => {
        return item.id != currentActionJob.value.id
    })
    pageData.value.records = filterdJobs
    ElNotification.success({
        title: '成功',
        message: '工作已经移入指定队列了',
    })
}
function jobCreated() {
    let queue_data = queueIdNameDict.value.find((item) => item.id == queueId.value)
    if (queue_data == undefined) {

        ElNotification.info({
            title: '失败',
            message: '工作队列不存在',
        })

        return
    }
    if (queue_data.dialog != undefined) {
        queue_data.dialog.showDialog(false)
    }
    ElNotification.success({
        title: '成功',
        message: '创建工作成功',
    })
}
function handleJobSetStatus(job: JobData, status: number) {
    if (job == null) {
        return
    }
    job.status = status
    updateJobStatus(job).then((res) => {
        handleRefreshTable()
        ElNotification.success({
            title: '成功',
            message: '变更工作状态成功',
        })
    })
}
function handleDeleteJob(job: JobData) {
    if (job == null) {
        return
    }
    ElMessageBox.confirm(
        '此操作将永久删除该工作, 是否继续?',
        '提示',
    ).then(() => {
        deleteJob({ job_id: job.id }).then((res) => {
            handleRefreshTable()
            ElNotification.success({
                title: '成功',
                message: '删除工作成功',
            })
        })
    }).catch(() => {
        ElNotification.error({
            title: '失败',
            message: '删除工作失败，请稍后再试',
        })
    })

}
function handlePutJobIntoQueue(job: JobData) {
    currentActionJob.value = job

    queueSelectDialog.value.showDialog(job)
}
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 handleJobMenuSelect(key: string, keyPath: string[]) {
    // console.log(key, keyPath)
}
function handleViewJob(job: JobData) {
    if (job == null) {
        return
    }
    jobFileData.value = []
    jobFileInDir.value = []
    getJob(job.id).then((res) => {
        currentJob.value = res.records[0]
        showDrawer.value = true
        browseJobFile({ job_id: job.id, path: "" }).then((res) => {
            for (let i = 0; i < res.records.length; i++) {
                res.records[i]['label'] = res.records[i].name
                res.records[i]['children'] = []
                res.records[i]['display_name'] = formatFolderName(res.records[i].name)
            }
            jobFileData.value = res.records
            // console.log("show drawer")
        })
    })
}
function handleCurrentChange(data: any) {
    if (data == null) {
        return
    }

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

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