<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="知识库" prop="datasetId">
        <el-select v-model="queryParams.datasetId" placeholder="请选择所属知识库" clearable size="small">
          <el-option
            v-for="item in datasetIdList"
            :key="item.datasetId"
            :label="item.name"
            :value="item.datasetId"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="集合名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入集合名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['fastGpt:fastGptCollection:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['fastGpt:fastGptCollection:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-more-outline"
          size="mini"
          @click="handleSync(datasetId)"
          v-hasPermi="['fastGpt:fastGptCollection:sync']"
        >同步集合</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="fastGptCollectionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="集合id" align="center" prop="collectionId" />
      <el-table-column label="类型" align="center" prop="type"  />
<!--      <el-table-column label="知识库的ID" align="center" prop="datasetId" width="" />-->
      <el-table-column label="集合名称" align="center" prop="name" />
      <el-table-column label="原文本" align="center" prop="text" v-if="fastGptCollectionList.some(item => item.type === 'text')" />
      <el-table-column label="训练类型" align="center" prop="trainingType">
        <template slot-scope="scope">
          <span v-for="(item,index) in trainingTypeOptions" v-if="scope.row.trainingType==item.dictValue">{{item.dictLabel}}</span>
        </template>
      </el-table-column>
      <el-table-column label="chunk长度" align="center" prop="chunkSize"    v-if="fastGptCollectionList.some(item => item.type !== 'folder' && item.type !== 'virtual')" />
      <el-table-column label="自定义最高优先分割符号" align="center" prop="chunkSplitter"      v-if="fastGptCollectionList.some(item => item.type !== 'folder' && item.type !== 'virtual')"/>
      <el-table-column label="qa拆分自定义提示词" align="center" prop="qaPrompt"      v-if="fastGptCollectionList.some(item => item.type !== 'folder' && item.type !== 'virtual')">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" :content="scope.row.qaPrompt" placement="top">
            <div style="display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 3; overflow: hidden; text-overflow: ellipsis;">
              <span>{{ scope.row.qaPrompt }}</span>
            </div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="网络链接" align="center" prop="link" v-if="fastGptCollectionList.some(item => item.type === 'link')" />
      <el-table-column label="文件链接" align="center" prop="fileUrl" v-if="this.fastGptCollectionList.some(item => item.type === 'file')" />
      <el-table-column label="文件名称" align="center" prop="fileName" v-if="this.fastGptCollectionList.some(item => item.type === 'file')" />
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180"/>
      <el-table-column label="集合禁用状态" align="center" prop="forbid" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['fastGpt:fastGptCollection:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['fastGpt:fastGptCollection:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改集合对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="150px">
<!--        <el-form-item label="集合类型" prop="type">-->
<!--          <el-select v-model="form.type" placeholder="请选择集合类型">-->
<!--            <el-option-->
<!--              v-for="item in allCollectionOptions"-->
<!--              :key="item.dictValue"-->
<!--              :label="item.dictLabel"-->
<!--              :value="item.dictValue"-->
<!--            />-->
<!--          </el-select>-->
<!--        </el-form-item>-->
<!--        -->
        <el-form-item label="知识库" prop="datasetId" placeholder="请选择所属知识库" >
          <el-select v-model="form.datasetId" clearable size="small">
            <el-option
              v-for="item in datasetIdList"
              :key="item.datasetId"
              :label="item.name"
              :value="item.datasetId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="集合名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入集合名称" />
        </el-form-item>


        <el-form-item label="原文本内容" prop="text" v-if=" form.type==='text'">
          <el-input v-model="form.text" type="textarea" placeholder="请输入文本内容" />
        </el-form-item>
        <el-form-item label="训练类型" prop="trainingType" v-if="form.type && (form.type !== 'folder' && form.type !== 'virtual')">
          <el-select v-model="form.trainingType" placeholder="请选择chunk(按文本长度进行分割),qa(QA拆分)" @change="updateChunkSize">
            <el-option
              v-for="item in trainingTypeOptions"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="每个chunk 的长度" prop="chunkSize" v-if="form.type && (form.type !== 'folder' && form.type !== 'virtual')">
          <el-input v-model="form.chunkSize" type="Number" placeholder="chunk模式:100~3000,qa模式:4000~模型最大token(16k模型通常建议不超过10000)"
                    @blur="validateChunkSize"
                    :placeholder="chunkSizePlaceholder"/>
        </el-form-item>
        <el-form-item label="自定义优先分割符号" prop="chunkSplitter" v-if="form.type && (form.type !== 'folder' && form.type !== 'virtual')">
          <el-input v-model="form.chunkSplitter" placeholder="请输入自定义最高优先分割符号" />
        </el-form-item>
        <el-form-item label="qa拆分自定义提示词" prop="qaPrompt" v-if="form.type && (form.type !== 'folder' && form.type !== 'virtual')">
          <el-input v-model="form.qaPrompt" placeholder="请输入qa拆分自定义提示词" />
        </el-form-item>
        <el-form-item label="网络链接" prop="link" v-if="form.type==='link'" >
          <el-input v-model="form.link" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="上传文件" prop="fileUrl" v-if="form.type==='file'">
          <el-upload v-model="form.fileUrl"
                     class="avatar-uploader"
                     :action="uploadUrl"
                     :show-file-list="false"
                     :on-success="handleAvatarSuccess"
                     :before-upload="beforeAvatarUploadFile">
            <i class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <span  v-if="fileNameDisPlay">{{form.fileName}}</span>
          <el-link style="margin-left: 10px"  v-if="form.fileUrl" type="primary" :href="downloadUrl(form.fileUrl)" download>
            下载文件
          </el-link>
          </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listFastGptCollection, getFastGptCollection, delFastGptCollection, addFastGptCollection, updateFastGptCollection, exportFastGptCollection,syncCollection } from "@/api/fastGpt/fastGptCollection";
import {getAllDataSetList} from "../../../api/fastGpt/fastGptDataset";

export default {
  name: "FastGptCollection",
  data() {
    return {
      //存储知识库id
      datasetId:null,

      fileNameDisPlay:false,
      //上传地址
      uploadUrl:process.env.VUE_APP_BASE_API+"/common/uploadOSS",
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      //训练类型
      trainingTypeOptions: [],
      //空集合的类型
      // collectionTypeOptions:[],
      //所有集合类型
      allCollectionOptions:[],
      // 集合表格数据
      fastGptCollectionList: [],
      //知识库列表
      datasetIdList:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type: null,
        datasetId: null,
        name: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        type: [
          { required: true, message: "不能为空", trigger: "blur" }
        ],
        datasetId: [
          { required: true, message: "不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "不能为空", trigger: "blur" }
        ],
        trainingType:[
          { required: true, message: "不能为空", trigger: "blur" }
        ],
        link:[
          { required: true, message: "不能为空", trigger: "blur" }
        ]

      }
    };
  },
  created() {
    this.getDicts("sys_training_type").then((response) => {
      this.trainingTypeOptions = response.data;
    });

    this.getDicts("sys_allCollection_type").then((response) => {
      this.allCollectionOptions = response.data;
    });
    getAllDataSetList().then(res => {
      this.datasetIdList=res.data
    })
    this.datasetId=this.$route.params && this.$route.params.datasetId;
    this.queryParams.datasetId=datasetId;
    this.getList();
  },
  computed: {
    chunkSizePlaceholder() {
      return this.form.trainingType === 'chunk'
        ? 'chunk模式:100~3000'
        : 'qa模式:4000~10000';
    },
  },
  methods: {

    updateChunkSize() {
      if (this.form.trainingType === 'chunk') {
        this.form.chunkSize = 3000; // 设置默认值
      } else if (this.form.trainingType === 'qa') {
        this.form.chunkSize = 6000; // 设置默认值
      }
    },
    validateChunkSize() {
      if (this.form.trainingType === 'chunk' && (this.form.chunkSize < 100 || this.form.chunkSize > 3000)) {
        this.form.chunkSize = 3000; // 超出范围，重置为默认值
      } else if (this.form.trainingType === 'qa' && (this.form.chunkSize < 4000 || this.form.chunkSize > 10000)) {
        this.form.chunkSize = 6000; // 超出范围，重置为默认值
      }
    },
    //下载文件
    downloadUrl(fileUrl) {
      // 直接返回文件 URL
      return fileUrl;
    },
    //上传成功后
    handleAvatarSuccess(res, file) {
      if(res.code==200){
        this.form.fileUrl=res.url;
        this.fileNameDisPlay=true;
      }
      else{
        this.msgError(res.msg);
      }
    },
    //上传之前
    beforeAvatarUploadFile(file){
      this.form.fileName=file.name;
    },
    /** 查询集合列表 */
    getList() {
      this.loading = true;
      listFastGptCollection(this.queryParams).then(response => {
        this.fastGptCollectionList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        collectionId: null,
        type: null,
        datasetId: null,
        parentId: null,
        name: null,
        // collectionType: null,
        metadata: null,
        text: null,
        trainingType: null,
        chunkSize: null,
        chunkSplitter: null,
        qaPrompt: null,
        link: null,
        fileUrl: null,
        fileName:null,
        updateTime: null,
        createTime: null,
        forbid: null,
        companyId: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.collectionId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加集合";
    },
    //同步集合
    handleSync(){
      syncCollection().then(res => {
        this.msgSuccess("同步成功");
        this.getList();
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const collectionId = row.collectionId || this.ids
      getFastGptCollection(collectionId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改集合";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.collectionId != null) {
            updateFastGptCollection(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addFastGptCollection(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const collectionIds = row.collectionId || this.ids;
      this.$confirm('是否确认删除集合编号为"' + collectionIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delFastGptCollection(collectionIds);
        }).then(res => {
          this.getList();
          if (res.data.length){
            this.msgError("部分删除失败:"+res.data);
          }else {
            this.msgSuccess("删除成功");
          }
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有集合数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportFastGptCollection(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    }
  }
};
</script>
