<template>
    <el-row>
        <h2>配置</h2>
    </el-row>
    <el-row style="margin:15px; ">
        <el-tabs v-model="activeName" style="width: 100%; ">
            <el-tab-pane label="基本配置" name="basic"
                style="width: 100%;height: 800px; overflow-y:auto; display: flex; flex-direction: row;">
                <el-form :model="basicConfig" label-width="120px" style="margin: 5px;">
                    <el-form-item label="名称" prop="name" style="height: 25px;">
                        <el-input v-model="basicConfig.name"></el-input>
                    </el-form-item>
                    <el-form-item label="联系人" prop="contactor" style="height: 25px;">
                        <el-input v-model="basicConfig.contactor"></el-input>
                    </el-form-item>
                    <el-form-item label="联系电话" prop="contact_phone" style="height: 25px;">
                        <el-input v-model="basicConfig.contact_phone"></el-input>
                    </el-form-item>
                    <el-form-item label="启用日期" prop="system_uptime" style="height: 25px;">
                        <el-date-picker v-model="basicConfig.system_uptime" type="date" placeholder="选择日期">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item label="结束日期" prop="system_downtime" style="height: 25px;">
                        <el-date-picker v-model="basicConfig.system_downtime" type="date" placeholder="选择日期">
                        </el-date-picker>
                    </el-form-item>
                </el-form>
            </el-tab-pane>
            <el-tab-pane label="队列配置" name="first" style="width: 100%;height: 800px; overflow-y:auto;">
                <div v-for="(queue) in queueData" :key="queue.id"
                    style="margin:0px 8px 10px 0px;width:350px; display: inline-block; ">
                    <span style="font-weight: bold;"> {{ queue.queue_label }}</span> <span style="font-size: 8pt;">（{{
                        queue.queue_category }}_{{ queue.queue_name }}）</span><br />
                    <br />
                    <div style="border: solid 1px #CDCDCD;padding:8px;">
                        当成功时，转到 {{ queue.queue_config?.success.queue_category }}_{{
                            queue.queue_config?.success.queue_name }}<br />
                        当失败时，转到 {{ queue.queue_config?.failed.queue_category }}_{{ queue.queue_config?.failed.queue_name
                        }}<br />
                        当错误时，转到 {{ queue.queue_config?.error.queue_category }}_{{ queue.queue_config?.error.queue_name
                        }}<br />
                        最大实例数：<el-select v-model="queue.queue_config.max_instance" style="width:55px;margin-right:5px;">
                            <el-option v-for="item in [1, 2, 3, 4, 5]" :key="item" :label="item"
                                :value="item"></el-option>
                        </el-select>
                        <div style="border-top: solid 1px #CDCDCD; margin-top:5px; display:grid;justify-items: right;">
                            <el-button @click="handleSaveConfig(queue)"
                                style=" width:80px; margin-top:3px;">保存</el-button>
                        </div>
                    </div>


                </div>
            </el-tab-pane>
            <el-tab-pane label="大模型配置" name="second">

                <el-button link type="primary" @click="handleSaveLLMConfig" style="">保存</el-button>
                <div style="width: 100%;display: flex; flex-direction: row; flex-wrap:wrap;">
                    <div
                        style="width: 300px;height:210px;border: 1px solid #CDCDCD; display: flex; flex-direction: column;justify-content:center;margin-right: 8px; margin-bottom: 8px;">
                        <el-button link type="primary" @click="handleAddLLMConfig">添加</el-button>
                    </div>
                    <template v-for="(item) in llmConfig.items" :key="item.id">
                        <div
                            style="width: 300px;height:210px;border: 1px solid #CDCDCD; display: flex; flex-direction: column;justify-content:center;margin-right: 8px; margin-bottom: 8px;">
                            <div v-if="item.is_default"
                                style="position: relative; width: 15px; height:15px;left: 0px; top:15px; background-color: darkgreen;">
                                <span style="height:15px;">&nbsp;</span>
                            </div>
                            <el-form :model="item" label-width="80px" style="margin: 5px;">
                                <el-form-item label="类型" prop="api_name" style="height: 25px;">
                                    <span v-if="getLLMConfigEditFlag(item) == false">{{ item.api_name }}</span>
                                    <el-select v-else v-model="item.api_name" style="width: 150px;">
                                        <el-option v-for="option in ['openai', 'deepseek v3', 'deepseek r1']"
                                            :key="option" :label="option" :value="option"></el-option>
                                    </el-select>
                                </el-form-item>
                                <el-form-item lable="模型" prop="model_name" style="height: 25px;">
                                    <span v-if="getLLMConfigEditFlag(item) == false">{{ item.model_name }}</span>
                                    <el-input v-else v-model="item.model_name"></el-input>
                                </el-form-item>
                                <el-form-item label="API 地址" prop="api_host" style="height: 25px;">
                                    <span v-if="getLLMConfigEditFlag(item) == false" style="overflow: hidden;">{{
                                        formatOverflowText(item.api_host, 32) }}</span>
                                    <el-input v-else v-model="item.api_host"></el-input>
                                </el-form-item>
                                <el-form-item label="API Key" prop="api_key" style="height: 25px;">
                                    <span v-if="getLLMConfigEditFlag(item) == false">********</span>
                                    <el-input v-else v-model="item.api_key"></el-input>
                                </el-form-item>
                                <el-form-item style="display:grid;justify-items: right; height:25px;">
                                    <el-button v-if="!item.is_default" link type="primary"
                                        @click="handleSetLLMConfigDefault(item)" style=" ">设为默认</el-button>
                                    <el-button link type="danger" @click="handleDeleteLLMConfig(item)"
                                        v-if="getLLMConfigEditFlag(item) == false" style=" ">删除</el-button>
                                    <el-button link type="primary" @click="handleEditLLMConfig(item)"
                                        v-if="getLLMConfigEditFlag(item) == false" style=" ">编辑</el-button>
                                    <el-button link type="primary" @click="handleCancelEditLLMConfig(item)"
                                        v-if="getLLMConfigEditFlag(item) == true" style=" ">取消</el-button>

                                </el-form-item>
                            </el-form>
                        </div>
                    </template>
                </div>
            </el-tab-pane>
            <!-- <el-tab-pane label="许可证" name="third">
        
        第一步：通过hash数值查询许可证信息<br/>
        第二步：导入许可证文件
        <el-image style="width: 300px; height: 300px" :src="'/api/agent/qrcode/somm'" wid></el-image>
    </el-tab-pane> -->
        </el-tabs>
    </el-row>
</template>
<script setup lang="ts">
import { ref, onMounted, watch, nextTick } from 'vue'
import { getConfig, setConfig, getQueues } from '@/api/AgentApi'
import { ElMessage } from 'element-plus'
import { formatOverflowText } from '@/utils/misc'
import { ITEM_RENDER_EVT } from 'element-plus/es/components/virtual-list/src/defaults.mjs'
interface ViewBasicInfo {
    name: string,
    contactor: string,
    contact_phone: string,
    system_uptime: Date,
    system_downtime: Date
}
interface ActionQueue {
    queue_category: string
    queue_name: string
}
interface QueueConfig {
    command: string
    script: string
    args: string[]
    success: ActionQueue
    failed: ActionQueue
    error: ActionQueue
    max_instance: number
}
interface QueueData {
    id: number
    queue_category: string
    queue_name: string
    queue_label: string
    queue_config: QueueConfig
}
interface ConfigData {
    id: number
    code: string
    name: string
    content: string
    status: number
}
interface LLMConfigData {
    current_api_name: string
    items: LLMConfigItemData[]
}
interface LLMConfigItemData {
    api_key: string
    api_host: string
    api_name: string
    model_name: string
    is_default: boolean
}
const basicConfig = ref<ViewBasicInfo>({} as ViewBasicInfo)
const activeName = ref('first')
const queueData = ref<QueueData[]>([])
const llmConfig = ref<LLMConfigData>({ current_api_name: "", items: [] })
const llmConfigEditFlag = ref<Map<LLMConfigItemData, boolean>>(new Map())
function loadQueueConfigData() {
    queueData.value.forEach((queue) => {
        var queue_code = queue.queue_category + "_" + queue.queue_name
        getConfig({ code: queue_code }).then((res) => {
            var config: ConfigData = res.records[0] as ConfigData
            var config_data: QueueConfig = JSON.parse(config.content) as QueueConfig
            queue.queue_config = config_data
            if (queue.queue_config != null) {
                if (queue.queue_config.max_instance === undefined) {
                    queue.queue_config.max_instance = 1
                }
            }
        })
    })
}
function loadLLMConfigData() {
    getConfig({ code: "LLM_CONFIG" }).then((res) => {
        var config: ConfigData = res.records[0] as ConfigData
        var config_data: LLMConfigData = JSON.parse(config.content) as LLMConfigData
        llmConfig.value = config_data
    })
}
function handleSaveLLMConfig() {
    llmConfig.value.items.forEach((item) => {
        if (item.is_default) {
            llmConfig.value.current_api_name = item.api_name
        }
    })
    var config: ConfigData = { id: 0, code: "LLM_CONFIG", name: "大模型配置", content: JSON.stringify(llmConfig.value), status: 1 }
    setConfig(config).then((res) => {
        if (res.code == 200) {
            ElMessage.success("保存成功")
        }
    })

}
function handleSaveConfig(queue: QueueData) {

}
function handleSetLLMConfigDefault(item: LLMConfigItemData) {
    llmConfig.value.items.forEach((item) => {
        item.is_default = false
    })
    item.is_default = true
}
function handleDeleteLLMConfig(item: LLMConfigItemData) {
    var index = llmConfig.value.items.indexOf(item)
    llmConfig.value.items.splice(index, 1)
}
function getLLMConfigEditFlag(item: LLMConfigItemData) {
    return llmConfigEditFlag.value.get(item) == true ? true : false
}
function handleEditLLMConfig(item: LLMConfigItemData) {
    llmConfigEditFlag.value.set(item, true)
}
function handleCancelEditLLMConfig(item: LLMConfigItemData) {
    llmConfigEditFlag.value.set(item, false)
}
function handleAddLLMConfig() {
    var item: LLMConfigItemData = { api_key: "", api_host: "", api_name: "", is_default: false, model_name: "" }
    item.api_name = "openai"

    llmConfig.value.items.push(item)
    llmConfigEditFlag.value.set(item, true)
}
function loadQueues() {
    getQueues().then(async (res) => {
        queueData.value = []
        let data = res.records as QueueData[]
        // loadQueueConfigData()
        await Promise.allSettled(data.map(async (queue, index) => {
            var queue_code = data[index].queue_category + "_" + data[index].queue_name
            await getConfig({ code: queue_code }).then((res) => {
                var config: ConfigData = res.records[0] as ConfigData
                var config_data: QueueConfig = JSON.parse(config.content) as QueueConfig
                data[index].queue_config = config_data
                if (data[index].queue_config != null) {
                    if (data[index].queue_config.max_instance === undefined) {
                        data[index].queue_config.max_instance = 1
                    }
                }
            })
            queueData.value.push(data[index])
        }))
        // queueData.value = data
    })
}
onMounted(() => {
    loadQueues()
    loadLLMConfigData()
})
</script>
<style lang="css" scoped></style>