<template>
    <div class="agent_page">
        <div class="top adfacjb">
            <div class="left">知识库管理</div>
            <div class="right adfac">
                <div class="r_query adfacjb queryInput">
                    <el-input v-model="queryParams.baseName" placeholder="请输入知识库名称查询" @keyup.enter.native="getList"></el-input>
                    <img src="@/assets/images/agent/query_mini.png">
                </div>
                <div class="r_add" @click="show=true">+ 创建知识库</div>
            </div>
        </div>
        <template v-if="list.length">
            <div class="list">
                <div class="item" v-for="(item, index) in list" :key="index" @click.self="handleFileList(item)">
                    <div class="i_top adfac" @click.self="handleFileList(item)">
                        <img src="@/assets/images/agent/file_mini.png">
                        <div class="texts">
                            <p>{{ item.baseName }}</p>
                            <p>知识库<span>{{ item.dataNum||0 }}</span></p>
                        </div>
                    </div>
                    <div class="i_txt" @click.self="handleFileList(item)">{{ item.description||'' }}</div>
                    <div class="i_bottom adfacjb">
                        <div class="ib_l adfac" @click="handleTag(item)">
                            <img src="@/assets/images/agent/tag_mini.png">
                            <span>添加标签</span>
                        </div>
                        <div class="ib_r">
                            <el-popover placement="bottom" width="128" trigger="hover" v-model="pvisibles[index]">
                                <div class="tl_czs">
                                    <div class="tlc_pre" @click="handleSet(item,index)">设置</div>
                                    <div class="tlc_pre del" @click="handleDelete(item)">删除</div>
                                </div>
                                <img slot="reference" src="@/assets/images/agent/more_mini.png" @click="handleShowPop(index)">
                            </el-popover>
                        </div>
                    </div>
                </div>
            </div>
            <el-row style="display: flex;justify-content: center;">
                <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="queryParams.page"
                    :page-sizes="[5, 10, 20, 50]"
                    :page-size="10"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total"
                    v-show="total > 0">
                </el-pagination>
            </el-row>
        </template>
        <template v-else>
            <div class="empty adffcacjc">
                <img src="@/assets/images/agent/knowledge_empty.png">
                <p>暂无知识库</p>
            </div>
        </template>
        <el-dialog width="579px" :visible.sync="show" title="创建知识库" @close="cancel">
            <div class="zsk_tip">知识库中还没有文档，你可以在今后任何时候上传文档至该知识库</div>
            <el-form ref="zskRef" :model="form" :rules="rules" label-width="100px" style="width: 90%;margin: 0 auto;" label-position="top">
                <el-form-item label="知识库名称" prop="baseName">
                    <el-input v-model="form.baseName" placeholder="请输入知识库名称"></el-input>
                </el-form-item>
            </el-form>
            <div class="demo-drawer__footer" style="display: flex;justify-content: end;">
                <el-button :loading="buttonLoading" type="primary" @click="submitForm">创建</el-button>
                <el-button @click="cancel" style="margin-right: 5%;">取 消</el-button>
            </div>
        </el-dialog>
        <el-dialog width="30%" :visible.sync="tagShow" title="新增标签" @close="tagShow=false">
            <div class="ed_box">
                <div class="eb_title">已有标签</div>
                <div class="eb_list">
                    <div class="ebl_item adfacjb" v-for="(item, index) in tagList" :key="index">
                        <div class="el_l">
                            <el-input v-model="item.name" placeholder="请输入标签名称"></el-input>
                        </div>
                        <img src="@/assets/images/agent/delete_mini.png" class="el_r" @click="handleDeleteTag(item,index)">
                    </div>
                </div>
                <div class="eb_add" @click="handleAddTag">+添加标签</div>
            </div>
            <div class="demo-drawer__footer" style="display: flex;justify-content: end;margin-top: 100px;">
                <el-button :loading="buttonLoading2" type="primary" @click="submitForm2">确 定</el-button>
                <el-button @click="cancel2" style="margin-right: 5%;">取 消</el-button>
            </div>
        </el-dialog>
        <el-dialog width="579px" :visible.sync="setShow" title="知识库设置" @close="cancel3">
            <el-form ref="setRef" :model="zskForm" :rules="zskRules" label-width="120px" style="width: 90%;margin: 0 auto;" label-position="top">
                <el-form-item label="知识库名称" prop="baseName">
                    <el-input v-model="zskForm.baseName" placeholder="请输入知识库名称"></el-input>
                </el-form-item>
                <el-form-item label="知识库描述" prop="description">
                    <el-input type="textarea" :rows="2" v-model="zskForm.description" placeholder="请输入知识库描述"></el-input>
                </el-form-item>
            </el-form>
            <div class="demo-drawer__footer" style="display: flex;justify-content: end;">
                <el-button :loading="buttonLoading3" type="primary" @click="submitForm3">保存</el-button>
                <el-button @click="cancel3" style="margin-right: 5%;">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script setup name="">
    import { ref, getCurrentInstance, onMounted } from 'vue'
    import {getKnowledgeList,addKnowledge,updateKnowledge,getKnowledgeInfo,deleteKnowledge} from '@/api/agent/index.js'
    const { proxy } = getCurrentInstance();
    
    const queryParams = ref({
        page:1,
        limit:10,
        baseName: ''
    })
    const total = ref(0)
    const pvisibles = ref([false,false])
    const show = ref(false)
    const tagShow = ref(false)
    const buttonLoading = ref(false)
    const buttonLoading2 = ref(false)
    const buttonLoading3 = ref(false)
    const setShow = ref(false)
    const tagList = ref([])
    const list = ref([])
    const form = ref({
        id:'',
        coachId:proxy.$store.state.user.id,
        baseName: '',
        description: '',
        labels:''
    })
    const rules = ref({
        baseName: [
            { required: true, message: '请输入知识库名称', trigger: 'blur' }
        ]
    })
    const zskRef = ref(null)
    const setRef = ref(null)
    const zskForm = ref({
        id:'',
        baseName: '',
        coachId:proxy.$store.state.user.id,
        description: '',
        labels:''
    })
    const zskRules = ref({
        baseName: [
            { required: true, message: '请输入知识库名称', trigger: 'blur' }
        ],
        description: [
            { required: true, message: '请输入知识库描述', trigger: 'blur' }
        ]
    })

    const submitForm = () => {
        proxy.$refs.zskRef.validate((valid) => {
            if (valid) {
                addKnowledge(form.value).then(res => {
                    if(res.code!==0) return proxy.$message.error(res.msg)
                    proxy.$message.success('创建成功')
                    show.value = false;
                    getList()
                })
                
            } else {
                return false;
            }
        });
    }
    const cancel = () => {
        show.value = false;
        form.value = {
            id:'',
            coachId:proxy.$store.state.user.id,
            baseName: '',
            description: '',
            labels:''
        }
        proxy.$refs.zskRef.resetFields();
    }

    const handleFileList = (item) => {
        console.log(item)
        proxy.$router.push({path: 'agentKnowledgeFile', query:{title: item.baseName,id:item.id}})
    }

    const handleShowPop = (index) => {
        pvisibles.value[index] = true;
    }

    const handleSet = (item,index) => {
        zskForm.value = {...zskForm.value, ...item}
        setShow.value = true;
        pvisibles.value[index] = false;
    }

    const handleDelete = (item) => {
        proxy.$confirm('删除知识库是不可逆的。用户将无法再访问您的知识库，所有的提示配置和日志将被永久删除。', '删除后无法恢复，确认删除吗？', {
            confirmButtonText: '确定',
            confirmButtonColor: '#FD4F66',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            deleteKnowledge(item.id).then((res)=>{
                if(res.code!==0) return proxy.$message.error(res.msg)
                proxy.$message.success('删除成功')
                getList()
            })
        }).catch(() => {});
    }

    const handleTag = (item) => {
        form.value = {...form.value, ...item}
        tagList.value = item?.labels?.split(',').map(l => ({name: l}))||[];
        tagShow.value = true;
    }
    const handleDeleteTag = (item, index) => {
        tagList.value?.splice(index, 1);
    }

    const handleAddTag = () => {
        tagList.value.push({name: ''});
    }

    const submitForm2 = () => {
        if(tagList.value.length === 0) return proxy.$message.error('请至少输入一条标签')
        form.value.labels = tagList.value.map(item => item.name).join(',');
        buttonLoading2.value = true;
        updateKnowledge(form.value).then((res)=>{
            if(res.code!==0) return proxy.$message.error(res.msg)
            proxy.$message.success('添加成功')
            tagShow.value = false;
            buttonLoading2.value = false;
            getList();
        })
    }
    const cancel2 = () => {
        tagShow.value = false;
        form.value = {
            id:'',
            coachId:proxy.$store.state.user.id,
            baseName: '',
            description: '',
            labels:''
        }
    }

    const submitForm3 = () => {
        proxy.$refs.setRef.validate((valid) => {
            if (valid) {
                buttonLoading3.value = true;
                updateKnowledge(zskForm.value).then((res)=>{
                    if(res.code!==0) return proxy.$message.error(res.msg)
                    proxy.$message.success('修改成功')
                    setShow.value = false;
                    buttonLoading3.value = false;
                    getList();
                })

            } else {
                return false;
            }
        });
    }
    const cancel3 = () => {
        setShow.value = false;
        zskForm.value = {
            id:'',
            coachId:proxy.$store.state.user.id,
            baseName: '',
            description: '',
            labels:''
        }
        proxy.$refs.setRef.resetFields();
    }

    const getList = () => {
        getKnowledgeList(queryParams.value).then((res)=>{
            if(res.code!==0) return proxy.$message.error(res.msg);
            list.value = res.data.list;
            total.value = res.data.total
        })
    }

    const handleCurrentChange = (val) => {
        queryParams.value.page = val;
        getList()
    }
    const handleSizeChange = (val) => {
        queryParams.value.limit = val;
        getList()
    }

    onMounted(()=>{
        getList();
    })
</script>

<style scoped lang="scss">
    ::v-deep .queryInput .el-input__inner{
        border: none !important;
        height: 30px !important;
        line-height: 30px !important;
        padding: 0 !important;
        width: 200px !important;
    }

    .agent_page{
        .top{
            width: 100%;
            padding: 20px;
            box-sizing: border-box;
            border-bottom: 1px solid #E5E7EB;
            .left{
                font-family: PingFang-SC, PingFang-SC;
                font-weight: bold;
                font-size: 16px;
                color: #111111;
                line-height: 16px;
            }
            .right{
                .r_query{
                    width: 278px;
                    height: 34px;
                    border-radius: 6px;
                    border: 1px solid #E2E7F5;
                    padding: 0 16px;
                    box-sizing: border-box;
                    img{
                        width: 16px;
                        height: 16px;
                        cursor: pointer;
                    }
                }
                .r_add{
                    width: 110px;
                    height: 36px;
                    background: #761E6A;
                    border-radius: 6px;
                    margin-left: 16px;
                    font-family: PingFangSC, PingFang SC;
                    font-weight: 400;
                    font-size: 14px;
                    color: #FFFFFF;
                    line-height: 36px;
                    text-align: center;
                    cursor: pointer;
                }
            }
        }

        .list{
            margin-left: -16rpx;
            display: flex;
            flex-wrap: nowrap;
            .item{
                width: calc(100% / 3 - 16px);
                margin: 26px 0 0 16px;
                min-height: 168px;
                background: #FFFFFF;
                border-radius: 8px;
                border: 1px solid #E5E7EB;
                padding: 16px;
                box-sizing: border-box;
                position: relative;
                cursor: pointer;
                .i_top{
                    &>img{
                        width: 36px;
                        height: 36px;
                    }
                    .texts{
                        padding-left: 16px;
                        p{
                            font-family: PingFang-SC, PingFang-SC;
                            font-weight: bold;
                            font-size: 14px;
                            color: #393939;
                            line-height: 14px;
                            &:last-child{
                                font-family: PingFangSC, PingFang SC;
                                font-weight: 400;
                                font-size: 14px;
                                color: #A4A4A4;
                                line-height: 14px;
                                margin-top: 8px;
                                span{
                                    font-weight: bold;
                                    color: #6B7280;
                                    margin-left: 5px;
                                }
                            }
                        }
                    }
                }
                .i_txt{
                    font-family: PingFangSC, PingFang SC;
                    font-weight: 400;
                    font-size: 14px;
                    color: #A4A4A4;
                    line-height: 24px;
                    margin-top: 16px;
                }
                .i_bottom{
                    width: calc(100% - 32px);
                    position: absolute;
                    left: 16px;
                    bottom: 16px;
                    .ib_l{
                        cursor: pointer;
                        img{
                            width: 16px;
                            height: 16px;
                        }
                        span{
                            font-family: PingFangSC, PingFang SC;
                            font-weight: 400;
                            font-size: 14px;
                            color: #A4A4A4;
                            line-height: 24px;
                            margin-left: 6px;
                        }
                    }
                    .ib_r{
                        cursor: pointer;
                        img{
                            width: 32px;
                            height: 32px;
                        }
                    }
                }
            }
        }

        .empty{
            width: 100%;
            height: calc(100% - 77px);
            img{
                width: 64px;
                height: 61px;
            }
            p{
                font-family: PingFangSC, PingFang SC;
                font-weight: 400;
                font-size: 14px;
                color: #9CA3AF;
                line-height: 14px;
                margin-top: 16px;
            }
        }

        .zsk_tip{
            font-family: PingFangSC, PingFang SC;
            font-weight: 400;
            font-size: 5rpx;
            color: #6B7280;
            line-height: 8rpx;
            margin: -30px 0 20px;
        }
    }

    .tl_czs{
        .tlc_pre{
            font-family: PingFangSC, PingFang SC;
            font-weight: 400;
            font-size: 14px;
            color: #393939;
            line-height: 20px;
            padding: 14px 20px;
            border-bottom: 1px solid #E5E7EB;
            cursor: pointer;
            &.del{
                color: #FD4F66;
                border: none;
            }
        }
    }

    .ed_box{
        .eb_title{
            font-family: PingFangSC, PingFang SC;
            font-weight: 400;
            font-size: 14px;
            color: #252525;
            line-height: 20px;
        }
        .eb_list{
            margin-top: 3px;
            .ebl_item{
                margin-top: 10px;
                .el_l{
                    width: calc(100% - 44px);
                }
                .el_r{
                    width: 18px;
                    height: 18px;
                    cursor: pointer;
                }
            }
        }
        .eb_add{
            font-family: PingFangSC, PingFang SC;
            font-weight: 400;
            font-size: 14px;
            color: #761E6A;
            line-height: 20px;
            margin-top: 17px;
            cursor: pointer;
        }
    }

    ::v-deep .el-dialog__title{
        font-weight: bold !important;
    }
    ::v-deep .el-dialog{
        margin-top: 25vh !important;
    }
    
</style>