<template>
  <div class="app-container search-table-box aidex-table">
    <el-card shadow="never" class="search_card" style="margin-bottom: 12px;">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
        <el-form-item label="知识库名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入知识库名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="知识库类型" prop="format_type">
          <el-select v-model="queryParams.format_type" placeholder="请选择知识库类型" clearable>
            <el-option
              v-for="dict in dict.type.datasets_format_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </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-card>
    <el-card shadow="never">
      <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="['system:cozeTokenSet:add']"
          >新增
          </el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="cknowledgeList" height="calc(100vh - 258px)" size="small">
        <el-table-column label="知识库" align="left" prop="id">
          <template slot-scope="scope">
            <div class="iten-box">
              <div class="item-row-div-one">
                <image-preview :src="scope.row.icon_url" :width="50" :height="50" style="margin-top: 10px"/>
              </div>
              <div class="item-row-div-two">
                <div>
                  <span class="iten-name">{{ scope.row.name }}</span>
                </div>
                <div class="item-row-div-three">
                  <div>
                    <dict-tag :options="dict.type.datasets_format_type" :value="scope.row.format_type"/>
                  </div>
                  <div class="iten-description">
                    {{ scope.row.description == null ? '暂无描述' : scope.row.description }}
                  </div>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="知识库ID" align="left" prop="dataset_id" width="180"/>
        <el-table-column label="文件数量" align="left" prop="doc_count" width="120"/>
        <el-table-column label="分段数量" align="left" prop="slice_count" width="120"/>
        <el-table-column label="知识库状态" align="left" prop="status" width="120">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.datasets_status" :value="scope.row.status"/>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="update_time" width="180">
          <template slot-scope="scope">
            <span> {{ unixTimestampToReadable(scope.row.update_time) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120" fixed="right">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:knowledge:update']"
            >编辑
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:knowledge:delete']"
            >删除
            </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-card>

    <!-- 创建知识库 -->
    <el-dialog title="创建知识库" :close-on-click-modal="false" :close-on-press-escape="false" :visible.sync="open" width="480px" append-to-body>
      <div v-loading="addLoading" element-loading-text="数据处理中">
        <el-alert
          title="创建后，类型不可修改"
          type="warning"
          class="search_card_desc"
          :closable="false"
          show-icon/>
        <el-form ref="form" :model="form" :rules="rules" label-position="top" label-width="120px" size="small" class="datasets-format-form">
          <el-row :gutter="10" class="datasets-format-type-row">
            <el-col :span="8">
              <!-- 文本格式选项 -->
              <div class="datasets-format-type-div" :class="{ 'active': selectedFormat === 0 }" @click="selectFormat(0)">
                <svg-icon icon-class="wenben" class-name="card-panel-icon"/>
                <span>文本格式</span>
              </div>
            </el-col>
            <el-col :span="8">
              <!-- 表格格式选项 -->
              <div class="datasets-format-type-div disabled" :class="{ 'active': selectedFormat === 1 }" @click="selectFormat(1)">
                <svg-icon icon-class="biaoge" class-name="card-panel-icon"/>
                <span>表格格式</span>
              </div>
            </el-col>
            <el-col :span="8">
              <!-- 图片格式选项 -->
              <div class="datasets-format-type-div" :class="{ 'active': selectedFormat === 2 }" @click="selectFormat(2)">
                <svg-icon icon-class="tupian" class-name="card-panel-icon"/>
                <span>图片格式</span>
              </div>
            </el-col>
          </el-row>
          <el-form-item label="名称" prop="name">
            <el-input v-model="form.name" placeholder="输入数据集名称" maxlength="100" show-word-limit/>
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-input type="textarea" rows="3" v-model="form.description" placeholder="输入数据集内容的描述" maxlength="2000" show-word-limit/>
          </el-form-item>
          <el-form-item label="图标" prop="icon_url">
            <image-upload v-model="form.icon_url" :limit="1" :fileSize="1"/>
          </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>
      </div>
    </el-dialog>

    <!-- 修改知识库 -->
    <el-dialog title="编辑知识库" :close-on-click-modal="false" :close-on-press-escape="false" :visible.sync="openUpdate" width="480px" append-to-body>
      <div v-loading="updateLoading" element-loading-text="数据处理中">
        <el-form ref="form" :model="form" :rules="rules" label-position="top" label-width="120px" size="small" class="datasets-format-form">
          <el-form-item label="名称" prop="name">
            <el-input v-model="form.name" placeholder="输入数据集名称" maxlength="100" show-word-limit/>
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-input type="textarea" rows="3" v-model="form.description" placeholder="输入数据集内容的描述" maxlength="2000" show-word-limit/>
          </el-form-item>
          <el-form-item label="图标" prop="icon_url">
            <image-upload v-model="form.icon_url" :limit="1" :fileSize="1"/>
          </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>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {listKnowledge, addKnowledge, delKnowledge, updateKnowledge} from "@/api/business/aimodel/knowledge";

export default {
  name: "knowledge",
  dicts: ['datasets_format_type', 'datasets_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 知识库列表
      cknowledgeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        format_type: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          {required: true, message: "名称不能为空", trigger: "blur"}
        ],
        description: [
          {required: true, message: "描述不能为空", trigger: "blur"}
        ],
        icon_url: [
          {required: true, message: "图标不能为空", trigger: "blur"}
        ]
      },
      // 默认选中文本格式
      selectedFormat: 0,
      addLoading: false,

      updateLoading: false,
      openUpdate: false
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询知识库列表 */
    getList() {
      this.loading = true;
      listKnowledge(this.queryParams).then(response => {
        this.cknowledgeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openUpdate = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        datasetId: null,
        formatType: null,
        name: null,
        description: null,
        icon_url: null,
        status: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
    },
    /** 查询知识库详情*/
    handleUpdate(row) {
      this.reset();
      this.form.datasetId = row.dataset_id;
      this.form.name = row.name;
      this.openUpdate = true;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.datasetId != null) {
            this.updateLoading = true;
            updateKnowledge(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.updateLoading = false;
              this.openUpdate = false;
              this.getList();
            });
          } else {
            this.addLoading = true;
            this.form.formatType = this.selectedFormat;
            addKnowledge(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.addLoading = false;
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除"' + row.name + '"知识库？').then(function () {
        return delKnowledge({'datasetId': row.dataset_id});
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    //格式化时间戳
    unixTimestampToReadable(timestamp) {
      const date = new Date(timestamp * 1000);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    // 选择格式类型的方法
    selectFormat(format) {
      this.selectedFormat = format;
      console.log('选中的格式:', this.selectedFormat);
    }

  }
};
</script>
<style lang="scss" scoped>
.search_card_desc {
  margin: 0px 0px 20px 0px;
}

.iten-box {
  display: flex;
  flex-direction: row;
  width: 100%;
  justify-content: left;
  min-width: 350px;

  .item-row-div-one {
    flex-grow: 0;
    width: 60px;
  }

  .item-row-div-two {
    flex-grow: 1;
    align-content: center;
    display: flex;
    flex-direction: column;
    justify-content: center;

    .item-row-div-three {
      display: flex;
      flex-direction: row;
      align-items: center;
      gap: 4px;

      .item-row-div-three-tag {
        font-size: 10px;
        height: 18px;
        line-height: 18px;
      }
    }
  }

  .iten-name {
    font-weight: 400;
    font-size: 14px;
  }

  .iten-description {
    color: #5f61679e;
  }
}

.datasets-format-type-row {
  margin-bottom: 30px;
}

.datasets-format-type-div {
  display: flex;
  flex-direction: column;
  align-items: center;
  border: 1px solid #44538240;
  padding: 10px 16px;
  border-radius: 10px;
  font-size: 14px;
  font-weight: 600;
  line-height: 20px;
  cursor: pointer; /* 鼠标悬停显示手形 */
  transition: background-color 0.3s, border-color 0.3s; /* 过渡效果 */

  span {
    margin-top: 5px;
  }
}

.card-panel-icon {
  height: 24px;
  width: 24px;
}

.datasets-format-type-div:hover {
  background-color: #f0f0f0; /* 悬停时背景颜色 */
  border: 1px solid #ccc; /* 悬停时边框颜色 */
}

/* 选中样式 */
.datasets-format-type-div.active {
  background-color: #eaf6ff;
  border: 1px solid #b3d8ff;
}

/* 禁用样式 */
.datasets-format-type-div.disabled {
  cursor: not-allowed;
  opacity: 0.6;
  pointer-events: none;
}

.datasets-format-form {
  .el-form-item__label {
    line-height: 14px;
    padding: 0px 0 5px;
  }
}

.dialog-footer {
  text-align: right;
  margin-top: 30px;
}


</style>
