<template>
    <div class="group-container">
        <div class="infinite-list" v-infinite-scroll="listLoad" style="overflow: auto"
            :infinite-scroll-immediate="false" infinite-scroll-distance="10">
            <el-card class="add-robot">
                <div class="add-box" @click="handleAdd">
                    <el-icon>
                        <Plus></Plus>
                    </el-icon>
                    添加智能体
                </div>
            </el-card>

            <el-card v-for="(item, index) in robotCards" :key="item.index"
                :class="{ 'active-robot': newRobotId == item.id }" @click="handleRobot(item)">
                <div class="robot-title">
                    <div class="robot-icon" v-if="item.type == 3"><span>FastGPT</span></div>
                    <el-image v-if="item.type == 1" class="robot-head" :src="dify"></el-image>
                    <el-image v-if="item.type == 2" class="robot-head" :src="coze"></el-image>
                    <p>

                        <label class="name" style="">{{ item.name }}</label>
                        <template v-if="item.type == 1 || item.type == 3">
                            <label class="wx_name"> Host：{{ item.config.host
                            }}</label>
                            <label class="wx_name"> Key：{{ item.config.key }}</label>
                        </template>
                        <template v-if="item.type == 2">
                            <label class="wx_name"> Token：{{ item.config.token
                            }}</label>
                            <label class="wx_name"> Bot_id：{{ item.config.bot_id }}</label>
                        </template>
                    </p>
                </div>

                <p class="use-count"><el-link type="primary" @click.stop="openGroup(item)">{{ item.group_use_count
                        }}</el-link>，<el-link type="primary" @click.stop="openContacts(item)">{{ item.contact_use_count
                        }}</el-link></p>
                <p class="description">Model_type：
                    <span v-if="item.config.model_type == 'workflow'">Work_flow</span>
                    <span v-if="item.config.model_type == 'chat'">Chat</span>
                </p>
                <p class="description">描述：{{ item.description }}</p>
                <el-popover @click.stop placement="bottom" width="120px" trigger="hover" hide-after="0">
                    <template #reference>
                        <span class="edit-icon" @click.stop>
                            <el-icon>
                                <MoreFilled />
                            </el-icon>
                        </span>
                    </template>
                    <template #default>
                        <ul class="popover-list" @click.stop>
                            <li class="rizhi-icon" @click.stop="openLog(item)">
                                <el-icon>
                                    <ChatLineSquare />
                                </el-icon> 调用日志
                            </li>
                            <li class="edit-icon" @click.stop="handleEdit(item, index)">
                                <el-icon>
                                    <Edit></Edit>
                                </el-icon> 编辑
                            </li>
                            <li class="delete-icon" @click.stop="handleDelete(item, index)">
                                <el-icon>
                                    <Delete />
                                </el-icon> 删除
                            </li>
                        </ul>
                    </template>

                </el-popover>
                
            </el-card>
        </div>
        <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑智能体' : '添加智能体'" width="600px" align-center
            :before-close="handleClose">
            <div class="dialog-box" v-loading.fullscreen.lock="loading">

                <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules">
                    <el-form-item label="名称" prop="name">
                        <el-input v-model="ruleForm.name" placeholder="请输入智能体名称" size="large" />
                    </el-form-item>
                    <el-form-item label="类型" prop="type">
                        <el-select v-model="ruleForm.type" placeholder="请选择智能体类型" @change="changeType">
                            <el-option :value="1" label="DIFY"></el-option>
                            <el-option :value="2" label="COZE"></el-option>
                            <el-option :value="3" label="FastGPT"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="Host" prop="config.host" v-if="ruleForm.type == 1 || ruleForm.type == 3" :rules="[{
                        required: true,
                        message: '请输入Host地址',
                        trigger: 'blur',
                    }]">
                        <el-input v-model="ruleForm.config.host" placeholder="请输入Host地址" size="large" />
                    </el-form-item>
                    <el-form-item label="Key" prop="config.key" v-if="ruleForm.type == 1 || ruleForm.type == 3" :rules="[{
                        required: true,
                        message: '请输入Key',
                        trigger: 'blur',
                    }]">
                        <el-input v-model="ruleForm.config.key" placeholder="请输入Key" size="large" />
                    </el-form-item>
                    <el-form-item label="Token" prop="config.token" v-if="ruleForm.type == 2" :rules="[{
                        required: true,
                        message: '请输入Token',
                        trigger: 'blur',
                    }]">
                        <el-input v-model="ruleForm.config.token" placeholder="请输入Token" size="large" />
                    </el-form-item>
                    <el-form-item label="Bot_id" prop="config.bot_id" v-if="ruleForm.type == 2" :rules="[{
                        required: true,
                        message: '请输入Bot_id',
                        trigger: 'blur',
                    }]">
                        <el-input v-model="ruleForm.config.bot_id" placeholder="请输入Bot_id" size="large" />
                    </el-form-item>
                    <el-form-item label="Model_type" prop="config.model_type" :rules="[{
                        required: true,
                        message: '请选择模型类型',
                        trigger: 'blur',
                    }]">
                        <el-select v-model="ruleForm.config.model_type" placeholder="请选择模型类型" size="large">
                            <el-option v-for="item in modelTypeList" :key="item.value" :value="item.value" :label="item.label"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="智能体描述" prop="description">
                        <el-input type="textarea" row="3" v-model="ruleForm.description" placeholder="请输入智能体描述"
                            size="large" />
                    </el-form-item>

                </el-form>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitRobot" :class="{ 'no-click': mhtLoading }">
                        <el-icon v-if="mhtLoading" class="mht-loading" style="margin-right: 4px;">
                            <Loading />
                        </el-icon>
                        <el-icon v-else style="margin-right: 4px;">
                            <svg class="icon" aria-hidden="true">
                                <use xlink:href="#icon-baocun"></use>
                            </svg></el-icon>
                        {{ isEdit ? '保 存' : '添 加' }}
                    </el-button>
                </div>
            </template>
        </el-dialog>
        <el-dialog v-model="dialogGroup" title="使用智能体的群" width="800px" align-center :before-close="handleClose">
            <div class="dialog-box">
                <el-table :data="groupList" style="width: 100%" max-height="500px">
                    <template #empty>
                        <span v-if="tableLoading">加载中...</span>
                        <span v-if="!tableLoading">暂无数据</span>
                    </template>
                    <el-table-column prop="head_url" label="机器人" align="left">
                        <template #default="scope">
                            <img :src="scope.row.head_url" alt="" style="width: 36px; height: 36px; border-radius: 4px;vertical-align: middle;margin-right: 10px;">
                            <span>{{ scope.row.name }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="room_name" label="群组名称" align="center" />
                    <el-table-column prop="config_at" label="配置时间" align="center">
                    </el-table-column>
                    <el-table-column prop="status" label="状态" align="center" >
                        <template #default="scope">
                            <span v-if="scope.row.status == 1" type="success">启用</span>
                            <span v-else type="danger">禁用</span>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="pagination-box">
                    <el-pagination v-model:current-page="groupQuery.page" v-model:page-size="groupQuery.page_size"
                        :page-sizes="[10, 20, 30, 40, 50]" :size="groupQuery.page_size" background
                        layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
                        @current-change="handleCurrentChange" />
                </div>
                
            </div>

        </el-dialog>
        <el-dialog v-model="dialogContact" title="使用智能体的企业微信" width="800px" align-center :before-close="handleClose">
            <div class="dialog-box">

                <el-table :data="contactList" style="width: 100%" max-height="500px">
                    <template #empty>
                        <span v-if="tableLoading">加载中...</span>
                        <span v-if="!tableLoading">暂无数据</span>
                    </template>
                    
                    <el-table-column prop="head_url" label="机器人" align="left">
                        <template #default="scope">
                            <img :src="scope.row.head_url" alt="" style="width: 36px; height: 36px; border-radius: 4px;vertical-align: middle;margin-right: 10px;">
                            <span>{{ scope.row.name }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="config_at" label="配置时间" align="center">
                    </el-table-column>
                    <el-table-column prop="status" label="状态" align="center" >
                        <template #default="scope">
                            <span v-if="scope.row.status == 1" type="success">启用</span>
                            <span v-else type="danger">禁用</span>
                        </template>
                    </el-table-column>
                    
                </el-table>
                <div class="pagination-box">
                    <el-pagination v-model:current-page="contactQuery.page" v-model:page-size="contactQuery.page_size"
                        :page-sizes="[10, 20, 30, 40, 50]" :size="contactQuery.page_size" background
                        layout="total, sizes, prev, pager, next, jumper" :total="contactTotal" @size-change="contactSizeChange"
                        @current-change="contactCurrentChange" />
                </div>
            </div>

        </el-dialog>
        <el-dialog v-model="dialogLog" title="调用日志" width="65%" align-center :before-close="handleClose">
            <template #header>
                <span>调用日志</span>
                <el-icon class="refresh-icon" :class="{ 'mht-loading': logLoading }" @click="refreshLog"><Refresh /></el-icon>
            </template>
            <div class="dialog-box">

                <el-table :data="logList" style="width: 100%" max-height="calc(100vh - 240px)" :row-class-name="rowClassname">
                    <template #empty>
                        <span v-if="tableLoading">加载中...</span>
                        <span v-if="!tableLoading">暂无数据</span>
                    </template>
                    <el-table-column prop="status" label="状态">
                        <template #default="scope">
                            <span v-if="scope.row.status == 1" style="color: var(--el-color-success)">成功</span>
                            <span v-if="scope.row.status == 2" style="color: var(--el-color-danger)">失败</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="created_at" label="调用时间" />
                    <el-table-column prop="cost_time" label="耗时(秒)"/>
                    <!-- <el-table-column prop="path" label="接口地址" /> -->
                    <el-table-column label="查看详情" type="expand" width="80" align="center">
                        <template #default="scope">
                        <div class="message-box">
                            <span class="message-title">接口地址:</span>
                            <p>{{ scope.row.path }}</p>
                            <span class="message-title">请求参数:</span>
                            <!-- <p>{{ scope.row.request_param }}</p> -->
                                <json-viewer
                                    :expand-depth="3"
                                    theme="my-json-theme"
                                    :value="scope.row.request_param"
                                ></json-viewer>
                            <div v-if="scope.row.status == 1">
                                <span class="message-title">响应数据:</span>
                                <!-- <p>{{ scope.row.response_data }}</p> -->
                                <json-viewer
                                    :expand-depth="3"
                                    theme="my-json-theme"
                                    :value="scope.row.response_data"
                                ></json-viewer>
                            </div>
                            <div v-if="scope.row.status == 2">
                                <span class="message-title">错误信息:</span>
                                <p>{{ scope.row.error_msg }}</p>
                                <!-- <json-viewer
                                    :expand-depth="3"
                                    theme="my-json-theme"
                                    :value="scope.row.error_msg"
                                ></json-viewer> -->
                            </div>
                        </div>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="pagination-box">
                    <el-pagination v-model:current-page="logQuery.page" v-model:page-size="logQuery.page_size"
                        :page-sizes="[10, 20, 30, 40, 50]" :size="logQuery.page_size" background
                        layout="total, sizes, prev, pager, next, jumper" :total="logTotal" @size-change="handleSizeChangeAgent"
                        @current-change="handleCurrentChangeAgent" />
                </div>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="dialogLog = false">
                        关闭
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
<script setup>
import { ref, onMounted, reactive, nextTick } from 'vue'
import { getAgents, addRobot, deleteRobot, editRobot, agentGroups, agentContacts, agentLogs } from '@/api/ai'
import robotStore from '@/store/modules/robotStore'
import robotImg from '@/assets/images/robot.png'
import coze from '@/assets/images/coze.png'
import dify from '@/assets/images/dify.png'
import { ElNotification } from 'element-plus'
const robot_img = robotImg
const userRobotStore = robotStore()
const robotCards = ref([])
const dialogVisible = ref(false)
const loading = ref(false)
const ruleFormRef = ref()
const ruleForm = ref({
    config: {}
})
const isEdit = ref(false)
const newRobotId = ref('')
let robotCopy = {}
const rules = ref({
    name: [
        {
            required: true,
            message: '请输入智能体名称',
            trigger: 'change',
        }
    ],
    description: [{
        required: true,
        message: '请输入智能体描述',
        trigger: 'change',
    }],
    type: [{
        required: true,
        message: '请选择智能体类型',
        trigger: 'change',
    }]
})
const modelTypeList = ref([])
const changeType = (e) => {
    ruleForm.value.config.model_type = ''
    if(e == 1){
        modelTypeList.value = [
            {
                value: 'workflow',
                label: 'Work_flow'
            },
            {
                value: 'chat',
                label: 'Chat'
            }
        ]
    }else{
        modelTypeList.value = [
            
            {
                value: 'chat',
                label: 'Chat'
            }
        ]
    }
}
const query = reactive({
    page: 1,
    page_size: 30
})
let robtoTotal = 0
const getTable = async () => {
    const res = await getAgents(query)
    robtoTotal = res.total
    console.log(res)
    if (res.list.length > 0) {
        let arr = res.list.map((el) => {
            el.config = JSON.parse(el.config)
            return el
        })
        console.log(arr)
        robotCards.value = [...robotCards.value, ...arr]
    }
    console.log(robotCards.value)
}
const listLoad = () => {
    console.log('到底了')
    if (robtoTotal > robotCards.value.length) {
        query.page++
        getTable()
    }

}
const handleAdd = () => {

    isEdit.value = false
    dialogVisible.value = true
    nextTick(() => {
        ruleForm.value = {
            config: {}
        }
        ruleFormRef.value.resetFields()

    })
}
let editItem = {}
let editIndex = 0
const handleEdit = (item, index) => {
    isEdit.value = true
    editItem = item
    editIndex = index
    ruleForm.value = JSON.parse(JSON.stringify(item))
    if(item.type == 1){
        modelTypeList.value = [
            {
                value: 'workflow',
                label: 'Work_flow'
            },
            {
                value: 'chat',
                label: 'Chat'
            }
        ]
    }else{
        modelTypeList.value = [
            {
                value: 'chat',
                label: 'Chat'
            }
        ]
    }
    dialogVisible.value = true
}
const mhtLoading = ref(false)
const submitRobot = async () => {
    await ruleFormRef.value.validate(async (valid, fields) => {
        if (valid) {
            mhtLoading.value = true
            if (isEdit.value) {
                try {
                    submitRobot.value = true
                    const res = await editRobot(ruleForm.value.id, {
                        description: ruleForm.value.description,
                        name: ruleForm.value.name,
                        config: JSON.stringify(ruleForm.value.config),
                        type: ruleForm.value.type
                    })
                    submitRobot.value = false
                    editItem = ruleForm.value
                    robotCards.value[editIndex] = editItem
                    console.log(editItem)
                    // editItem.config = JSON.parse(ruleForm.value.config)
                    // getTable()
                    mhtLoading.value = false
                    dialogVisible.value = false
                    ElNotification({
                        type: 'success',
                        message: '操作成功'
                    })
                } catch {
                    submitRobot.value = false
                    mhtLoading.value = false
                }

            } else {
                try {
                    submitRobot.value = true
                    let form = JSON.parse(JSON.stringify(ruleForm.value))
                    form.config = JSON.stringify(ruleForm.value.config)
                    const res = await addRobot(form)
                    submitRobot.value = false
                    // getTable()
                    robotCards.value.push({
                        ...ruleForm.value,
                        id: res.id
                    })
                    dialogVisible.value = false
                    mhtLoading.value = false
                    ElNotification({
                        type: 'success',
                        message: '操作成功'
                    })
                } catch {
                    submitRobot.value = false
                    mhtLoading.value = false
                }
            }

        } else {
        }
    })
}


const handleDelete = (item, index) => {
    ElMessageBox.confirm(
        '确认删除该智能体吗?',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            await deleteRobot(item.id)
            // getGroups()
            robotCards.value.splice(index, 1)

        })
        .catch(() => {

        })
}
const handleRobot = (row) => {
    return
}
const groupQuery = reactive({
    page: 1,
    page_size: 10
})
const total = ref(0)
const dialogGroup = ref(false)
const groupList = ref([])
const agentData = ref({})

const tableLoading = ref(false)
const openGroup = async (row) => {
    dialogGroup.value = true
    agentData.value = row
    groupList.value = []
    total.value = 0
    getGroups()

}
const getGroups = async () => {
    tableLoading.value = true
    const res = await agentGroups({
        agent_id: agentData.value.id,
        ...groupQuery
    })
    tableLoading.value = false
    groupList.value = res.list
    total.value = res.total
}
const handleSizeChange = (e) => {
    groupQuery.page = 1
    groupQuery.page_size = e
    getGroups()
}
const handleCurrentChange = (e) => {
    groupQuery.page = e
    getGroups()
}


// 使用的机器人

const contactQuery = reactive({
    page: 1,
    page_size: 10
})
const contactTotal = ref(0)
const dialogContact = ref(false)
const contactList = ref([])

const openContacts = async (row) => {
    dialogContact.value = true
    agentData.value = row
    contactList.value = []
    contactTotal.value = 0
    getContact()
    
}
const getContact = async () => {
    tableLoading.value = true
    const res = await agentContacts({
        agent_id: agentData.value.id,
        ...contactQuery
    })
    tableLoading.value = false
    contactList.value = res.list
    contactTotal.value = res.total
}
const contactSizeChange = (e) => {
    contactQuery.page = 1
    contactQuery.page_size = e
    getContact()
}
const contactCurrentChange = (e) => {
    contactQuery.page = e
    getContact()
}


// 日志
const logQuery = reactive({
    page: 1,
    page_size: 10
})
const logTotal = ref(0)
const dialogLog = ref(false)
const logList = ref([])
let agent_data = ''

const logLoading = ref(false)
const openLog = async (row) => {
    dialogLog.value = true
    agent_data = row
    tableLoading.value = true
    const res = await agentLogs({
        agent_id: row.id,
        type: row.type,
        ...logQuery
    })
    tableLoading.value = false
    logList.value = res.list.map((item) => {
        item.request_param = item.request_param ? JSON.parse(item.request_param) : ''
        item.response_data = item.response_data ? JSON.parse(item.response_data) : ''
        // item.error_msg = item.error_msg ? JSON.parse(item.error_msg) : ''
        return item
    })
    logTotal.value = res.total
    if(logLoading.value == true){
        logLoading.value = false
        ElNotification({
            type: 'success',
            message: '刷新成功'
        })
    }
}
const handleSizeChangeAgent = (e) => {
    logQuery.page = 1
    logQuery.page_size = e
    openLog(agent_data)
}
const handleCurrentChangeAgent = (e) => {
    logQuery.page = e
    openLog(agent_data)
}
const refreshLog = () => {
    logQuery.page = 1
    logLoading.value = true
    openLog(agent_data)
}
onMounted(() => {
    query.page = 1
    robotCards.value = []
    getTable()
    newRobotId.value = userRobotStore.robotInfo.id ? userRobotStore.robotInfo.id : ''
})
</script>
<style></style>
<style lang="scss" scoped>
.group-container {
    height: 100%;

    .infinite-list {
        height: 100%;
        padding: var(--el-main-padding);
        padding-right: 0;
    }

    .el-card {
        width: 380px;
        height: 190px;
        cursor: pointer;
        transition: all 0.3s;
        position: relative;
        float: left;
        margin-right: 20px;
        margin-bottom: 20px;
        padding: 5px;

        :deep(.el-card__body) {
            height: 100%;
        }

        .robot-title {
            overflow: hidden;
            margin-bottom: 10px;

            .robot-head {
                float: left;
                width: 60px;
                height: 60px;
                border-radius: 10px;
                transform: translateY(4px);
            }
            .robot-icon {
                float: left;
                width: 60px;
                height: 60px;
                border-radius: 10px;
                transform: translateY(4px);
                display: flex;
                align-items: center;
                justify-content: center;
                background-color: var(--el-color-primary-light-3);
                color: #fff;
                font-size: 14px;
                font-weight: bold;
                span{
                    transform: scaleY(1.3);

                }
            }

            p {
                float: left;
                padding-left: 10px;
                width: calc(100% - 66px);
            }
        }

        .use-count {
            font-size: 14px;
            margin-bottom: 5px;
            color: var(--el-color-primary);

        }

        label {
            display: inline-block;
            // font-weight: bold;
            line-height: 16px;
            margin-bottom: 6px;
            font-size: 12px;
            white-space: nowrap;
        }

        .name {
            font-size: 15px;
            font-weight: bold;
            margin-top: 4px;
        }

        .wx_name {
            display: block;
            color: var(--el-text-color-regular);
        }

        .description {
            font-size: 12px;
            line-height: 20px;
            // display: -webkit-box;
            // -webkit-box-orient: vertical;
            // /* 设置垂直排列 */
            // -webkit-line-clamp: 2;
            // /* 设置行数 */
            // overflow: hidden;
            // /* 设置超出省略 */
            // text-overflow: ellipsis;
            // /* 设置省略以...结尾 */

            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;

            color: var(--el-text-color-secondary);
        }

        &:hover {
            transform: translateY(-6px);
            background-color: var(--el-color-primary-light-7);
        }

        .icon-robot {
            font-size: 66px;
        }

        .act-icon {
            position: absolute;
            font-size: 40px;
            right: -2px;
            bottom: -8px;
            opacity: 0;
        }

    }

    .active-robot {
        .act-icon {
            opacity: 0.6;
        }
    }

    .add-robot {

        background-image: url('@/assets/images/add_robot_bg.png');
        background-color: var(--el-color-primary-light-5);
        background-size: 100% auto;

        &:hover {
            transform: translateY(-10px);
        }

        .add-box {
            height: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
            color: var(--el-color-primary);

            .el-icon {
                position: relative;
                top: -1px;
                margin-right: 3px;
            }
        }
    }

    .edit-icon {
        position: absolute;
        right: 15px;
        top: 14px;
        // display: none;
        height: 30px;
        width: 30px;
        text-align: center;
        line-height: 30px;
        border-radius: 8px;
        transition: all 0.1s;

        i {
            position: relative;
            left: 2px;
            top: 3px;
            color: var(--el-color-primary);
            // color: #fff;
            // transition: all 0.1s;
            // transform: rotate(90deg);
        }


    }


}

.popover-list {
    li {
        height: 32px;
        line-height: 32px;
        padding-left: 10px;
        // border-radius: 6px;
        cursor: pointer;

        // color: var(--el-color-primary);
        .el-icon {
            position: relative;
            top: 2px;
            margin-right: 4px;
        }

        &:hover {
            background-color: var(--el-color-primary-light-9);
        }
    }

    .rizhi-icon {
        color: var(--el-color-warning);
    }

    .edit-icon {
        color: var(--el-color-primary);
    }

    .delete-icon {
        color: var(--el-color-danger);
    }
}

.message-box {
    padding: 0px 30px;
    line-height: 20px;
    // width: 90wh;
    white-space: normal;
    word-break: break-all;
    .message-title{
        display: block;
    }
    p{
        margin-top: 20px;
        margin-bottom: 20px;
    }
  }
  .refresh-icon{
    color: var(--el-color-primary);
    cursor: pointer;
    position: relative;
    top: 3px;
    margin-left: 10px;
    font-size: 18px;
  }
</style>