<script>
import { datasetsExTaskPages as datasetsExPages, docManageDataset } from '@/api/generatedApi'
import KnowledgeInfo from '@/views/track/views/knowledge-info/Index.vue'

export default {
  components: {
    KnowledgeInfo
  },
  data() {
    return {
      infoDialogVisible: false,
      activeForm: {},
      tableData: [],
      form: {
        datasetId: '',
        datasetValue: '',
        uploadUser: '',
        documentStatus: '',
        // 知识文件名称（新字段）
        knowledgeName: '',
        taskTime: []
      },
      datasetList: [],
      tableConfig: {
        uploadStatusType: {
          '1': '成功',
          '0': '上传中',
          '-1': '失败'
        },
        total: 0,
        currentPage: 1,
        pageSize: 10,
        columns: [
          { prop: 'id', key: '任务号', width: '180' },
          { prop: 'datasetName', key: '知识库', width: '180' },
          { prop: 'knowledgeName', key: '知识文件名称' },
          {
            prop: 'documentStatus',
            key: '上传状态',
            width: '100',
            render: (h, params) => {
              return h('span', this.tableConfig.uploadStatusType[params.row.documentStatus])
            }
          },
          // 上传用户 现在只有 admin . 后面需要自己添加
          { prop: 'userName', key: '上传用户', width: '100' },
          { prop: 'createdDate', key: '上传时间', width: '200' },
          {
            key: '操作',
            render: (h, params) => {
              return h('div', [
                h(
                  'el-button',
                  {
                    props: { type: 'text', size: 'mini' },
                    on: { click: () => this.handleActiveInfo(params) }
                  },
                  '查看详情'
                )
              ])
            }
          }
        ]
      }
    }
  },
  computed: {
    /**
     * 获取上传用户列表
     */
    getUploadUserList() {
      // 进行去重处理
      return [...new Set(this.tableData.map(item => item.userName))]
    },
    /**
     * 格式化上传时间
     * @returns {string[]} 格式化后的日期字符串 格式是 年-月-日
     */
    formattedDate() {
      if (!this.form.taskTime || this.form.taskTime.length !== 2) return ''

      return this.form.taskTime.map((date, index) => {
        return `${new Date(date).getFullYear()}-${String(new Date(date).getMonth() + 1).padStart(2, '0')}-${String(new Date(date).getDate()).padStart(
          2,
          '0'
        )} ${index === 0 ? '00:00:00' : '23:59:59'}`
      })
    }
  },
  methods: {
    // 搜索
    handleSearch() {
      // 重置页码
      this.tableConfig.currentPage = 1

      this.getTableData()
    },
    // 反转 uploadStatusType ,获取 key 值
    reverseUploadStatusType(value) {
      const values = Object.values(this.tableConfig.uploadStatusType)
      const res = values.indexOf(value) + 1
      // 如果没有找到，默认查询所有内容
      if (res === -1) return ''
      return res
    },
    handleCurrentChange(current) {
      // 重置页码
      this.tableConfig.currentPage = current
      this.getTableData()
    },
    handleSizeChange(size) {
      this.tableConfig.pageSize = size
      this.getTableData()
    },
    getTableData() {
      const payload = {
        // 分页参数
        page: this.tableConfig.currentPage,
        pageSize: this.tableConfig.pageSize,
        // // 知识库名称
        datasetId: this.form.datasetId,
        // // 知识文件名称
        // fileName: this.form.knowledgeName,
        // // 上传用户
        // userName: this.form.uploadUser,
        // // 上传状态
        // documentStatus: this.form.documentStatus,
        // // 任务时间
        startCreatedDate: this.formattedDate.length > 1 ? this.formattedDate[0] : '',
        endCreatedDate: this.formattedDate.length > 1 ? this.formattedDate[1] : '',
        knowledgeNameLike: this.form.knowledgeName,
        documentStatus: this.form.documentStatus
      }

      datasetsExPages(payload).then(res => {
        this.tableData = res.content.content.list ? res.content.content.list : []
        this.tableConfig.total = res.content.content.total
      })
    },
    // 远程搜索知识库内容, 暂时不添加这个功能
    remoteSearchDataset(query) {
      this.form.datasetValue = query

      if (query !== '') {
        this.getKnowledgeList()
      }
    },
    // 获取知识库列表
    getKnowledgeList() {
      docManageDataset({
        // 对搜索的内容不做限制,主要获取所有的内容, 后续再添加参数
        // page: this.tableConfig.currentPage,
        // pageSize: this.tableConfig.pageSize,
        nameLike: this.form.datasetValue
      }).then(res => {
        this.datasetList = res.content.content ? res.content.content : []
      })
    },
    // 重置 form 表单状态
    handleReset() {
      this.form = {
        datasetId: '',
        datasetValue: '',
        fileName: '',
        uploadUser: '',
        documentStatus: '',
        taskTime: []
      }
      this.handleSearch()
    },
    // 处理查看详情
    handleActiveInfo(scope) {
      this.infoDialogVisible = true
      this.activeForm = scope.row
    }
  },
  created() {
    this.getTableData()
    this.getKnowledgeList()
  }
}
</script>

<template>
  <div class="track-container container">
    <el-card shadow="hover">
      <!-- 知识库信息 -->
      <el-form :model="form" label-width="100px" size="small">
        <el-row>
          <el-col :span="8">
            <el-form-item label="知识库">
              <!-- 启用远程加载 -->
              <el-select filterable v-model="form.datasetId" placeholder="输入搜索知识库">
                <!-- 后续需要添加懒加载 -->
                <el-option v-for="item in datasetList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="知识文件名称">
              <el-input @keydown.enter.native="handleSearch" v-model="form.knowledgeName" placeholder="请输入知识文件名称"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="上传用户">
              <el-select v-model="form.uploadUser" placeholder="请选择上传用户">
                <el-option label="全部上传用户" value="">全部上传用户</el-option>
                <el-option v-for="item in getUploadUserList" :key="item" :label="item" :value="item"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="上传状态">
              <el-select v-model="form.documentStatus" placeholder="请选择上传状态">
                <el-option label="全部上传状态" value="" />
                <el-option
                  v-for="item in Object.keys(this.tableConfig.uploadStatusType)"
                  :key="item"
                  :label="tableConfig.uploadStatusType[item]"
                  :value="Number(item)"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="任务时间">
              <el-date-picker
                v-model="form.taskTime"
                type="daterange"
                unlink-panels
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="9" :offset="11" class="mb20">
            <!-- 搜索按钮 -->
            <el-button type="primary" size="small" @click="handleSearch">搜索</el-button>
            <!-- 重置按钮 -->
            <el-button type="primary" size="small" @click="handleReset">重置筛选</el-button>
          </el-col>
        </el-row>
      </el-form>

      <!-- 任务列表 -->
      <div>
        <r-table
          :columns="tableConfig.columns"
          :data="tableData"
          :deletion="false"
          :total="tableConfig.total"
          @currentChange="handleCurrentChange"
          @sizeChange="handleSizeChange"
          :currentPage="tableConfig.currentPage"
          :pageSize="tableConfig.pageSize"
        />

        <!-- 弹出提示框， 里面是各种详情内容 -->
        <el-drawer title="上传任务详情" :visible.sync="infoDialogVisible" size="95%" :before-close="() => (infoDialogVisible = false)">
          <knowledge-info :form="activeForm" v-if="infoDialogVisible"></knowledge-info>
        </el-drawer>
      </div>
    </el-card>
  </div>
</template>
