<template>
  <div class="search-table-box aidex-table" v-loading="textLoading" element-loading-text="数据处理中">
    <el-row :gutter="0">
      <!-- 知识库 -->
      <el-col :span="6" >
        <!-- 左侧分类列表 -->
        <div class="sidebar">
          <div class="sidebar-left-title">
            <span>文档列表</span>
            <el-button icon="el-icon-circle-plus-outline" type="text" @click="openDocumentAdd()"/>
          </div>
          <div v-if="knowledgeDocList.length===0" class="no-data">
            <el-empty :image-size="50"/>
          </div>
          <div
            v-else
            v-for="(item, index) in knowledgeDocList"
            :key="item.id"
            :class="['sidebar-item', { active: selectedDocID === item.document_id }]"
            @click="handleKnowledgeSelect(item)">
            <!-- 图标区域 -->
            <div class="sidebar-icon">
              <img v-if="item.icon_url" :src="item.icon_url" alt="图标" class="icon-image"/>
              <i v-else class="el-icon-tickets" style="color: #ffc107;"></i>
            </div>
            <!-- 标题区域 -->
            <div class="sidebar-title">{{ item.name }}</div>
          </div>
        </div>
      </el-col>

      <!--知识库文件-->
      <el-col :span="18">
        <div class="right-doc" v-if="knowledgeDocInfo.name!=null">
          <div class="right-doc-top">
            <div class="right-dov-top-icon">
              <img v-if="knowledgeDocInfo.icon_url" :src="knowledgeDocInfo.icon_url" alt="图标" class="icon-image"/>
              <i v-else class="el-icon-tickets" style="color: #ffc107;"></i>
            </div>
            <div>
              {{ knowledgeDocInfo.name == null ? '----' : knowledgeDocInfo.name }}
            </div>
            <div class="right-doc-top-button-edit">
              <el-button icon="el-icon-edit" type="text" @click="handleDocumentUpdate(knowledgeDocInfo)"/>
            </div>
            <div class="right-doc-top-button-del">
              <el-button icon="el-icon-delete" type="text" @click="handleDocumentDelete(knowledgeDocInfo)"/>
            </div>
          </div>
          <div class="right-doc-bottom">
            <div class="right-doc-bottom-info">
              <div class="text-info">
                <document-previewer :preview-url="previewUrl" :web-url="webUrl"/>
              </div>
            </div>
          </div>
        </div>
        <div class="right-doc" v-else>
          <el-empty :image-size="50" class="no-data"/>
        </div>
      </el-col>

    </el-row>

    <!-- 添加-知识库文件 -->
    <el-dialog title="创建知识库文件" :visible.sync="openAdd" width="500px" append-to-body>
      <div v-loading="updateLoading" element-loading-text="数据处理中">
        <el-form ref="addForm" :model="addForm" :rules="addRules" label-position="top" label-width="120px">
          <el-form-item label="上传文件列表" prop="document_list">
            <file-upload v-model="addForm.document_list" :fileType='["txt", "doc", "docx", "pdf"]' :limit="10"/>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="addSubmitForm">确 定</el-button>
          <el-button @click="addCancel">取 消</el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 修改-知识库文件名称 -->
    <el-dialog title="重命名" :visible.sync="openUpdateName" width="500px" append-to-body>
      <el-form ref="updateNameForm" :model="updateNameForm" :rules="updateNameRules" label-position="top" label-width="120px">
        <el-form-item label="知识库文件新名称" prop="name">
          <el-input
            type="textarea"
            v-model="updateNameForm.name"
            placeholder="请输入知识库文件新名称"
            :rows="4"
            maxlength="100"
            show-word-limit/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="upNameSubmitForm">确 定</el-button>
        <el-button @click="upNameCancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {listKnowledgeDocText, updateDocumentName, addDocument, deleteDocument} from "@/api/business/aimodel/knowledgeDocument"
import DocumentPreviewer from "@/views/business/aimodel/viewer/DocumentPreviewer.vue";

export default {
  name: "textDoc",
  components: {DocumentPreviewer},
  data() {
    return {
      // 遮罩层
      textLoading: true,
      // 知识库文件列表
      knowledgeDocList: [],
      selectedDocID: null,// 初始未选中 文件ID
      knowledgeDocInfo: {},
      previewUrl: "",//文档内容预览地址
      webUrl: "",//下载地址
      updateLoading: false,

      oldDatasetId: null,//初始选中知识库ID

      //重命名
      openUpdateName: false,
      updateNameForm: {},
      updateNameRules: {
        name: [
          {required: true, message: "请输入新名称", trigger: "blur"},
          {min: 1, max: 100, message: "长度在 1 到 100 个字符", trigger: "blur"}
        ]
      },

      //创建
      openAdd: false,
      addForm: {},
      addRules: {
        document_list: [
          {required: true, message: "请上传文件", trigger: "blur"},
        ]
      },


    };
  },
  methods: {
    selectedDatasetDoc(datasetId) {
      this.oldDatasetId = datasetId;
      this.getKnowledgeDocTextList(datasetId);
    },
    /** 查询知识库列表 */
    getKnowledgeDocTextList(datasetId) {
      listKnowledgeDocText({"dataset_id": datasetId}).then(response => {
        this.knowledgeDocList = response.data;
        // 自动选中第一个
        if (this.knowledgeDocList.length > 0) {
          this.selectedDocID = this.knowledgeDocList[0].document_id;
          this.handleKnowledgeSelect(this.knowledgeDocList[0]);
        } else {
          this.knowledgeDocInfo = {};
        }
        this.textLoading = false;
      });
    },
    /*点击菜单*/
    handleKnowledgeSelect(item) {
      this.selectedDocID = item.document_id;
      this.knowledgeDocInfo = item;
      this.previewUrl = this.knowledgeDocInfo.preview_tos_url === null ? this.knowledgeDocInfo.web_url : this.knowledgeDocInfo.preview_tos_url;
      this.webUrl = this.knowledgeDocInfo.web_url;
    },


    // 表单重置
    upNameReset() {
      this.updateNameForm = {
        document_id: null,
        name: null,
      };
      this.resetForm("updateNameForm");
    },
    /** 重命名-打开窗口 */
    handleDocumentUpdate(knowledgeDocInfo) {
      this.upNameReset();
      this.updateNameForm.document_id = knowledgeDocInfo.document_id;
      this.updateNameForm.name = knowledgeDocInfo.name;
      this.openUpdateName = true;
    },
    /** 重命名-修改提交 */
    upNameSubmitForm() {
      this.$refs["updateNameForm"].validate(valid => {
        if (valid) {
          updateDocumentName(this.updateNameForm).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.openUpdateName = false;
            this.selectedDatasetDoc(this.oldDatasetId);
          });
        }
      });
    },
    /** 重命名-取消按钮 */
    upNameCancel() {
      this.openUpdateName = false;
      this.upNameReset();
    },

    /** 创建-表单重置 **/
    addReset() {
      this.addForm = {
        dataset_id: null,
        document_list: null,
      };
      this.resetForm("addForm");
    },
    /** 创建-打开窗口 */
    openDocumentAdd() {
      this.addReset();
      this.addForm.dataset_id = this.oldDatasetId;
      this.openAdd = true;
    },
    /** 创建-取消按钮 */
    addCancel() {
      this.openAdd = false;
      this.addReset();
    },
    /** 创建-修改提交 */
    addSubmitForm() {
      this.$refs["addForm"].validate(valid => {
        if (valid) {
          this.updateLoading = true;
          addDocument(this.addForm).then(response => {
            this.$modal.msgSuccess("创建成功");
            this.openAdd = false;
            this.updateLoading = false;
            this.selectedDatasetDoc(this.oldDatasetId);
          });
        }
      });
    },

    /** 删除知识库-文本 **/
    handleDocumentDelete(knowledgeDocInfo) {
      this.$modal.confirm('是否确认删除"' + knowledgeDocInfo.name + '"知识库文件？').then(function () {
        return deleteDocument({'document_id': knowledgeDocInfo.document_id});
      }).then(() => {
        this.selectedDatasetDoc(this.oldDatasetId);
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },

  }
};
</script>

<style scoped>

.sidebar {
  padding: 15px 10px;
  height: calc(100vh - 105px);
  background-color: #ffffff;
  overflow: auto;
  border: 1px solid #52649a21;
  border-top-left-radius: 5px;
  border-bottom-left-radius: 5px;

  .sidebar-left-title {
    font-size: 14px;
    color: #52649a;
    margin-bottom: 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .sidebar-item {
    display: flex;
    align-items: center;
    padding: 2px 5px;
    margin-bottom: 10px;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.3s ease;
  }

  .sidebar-item:hover {
    background: #e9ecef;
  }

  .sidebar-item.active {
    background: #5768a114;
  }

  .sidebar-icon {
    width: 30px;
    height: 30px;
    display: flex; /* 添加这一行，让图标在内部也能垂直居中 */
    align-items: center; /* 添加这一行，让图标在内部垂直居中 */
    justify-content: center; /* 添加这一行，让图标在内部水平居中 */
  }

  .icon-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
    border-radius: 4px;
  }

  .sidebar-title {
    font-size: 14px;
    line-height: 1.5;
  }

  .no-data {
    display: flex;
    justify-content: center;
    align-items: center;
    height: calc(100vh - 185px) !important;
  }
}

.right-doc {
  height: calc(100vh - 105px);
  background-color: #FFFFFF;
  border-top-right-radius: 5px;
  border-bottom-right-radius: 5px;
  border: 1px solid #52649a21;
  border-left: none;
  display: flex;
  flex-direction: column; /* 设置垂直排列 */

  .right-doc-top {
    height: 60px;
    border-bottom: 1px solid #52649a21;
    display: flex;
    align-items: center;
    padding: 0 10px;
    color: #0f1528d1;
    font-size: 14px;

    .right-dov-top-icon {
      width: 20px;
    }

    .right-doc-top-button-edit {
      margin-left: 10px;
    }

    .right-doc-top-button-del {
      margin-left: auto; /* 使删除按钮右对齐 */
    }
  }

  .right-doc-bottom {
    flex: 1;

    .right-doc-bottom-info {
      height: calc(100vh - 165px);
      padding: 16px;
      overflow: auto;

      .text-info {
        background-color: #5a6ca70a;
        border: 1px solid #52649a21;
        border-radius: 8px;
        color: #0f1528d1;
        font-size: 14px;
        line-height: 20px;
        margin-bottom: 8px;
        padding: 8px;
        position: relative;
        word-break: break-word;
      }
    }
  }
}

</style>
