<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">
          <el-table-column type="index" label="行号" width="100"></el-table-column>
          <el-table-column prop="space" label="实例名称"></el-table-column>
          <el-table-column prop="name" label="任务名称"></el-table-column>
          <el-table-column prop="totle" label="文件个数"></el-table-column>
          <el-table-column prop="over" label="已导入个数"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button @click.native.prevent="modifyRow(scope.row)" type="text" size="small">
                编辑
              </el-button>
              <el-button @click.native.prevent="showRow(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="'查看-' + showTaskName"
        :visible.sync="showDialogVisible"
        width="60%">
      <!--      createTime: "2022-08-03 08:19:29"-->
      <!--      headerRow: null-->
      <!--      id: 1-->
      <!--      over: false-->
      <!--      originalFilename: "dn_graph_one_tag"-->
      <!--      path: "2022-08-03\\64e790821d872af8db27e781b6becc0e.xlsx"-->
      <!--      suffix: ".xlsx"-->
      <!--      taskId: 4-->
      <el-tabs v-model="activeTab">
        <el-tab-pane label="未导入" name="first">
          <el-table :data="cmd.records" style="width: 100%" ref="fileListTable"
                    @selection-change="handleSelectionChange" default-expand-all>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-form label-position="left" class="demo-table-expand">
                  <el-form-item label="类型">
                    <el-select v-model="scope.row.type" @change="val => {handleTypeChange(val, scope.row)}">
                      <el-option label="TAG" value="TAG"></el-option>
                      <el-option label="EDGE" value="EDGE"></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="TAG名称" v-show="scope.row.type == 'TAG'">
                    <el-select v-model="scope.row.name" placeholder="请选择TAG名称" @change="val => {handleTagNameChange(val, scope.row)}">
                      <el-option :label="item.Name" :value="item.Name" v-for="item in tagList"
                                 :key="item.Name"></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="EDGE名称" v-show="scope.row.type == 'EDGE'">
                    <el-select v-model="scope.row.name" placeholder="请选择EDGE名称" @change="val => {handleEdgeNameChange(val, scope.row)}">
                      <el-option :label="item.Name" :value="item.Name" v-for="item in edgeList"
                                 :key="item.Name"></el-option>
                    </el-select>
                  </el-form-item>
                  <template v-show="scope.row.name">
                    <el-form-item :label="field.field" v-for="field in scope.row.fieldList" :key="field.field">
                      <el-select v-model="field.value" placeholder="请选择TAG名称">
                        <el-option :label="row" :value="row" v-for="row in scope.row.headerRowList"
                                   :key="row"></el-option>
                      </el-select>
                    </el-form-item>
                  </template>
                </el-form>
              </template>
            </el-table-column>
            <el-table-column
                type="selection"
                width="55">
            </el-table-column>
            <el-table-column type="index" label="行号" width="80"></el-table-column>
            <el-table-column prop="originalFilename" label="源文件名称">
              <template slot-scope="scope">{{scope.row.originalFilename}}{{scope.row.suffix}}</template>
            </el-table-column>
            <el-table-column prop="type" label="类型" ></el-table-column>
            <el-table-column prop="typename" label="名称" ></el-table-column>
<!--            <el-table-column prop="path" label="路径" width="450"></el-table-column>-->
            <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="已导入" name="second">
          <el-table :data="cmd.records2" style="width: 100%" ref="fileListTable">
            <el-table-column type="index" label="行号" width="80"></el-table-column>
            <el-table-column prop="originalFilename" label="源文件名称"></el-table-column>
            <el-table-column prop="path" label="路径" width="450"></el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showDialogVisible = false">关 闭</el-button>
        <el-button type="primary" @click="importRow" v-show="activeTab == 'first'">导 入</el-button>
      </span>
    </el-dialog>
    <el-dialog
        title="创建任务"
        :visible.sync="createDialogVisible"
        width="40%">
      <el-form ref="createCmd" label-width="100px" :rules="rules" :model="cmd">
        <el-form-item label="实例名称" prop="space">
          <el-select v-model="cmd.space" placeholder="请选择实例名称">
            <el-option v-for="space in spaceList" :key="space.Name" :label="space.Name" :value="space.Name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="任务名称" prop="name">
          <el-input v-model="cmd.name" placeholder="请输入名称"></el-input>
        </el-form-item>
        <el-form-item label="文件选择" prop="file">
          <el-upload
              class="upload-demo"
              :auto-upload="false"
              accept=".xls,.xlsx"
              action="#"
              :limit="10"
              :on-change="handleFileChange"
              :file-list="fileList">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传xls/xlsx文件</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="createDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitCreate">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
        title="编辑"
        :visible.sync="cmdDialogVisible"
        width="40%">
      <el-form ref="cmd" label-width="100px" :rules="rules" :model="cmd">
        <el-form-item label="实例名称">
          <el-input v-model="cmd.space" disabled></el-input>
        </el-form-item>
        <el-form-item label="任务名称" prop="name">
          <el-input v-model="cmd.name" placeholder="请输入名称"></el-input>
        </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>
  </div>
</template>

<script>
import request from '@/utils/request';

var _this;
export default {
  name: "codeWarehouse",
  data() {
    return {
      qo: {
        pageNo: 1,
        pageSize: 10,
        LIKES_name: '',
      },
      spaceList: [], // 实例列表
      result: {
        records: [],
        total: 0
      },
      showTaskName: '',
      createDialogVisible: false,
      cmdDialogVisible: false,
      showDialogVisible: false,
      cmd: {},
      rules: {
        name: [
          {required: true, message: '请输入任务名称'}
        ],
        space: [
          {required: true, message: '请选择实例名称'}
        ]
      },
      fileList: [], // 创建任务导入的文件列表
      importSelection: [], // 选中的需要执行导入的文件
      activeTab: 'first',
      tagList: [], // 任务space下的所有tag
      edgeList: [], // 任务space下的所有edge
    }
  },
  mounted() {
    _this = this;
    _this.queryData();
    _this.querySpaceList();
  },
  methods: {
    querySpaceList() { // 查询实例列表
      request({
        url: '/nebula_operate/showspace',
        method: 'get',
        data: {}
      }).then(res => {
        _this.spaceList = res.data;
      });
    },
    queryData() {
      request({
        url: '/graph-task/query_pages',
        method: 'post',
        data: _this.qo
      }).then(res => {
        res.data.records.forEach(item => {
          item.totle = item.totle || 0;
          item.over = item.over || 0;
        });
        _this.result.records = res.data.records;
        _this.result.total = res.data.total;
      });
    },
    handleCurrentChange(val) {
      _this.qo.pageNo = val;
      _this.queryData();
    },
    removeRow(item) {
      _this.$confirm('此操作将永久删除记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        request({
          url: `/graph-task/remove/${item.id}`,
          method: 'post',
        }).then(res => {
          _this.$message.success("删除成功");
          _this.queryData();
        });
      }).catch(() => {
      });
    },
    createRow() {
      _this.createDialogVisible = true;
      _this.$nextTick(() => {
        _this.cmd = {
          "space": "",
          "name": "",
          "file": null
        };
        _this.fileList = [];
        _this.$refs.createCmd.resetFields();
      });
    },
    handleFileChange(file, fileList) {
      _this.cmd.file = file.raw;
      _this.fileList = [fileList.at(-1)];
    },
    modifyRow(item) {
      _this.cmdDialogVisible = true;
      _this.$nextTick(() => {
        _this.cmd = JSON.parse(JSON.stringify(item));
        _this.$refs.cmd.resetFields();
      });
    },
    submitCreate() {
      this.$refs.createCmd.validate((valid) => {
        if (valid) {
          let formData = new FormData();
          formData.append("file", _this.cmd.file);
          formData.append("name", _this.cmd.name);
          request({
            url: `/nebula_graph_import/createtask/${_this.cmd.space}`,
            method: 'put',
            data: formData
          }).then(res => {
            _this.$message.success("创建成功");
            _this.queryData();
            _this.createDialogVisible = false;
          });
        }
      });
    },
    submitModify() {
      this.$refs.cmd.validate((valid) => {
        if (valid) {
          request({
            url: '/graph-task/modify',
            method: 'post',
            data: _this.cmd
          }).then(res => {
            _this.$message.success("编辑成功");
            _this.queryData();
            _this.cmdDialogVisible = false;
          });
        }
      });
    },
    showRow(item) { // 打开查看
      _this.showTaskName = item.name;
      _this.importSelection = [];
      request({
        url: `/nebula_graph_import/findtaskbyid/${item.id}`,
        method: 'get',
        data: _this.cmd
      }).then(res => {
        let _records = [], _records2 = [];
        _this.tagList = res.data.tags;
        _this.edgeList = res.data.edges;
        res.data.tfs.forEach(row => {
          if (row.over) {
            _records2.push(row);
          } else {
            row.headerRowList = JSON.parse(row.headerRow) || [];
            row.fieldList = [];
            row.type = row.type || "TAG"; // 默认TAG类型
            row.name = row.typename || "";
            if(row.name && row.type) {
              if(row.type === 'TAG') {
                  _this.handleTagNameChange(row.typename, row);
              } else if(row.type === 'EDGE') {
                _this.handleEdgeNameChange(row.typename, row);
              }
            }
            _records.push(row);
          }
        });
        _this.cmd = {
          records: _records,
          records2: _records2
        };
        _this.showDialogVisible = true;
      });
    },
    handleTypeChange(val, row) {
      row.name = "";
      row.fieldList = [];
    },
    handleTagNameChange(val, row) {
      row.typename = val;
      let index = _this.tagList.findIndex(tag => {
        return tag.Name == val;
      });
      if(index >= 0) {
        row.fieldList = _this.resolveFieldList(_this.tagList[index].fields, row.headerRowList);
      }
    },
    handleEdgeNameChange(val, row) {
      row.typename = val;
      let index = _this.edgeList.findIndex(edge => {
        return edge.Name == val;
      });
      if(index >= 0) {
        row.fieldList = _this.resolveFieldList(_this.edgeList[index].fields, row.headerRowList);
      }
    },
    resolveFieldList(fieldList, headerRowList) { // solve fieldList, field.value auto assignment rowHeader's value
      fieldList.forEach(field => {
        if(headerRowList.indexOf(field.field) >= 0) {
          field.value = field.field;
        }
      });
      return fieldList;
    },
    handleSelectionChange(val) {
      _this.importSelection = val;
    },
    importRow() { // 执行批量导入，导入选择的
      if (_this.importSelection.length == 0) {
        _this.$message.warning("请选择文件再执行导入！");
        return;
      }
      let cmd = {
        taskId: _this.importSelection[0].taskId,
        taskFiles: []
      };
      _this.importSelection.forEach(item => {
        let _correspond = {};
        item.fieldList.forEach(field => {
          _correspond[field.field] = field.value;
        });
        cmd.taskFiles.push({
          taskFileId: item.id,
          type: item.type,
          name: item.name,
          correspond: _correspond
        });
      });
      console.log(cmd);
      request({
        url: '/nebula_graph_import/graphtaskexecute',
        method: 'post',
        data: cmd
      }).then(res => {
        _this.$message.success("导入成功");
        _this.queryData();
        _this.showDialogVisible = false;
      });
    }
  }
}
</script>

<style lang="scss">
</style>
