<template>
  <div>
    <div class="menu-title">
      数据集管理
    </div>
    <div class="menu-content">
      <div>
        <el-form :inline="true" :model="qo" class="demo-form-inline">
          <el-form-item>
            <el-input v-model="qo.LIKES_name" placeholder="请输入任务名称"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="qo.pageNo=1;queryData()">搜 索</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div style="margin: 0px 0 20px 0">
        <el-button type="primary" @click="createRow()">新建任务</el-button>
      </div>
      <div>
        <el-table :data="result.records" style="width: 100%" ref="table" @expand-change="showDataSetListByTaskId">
          <el-table-column type="expand">
            <template slot-scope="scope">
              <el-row>
                <el-col :span="8" v-for="item in scope.row.tasks" :key="item.id">
                  <el-form label-position="left" inline class="demo-table-expand" label-width="85px">
                    <el-form-item label="数据集类型">
                      <span>{{ item.taskTypeName }}</span>
                      <span v-if="item.taskId == null">（暂无数据）</span>
                    </el-form-item>
                    <el-form-item label="总记录数">
                      <span>{{ item.icount }}</span>
                    </el-form-item>
                    <el-form-item label="实体数量">
                      <span>{{ item.ecount }}</span>
                    </el-form-item>
                    <el-form-item label="关系数量">
                      <span>{{ item.rcount }}</span>
                    </el-form-item>
                    <el-form-item label="操作">
                      <el-button type="text" size="small" @click="showImportDialog(item, scope.row)">
                        导入
                      </el-button>
                      <el-button type="text" size="small" @click="showDataSetViewDialog(item, scope.row)"
                                 v-if="item.taskId != null">
                        查看
                      </el-button>
                      <el-button type="text" size="small" @click="markTxt(item, scope.row)"
                                 v-if="item.taskId != null">
                        标注
                      </el-button>
                      <el-button type="text" size="small" @click="downloadFile(item, scope.row)"
                                 v-if="item.taskId != null">
                        导出
                      </el-button>
                      <el-button type="text" size="small" @click="removeDataSet(item, scope.row)"
                                 v-if="item.taskId != null">
                        删除
                      </el-button>
                    </el-form-item>
                  </el-form>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
          <el-table-column type="index" label="行号" width="100"></el-table-column>
          <el-table-column prop="name" label="任务名称"></el-table-column>
          <el-table-column prop="createTime" label="创建时间"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button title="将其他知识图谱本体三元组导入当前数据集中"
                         @click.native.prevent="showImportNodeDialog(scope.row)"
                         type="text" size="small">
                导入知识图谱本体
              </el-button>
              <el-button @click.native.prevent="removeRow(scope.row)" type="text" size="small">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="page-box">
        <el-pagination background
                       @current-change="handleCurrentChange"
                       :current-page="qo.pageNo"
                       :page-size="qo.pageSize"
                       layout="total, prev, pager, next"
                       :total="result.total">
        </el-pagination>
      </div>
    </div>
    <el-dialog
        title="新建"
        :visible.sync="cmdDialogVisible"
        width="40%">
      <el-form ref="cmd" label-width="100px" :rules="rules" :model="cmd">
        <el-form-item label="任务名称" prop="name">
          <el-input v-model="cmd.name" placeholder="请输入任务名称"></el-input>
        </el-form-item>
        <!--        <el-form-item label="相关描述" prop="name">-->
        <!--          <el-input v-model="cmd.description" placeholder="请输入相关描述" type="textarea"></el-input>-->
        <!--        </el-form-item>-->
        <el-form-item label="验证集文件">
          <el-upload
              class="upload-demo"
              ref="upload2"
              action="#"
              :on-change="handleValidationFileChange"
              :auto-upload="false"
              accept=".txt"
              :limit="10"
              :file-list="fileList2">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">请选择一个格式为.txt的文本文件进行上传</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="训练集文件">
          <el-upload
              class="upload-demo"
              ref="upload3"
              action="#"
              :on-change="handleTrainingFileChange"
              :auto-upload="false"
              accept=".txt"
              :limit="10"
              :file-list="fileList3">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">请选择一个格式为.txt的文本文件进行上传</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cmdDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitModify">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
        title="导入知识图谱本体"
        :visible.sync="importNodeDialogVisible"
        width="40%">
      <el-table :data="ontologyList" style="width: 100%">
        <el-table-column type="index" label="行号" width="100"></el-table-column>
        <el-table-column prop="name" label="模型名称"></el-table-column>
        <el-table-column prop="createTime" label="创建时间"></el-table-column>
        <el-table-column label="操作" width="80">
          <template slot-scope="scope">
            <el-button @click.native.prevent="submitImportNode(scope.row)" type="text" size="small"
                       v-if="cmd.srcOntologyId != scope.row.id">
              导入
            </el-button>
            <label v-else>自身</label>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="importNodeDialogVisible = false">关 闭</el-button>
      </span>
    </el-dialog>
    <el-dialog
        title="导入"
        :visible.sync="importDialogVisible"
        width="40%">
      <el-form ref="cmd" label-width="100px" :model="cmd">
        <el-form-item label="数据集类型" prop="name">
          <el-select v-model="cmd.taskType" disabled>
            <el-option :label="item.name" :value="item.code" v-for="item in taskTypeList" :key="item.code"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择文件" prop="name">
          <el-upload
              class="upload-demo"
              ref="upload"
              action="#"
              :on-change="handleFileChange"
              :auto-upload="false"
              accept=".txt"
              :limit="10"
              :file-list="fileList">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">请选择一个格式为.txt的文本文件进行上传</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="importDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitImport">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
        title="查看"
        :visible.sync="viewDialogVisible"
        width="60%">
      <div>
        <el-table :data="dataSetResult.records" style="width: 100%">
          <el-table-column type="index" label="行号" width="80"></el-table-column>
          <el-table-column prop="content" label="文本内容">
            <template slot-scope="scope">
              <label
                  :title="scope.row.content">{{
                  scope.row.content.length > 45 ? (scope.row.content.substring(0, 45) + '...') : scope.row.content
                }}</label>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template slot-scope="scope">
              <el-button @click.native.prevent="remarkText(scope.row, scope.$index)" type="text" size="small">
                标注
              </el-button>
              <el-button @click.native.prevent="removeDataSetView(scope.row)" type="text" size="small">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="page-box">
        <el-pagination background
                       @current-change="handleDataSetCurrentChange"
                       :current-page="dataSetQo.pageNo"
                       :page-size="dataSetQo.pageSize"
                       layout="total, prev, pager, next"
                       :total="dataSetResult.total">
        </el-pagination>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="viewDialogVisible = false">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import request, {getBaseUrl} from '@/utils/request';

var _this;
export default {
  name: "company",
  data() {
    return {
      qo: {
        pageNo: 1,
        pageSize: 10,
        LIKES_name: '',
      },
      result: {
        records: [],
        total: 0
      },
      dataSetQo: {
        pageNo: 1,
        pageSize: 10,
        taskId: '',
        taskType: ''
      },
      dataSetResult: {
        records: [],
        total: 0
      },
      ontologyList: [],
      taskTypeList: [{
        name: "测试集",
        code: 1,
        eName: "test"
      }, {
        name: "验证集",
        code: 2,
        eName: "validation"
      }, {
        name: "训练集",
        code: 3,
        eName: "training"
      }],
      dialogName: '编辑',
      cmdDialogVisible: false,
      viewDialogVisible: false,
      importDialogVisible: false,
      importNodeDialogVisible: false,
      cmd: {},
      rules: {
        name: [
          {required: true, message: '请输入任务名称'}
        ],
        ontologyId: [
          {required: true, message: '本体标签库'}
        ],
      },
      fileList: [],
      fileList2: [],
      fileList3: []
    }
  },
  mounted() {
    _this = this;
    _this.queryOntologyList();
    _this.queryData();
  },
  methods: {
    queryData() {
      request({
        url: '/remark_task/query_pages',
        method: 'post',
        data: _this.qo
      }).then(res => {
        _this.result.records = res.data.records;
        _this.result.total = res.data.total;
        if (res.data.records.length > 0) {
          _this.$nextTick(() => {
            _this.$refs['table'].toggleRowExpansion(res.data.records[0], true);
          });
        }
      });
    },
    handleCurrentChange(val) {
      _this.qo.pageNo = val;
      _this.queryData();
    },
    downloadFile(item, row) { // 导出
      window.open(getBaseUrl() + `/es_remark_task/export/${row.id}/${item.taskTypeCode}`);
    },
    showImportNodeDialog(item) { // 打开复制图模型的列表弹窗
      _this.queryOntologyList();
      _this.cmd = {
        srcOntologyId: item.ontologyId,
        dictOntologyId: ''
      };
      _this.importNodeDialogVisible = true;
    },
    submitImportNode(item) {
      _this.cmd.dictOntologyId = item.id;
      request({
        url: '/noumenon/copy_by_ontologyid',
        method: 'post',
        data: _this.cmd
      }).then(res => {
        _this.$message.success("导入成功");
      });
    },
    queryOntologyList() {
      request({
        url: '/ontology/query_list',
        method: 'post',
        data: {}
      }).then(res => {
        _this.ontologyList = res.data;
      });
    },
    removeRow(item) {
      _this.$confirm('此操作将永久删除记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        request({
          url: '/remark_task/removeremarktask',
          method: 'post',
          data: {
            remarkId: item.id,
            ontologyId: item.ontologyId
          }
        }).then(res => {
          _this.$message.success("删除成功");
          _this.queryData();
          _this.queryOntologyList();
        });
      }).catch(() => {
      });
    },
    createRow() {
      _this.cmd = {
        name: '',
      };
      _this.cmdDialogVisible = true;
    },
    modifyRow(item) {
      _this.cmd = JSON.parse(JSON.stringify(item));
      _this.cmdDialogVisible = true;
    },
    showImportDialog(dataSet, task) {
      _this.cmd = {
        taskId: task.id,
        taskType: dataSet.taskTypeCode
      }
      _this.fileList = [];
      _this.importDialogVisible = true;
    },
    handleFileChange(file) {
      _this.$refs['upload'].clearFiles();
      _this.fileList = [file];
    },
    handleValidationFileChange(file) {
      _this.$refs['upload2'].clearFiles();
      _this.fileList2 = [file];
    },
    handleTrainingFileChange(file) {
      _this.$refs['upload3'].clearFiles();
      _this.fileList3 = [file];
    },
    submitModify() {
      this.$refs.cmd.validate((valid) => {
        if (valid) {
          let formData = new FormData();
          formData.append("name", _this.cmd.name);
          formData.append("validationFile", _this.fileList2[0].raw);
          formData.append("trainingFile", _this.fileList3[0].raw);

          // if (_this.cmd.id) {
          //   request({
          //     url: '/remark_task/modify',
          //     method: 'post',
          //     data: _this.cmd
          //   }).then(res => {
          //     _this.$message.success("编辑成功");
          //     _this.queryData();
          //     _this.cmdDialogVisible = false;
          //   });
          // } else { // 新建
          request({
            url: '/remark_task/create_with_file',
            method: 'post',
            data: formData
          }).then(res => {
            _this.$message.success("添加成功");
            _this.queryData();
            _this.cmdDialogVisible = false;
          });
          // }
        }
      });
    },
    showDataSetListByTaskId(row, expanded) {
      if (row.tasks) {
        return;
      }
      request({
        url: '/es_remark_task/findesremarkinfosticdto/' + row.id,
        method: 'post',
        data: _this.qo
      }).then(res => {
        let tasks = [];
        for (let i = 0; i < 3; i++) {
          tasks.push({
            ecount: 0,
            icount: 0,
            rcount: 0,
            taskTypeName: _this.taskTypeList[i].name,
            taskTypeEName: _this.taskTypeList[i].eName,
            taskTypeCode: i + 1
          });
        }
        res.data.forEach(item => {
          let index = tasks.findIndex(row => {
            return row.taskTypeEName == item.type;
          });
          if (tasks[index]) {
            tasks[index].ecount = item.ecount;
            tasks[index].icount = item.icount;
            tasks[index].rcount = item.rcount;
            tasks[index].taskId = item.taskId;
          }
        });
        row.tasks = tasks;
      });
    },
    submitImport() {
      if (_this.fileList.length == 0) {
        _this.$message.warning("请选择一个文本文件进行上传");
        return;
      }
      let formData = new FormData();
      formData.append("taskId", _this.cmd.taskId);
      formData.append("file", _this.fileList[0].raw);
      formData.append("taskType", _this.cmd.taskType);
      request({
        url: '/es_remark_task/upload_task',
        method: 'post',
        data: formData
      }).then(res => {
        _this.$message.success("导入成功");
        _this.reloadDataSet(_this.cmd.taskId);
        _this.importDialogVisible = false;
      });
    },
    reloadDataSet(taskId) {
      let index = _this.result.records.findIndex(row => {
        return row.id == taskId;
      });
      _this.result.records[index].tasks = null;
      _this.showDataSetListByTaskId(_this.result.records[index]);
    },
    showDataSetViewDialog(dataSet, task) {  // 打开查看弹窗，保存一些父级数据集信息
      _this.dataSetQo = {
        pageNo: 1,
        pageSize: 10,
        taskId: task.id,
        taskType: dataSet.taskTypeCode,
        ontologyId: task.ontologyId
      }
      _this.queryDataSetViewData();
    },
    queryDataSetViewData() {
      request({
        url: '/es_remark_task/findbytaskidandtasktype',
        method: 'post',
        data: _this.dataSetQo
      }).then(res => {
        _this.dataSetResult.records = res.data.content;
        _this.dataSetResult.total = res.data.totalElements;
        _this.viewDialogVisible = true;
      });
    },
    handleDataSetCurrentChange(val) {
      _this.dataSetQo.pageNo = val;
      _this.queryDataSetViewData();
    },
    removeDataSet(item, task) {
      _this.$confirm('此操作将永久删除记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        request({
          url: '/es_remark_task/deletebyqo',
          method: 'post',
          data: {
            taskId: task.id,
            taskType: item.taskTypeCode
          }
        }).then(res => {
          _this.$message.success("删除成功");
          _this.reloadDataSet(task.id);
        });
      }).catch(() => {
      });
    },
    removeDataSetView(item) {
      _this.$confirm('此操作将永久删除记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        request({
          url: '/es_remark_task/delete/' + item.id,
          method: 'post'
        }).then(res => {
          _this.$message.success("删除成功");
          _this.queryDataSetViewData();
        });
      }).catch(() => {
      });
    },
    markTxt(item, task) {
      this.$router.push({
        path: '/textTag',
        query: {taskId: task.id, taskTypeCode: item.taskTypeCode, ontologyId: task.ontologyId}
      });
    },
    remarkText(row, index) { // 跳转到标注页，根据序号
      let sort  = (_this.dataSetQo.pageNo - 1) * _this.dataSetQo.pageSize + index + 1;
      this.$router.push({
        path: '/textTag',
        query: {sort: sort, taskId: _this.dataSetQo.taskId, taskTypeCode: _this.dataSetQo.taskType, ontologyId:  _this.dataSetQo.ontologyId}
      });
    }
  }
}
</script>

<style lang="scss">
.demo-table-expand {
  font-size: 0;
  margin-left: 10%;
}

.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}

.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 80%;
}
</style>
