<template>
    <div class="page">
        <div class="top adfac">
            <img src="@/assets/images/agent/arrow_left.png" @click="handleBack">
            <div class="spans">
                <span>知识库</span>
                <span class="last">&nbsp;/&nbsp;{{ title }}</span>
            </div>
        </div>
        <div class="content">
            <div class="c_top adfacjb">
                <div class="ct_l adfac">
                    <p>文件</p>
                    <el-input placeholder="搜索" suffix-icon="el-icon-search" v-model="queryParams.fileName" style="width: 300px;" @keyup.enter.native="getList"></el-input>
                </div>
                <div class="ct_r">
                    <el-button type="primary" icon="el-icon-plus" @click="handleAddFile">添加文件</el-button>
                </div>
            </div>
            <template v-if="list.length">
                <el-table :data="list" border cell-class-name="vertical-top-cell" v-loading="loading" empty-text="暂无文件" max-height="578px" style="margin-top: 16px;">
                    <el-table-column label="序号" width="50">
                        <template #default="scope">
                            {{ scope.$index + 1 }}
                        </template>
                    </el-table-column>
                    <el-table-column label="文件名称" prop="fileName"></el-table-column>
                    <el-table-column label="文件格式" prop="fileFormat"></el-table-column>
                    <el-table-column label="文件来源" prop="dataSources">
                        <template #default="scope">
                            {{ scope.row.dataSources === 'upload_file' ? '本地上传' : '未知' }}
                        </template>
                    </el-table-column>
                    <!-- <el-table-column label="字符数" prop="bbb"></el-table-column> -->
                    <el-table-column label="上传时间" prop="createDate"></el-table-column>
                    <!-- <el-table-column label="状态" prop="ddd">
                        <template #default="scope">
                            <div class="sdiv adfac">
                                <div class="sdian" :class="{'jxsb':scope.row.status===-1,'jxz':scope.row.status===0,'jxwc':scope.row.status===1}"></div>
                                <div class="stext">{{ statuscfg[scope.row.status]||'' }}</div>
                            </div>
                        </template>
                    </el-table-column> -->
                    <el-table-column label="操作" width="100">
                        <template #default="scope">
                            <el-button link type="text" size="mini" @click="handleDelete(scope.row)" v-hasPermi="['core:knowledgedata:delete']">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <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">
                    <img src="@/assets/images/agent/file_mini.png">
                    <p>还没有文档</p>
                    <p class="tip">您可以上传文件，从网站同步，或者从网络应用程序 (如概念、GitHub等) 同步。</p>
                    <el-button type="default" icon="el-icon-plus" @click="handleAddFile">添加文件</el-button>
                </div>
            </template>
        </div>
        <el-dialog width="40%" :visible.sync="show" title="上传文本文件" @close="cancel">
            <div class="cs_upload">
                <el-upload
                    class="upload-demo"
                    drag
                    :file-list="fileList"
                    :action="uploadUrl"
                    :headers="uploadHeaders"
                    :on-success="uploadFileSuccess"
                    :before-upload="beforeAvatarUpload"
                    :limit="1">
                    <i class="el-icon-upload"></i>
                    <div class="el-upload__text">点击或拖拽文件上传</div>
                    <div class="el-upload__text" style="font-size: 12px;color: #C1C7D2;line-height: 20px;margin-top: 8px;">
                        已支持 TXT、 MARKDOWN、 MDX、 PDF、 HTML、 XLSX、 XLS、 DOCX、 CSV、 VTT、<br> PROPERTIES、 MD、 HTM，每个文件不超过 15MB。
                    </div>
                </el-upload>
            </div>
            <div class="demo-drawer__footer" style="display: flex;justify-content: end;">
                <el-button :loading="buttonLoading" type="primary" @click="submitForm" v-hasPermi="['core:knowledgedata:save']">确认</el-button>
                <el-button @click="cancel" style="margin-right: 5%;">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script setup name="">
    import Cookies from "js-cookie";
    import { ref, getCurrentInstance, onMounted, nextTick } from 'vue'
    import {getKnowledgeFileList,addKnowledgeFile,deleteKnowledgeFile} from '@/api/agent/index.js'
    const { proxy } = getCurrentInstance();
    const uploadUrl = `${window.SITE_CONFIG["apiURL"]}/sys/oss/uploadFile`
    const uploadHeaders = {token:Cookies.get("token")}; 
    
    const statuscfg = {
        '-1':'解析失败',
        '0':'解析中',
        '1':'解析完成'
    }
    const title = ref('')
    const fileList = ref([])
    const list = ref([])
    const show = ref(false)
    const buttonLoading = ref(false)
    const queryParams = ref({
        baseId:'',
        page: 1,
        limit: 10,
        fileName:'',
        status:''
    })
    const total = ref(0)
    const loading = ref(false)
    const fileDto = ref({
        baseId:'',
        fileData:'',
        fileFormat:'',
        fileName:''
    })
    
    const uploadFileSuccess = e =>{
        fileList.value = [e.file];
        fileDto.value.fileData = e.data;
        proxy?.$modal.msgSuccess('上传成功');
    }
    const beforeAvatarUpload = (e) => {
        let name = e.name.split('.')[0];
        let type = e.name.split('.')[e.name.split('.').length-1];
        let isTxt = e.type === 'text/plain';
        let isPdf = e.type === 'application/pdf';
        let isHtml = e.type === 'text/html';
        let isExcel = e.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
        let isDocx = e.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
        if((type.toLowerCase() === 'xlsx' || type.toLowerCase() === 'xls' && isExcel) 
            || (type.toLowerCase() === 'docx' && isDocx)
            || (type.toLowerCase() === 'txt' && isTxt)
            || (type.toLowerCase() === 'pdf' && isPdf)
            || (type.toLowerCase() === 'html' && isHtml)
            && e.size <= 1024*1024*15){
            fileDto.value.fileName = name;
            fileDto.value.fileFormat = type;
        }else{
            proxy?.$modal.msgError('请上传txt、pdf、html、xlsx、xls或docx格式的文件！且文件大小不超过15MB！');
            fileDto.value.fileName = '';
            fileDto.value.fileFormat = '';
            return false;
        }
    }

    const handleBack = () => {
        proxy.$router.go(-1)
    }

    const handleAddFile = () => {
        show.value = true
    }

    const cancel = () => {
        fileList.value = [];
        fileDto.value = {
            baseId:'',
            fileData:'',
            fileFormat:'',
            fileName:''
        }
        show.value = false;
    }

    const submitForm = () => {
        if(!fileDto.value.fileData) return proxy?.$modal.msgError('请上传文件')
        buttonLoading.value = true;
        addKnowledgeFile(fileDto.value).then((res) => {
            if(res.code!==0) return proxy?.$modal.msgError(res.msg);
            proxy?.$modal.msgSuccess("上传成功");
            show.value = false;
            buttonLoading.value = false;
            getList();
        })
    }

    const getList = () => {
        loading.value = true;
        getKnowledgeFileList(queryParams.value).then((res) => {
            loading.value = false;
            list.value = res.data || [];
            total.value = res.data.total;
        })
    }
    const handleSizeChange = (val) => {
        queryParams.value.limit = val;
        getList()
    }

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

    async function handleDelete(row) {
        await proxy?.$modal.confirm('确认删除文件【' + row.fileName + '】吗？').finally(() => loading.value = false);
        let res = await deleteKnowledgeFile([row.id]);
        if (res.code === 0) proxy?.$modal.msgSuccess("删除成功");
        else return proxy?.$modal.msgError(res.msg);
        await getList();
    }

    onMounted(() => {
        title.value = proxy.$route.query.title;
        queryParams.value.baseId = proxy.$route.query.id;
        fileDto.value.baseId = proxy.$route.query.id;
        nextTick(() => {
            getList()
        })
    })
</script>

<style scoped lang="scss">
    .page{
        background: #FAFAFA;
        .top{
            width: 100%;
            height: 64px;
            background: #FFFFFF;
            border-bottom: 1px solid #F3F4F6;
            
            img{
                width: 36px;
                height: 36px;
                margin-left: 16px;
                cursor: pointer;
            }
            .spans{
                display: flex;
                align-items: center;
                margin-left: 23px;
                span{
                    font-family: PingFangSC, PingFang SC;
                    font-weight: 400;
                    font-size: 14px;
                    color: #6B7280;
                    line-height: 14px;
                    &.last{
                        color: #111111;
                    }
                }
            }
        }
        
        .content{
            width: calc(100% - 24px);
            height: calc(100vh - 88px);
            margin: 12px;
            background: #FFFFFF;
            border-radius: 6px 6px 0px 0px;
            border: 1px solid #F3F4F6;
            padding: 24px 20px;
            box-sizing: border-box;
            .ct_l{
                p{
                    font-family: PingFang-SC, PingFang-SC;
                    font-weight: bold;
                    font-size: 16px;
                    color: #252525;
                    line-height: 22px;
                    width: 60px;
                }
            }

            .empty{
                width: 780px;
                height: 236px;
                background: #F9FAFB;
                border-radius: 8px;
                
                margin: 220px auto 0;
                padding: 36px 49px;
                box-sizing: border-box;
                img{
                    width: 36px;
                    height: 36px;
                }
                p{
                    font-family: PingFang-SC, PingFang-SC;
                    font-weight: bold;
                    font-size: 16px;
                    color: #393939;
                    line-height: 16px;
                    margin-top: 16px;
                    &.tip{
                        font-size: 14px;
                        color: #999999;
                        margin-bottom: 30px;
                    }
                }
            }
        }

        .sdiv{
            .sdian{
                width: 8px;
                height: 8px;
                border-radius: 50%;
                &.jxsb{
                    background: rgb(196, 33, 33);
                }
                &.jxz{
                    background: #FFd750;
                }
                &.jxwc{
                    background: #22C55D;
                }
            }
            .stext{
                font-family: PingFangSC, PingFang SC;
                font-weight: 400;
                font-size: 14px;
                color: #393939;
                line-height: 20px;
                margin-left: 6px;
            }
        }
    }
    
    .cs_upload{
        width: calc(100% - 20px);
        margin: -10px auto 30px;
    }

    ::v-deep .el-dialog__title{
        font-weight: bold !important;
    }
    ::v-deep .el-dialog{
        margin-top: 25vh !important;
    }
    ::v-deep .el-upload,::v-deep .el-upload-dragger{
        width: 100% !important;
        background: #FAFAFB !important;
    }
</style>