<template>
  <div>
    <div class="menu-title">
      导入条目
      <div class="icon icon-back" @click="backBtn">
        <i title="返回"></i>
      </div>
    </div>
    <div class="block_box" style="margin-top: 20px;padding: 20px">
      <el-form ref="cmd" label-width="100px" :rules="rules" :model="cmd" :inline="true">
        <el-form-item label="文件" prop="file">
          <el-upload
              class="upload-demo"
              action="#"
              :auto-upload="false"
              accept=".csv"
              :on-change="handleFileChange"
              :limit="1"
              :show-file-list="false">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传csv文件</div>
          </el-upload>
        </el-form-item>
        <br/>
        <el-form-item label="字段分隔符" prop="field">
          <el-input v-model="cmd.field" placeholder="请输入字段分隔符" style="width: 300px"
                    @change="handleFieldChange"></el-input>
        </el-form-item>
        <el-form-item label="类别分隔符" prop="categories">
          <el-input v-model="cmd.categories" placeholder="请输入类别分隔符" style="width: 300px"></el-input>
        </el-form-item>
        <br/>
        <el-form-item label="唯一ID" prop="id">
          <el-select v-model="cmd.id" style="width: 300px" @change="refreshList">
            <template v-if="cmd.ifFirstHead">
              <el-option :value="index" :label="item" v-for="(item,index) in columnList" :key="index"></el-option>
            </template>
            <template v-if="!cmd.ifFirstHead">
              <el-option :value="index" :label="index" v-for="(item,index) in columnList" :key="index"></el-option>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="是否隐藏" prop="labels">
          <el-select v-model="cmd.hidden" style="width: 300px" @change="refreshList">
            <template v-if="cmd.ifFirstHead">
              <el-option :value="index" :label="item" v-for="(item,index) in columnList" :key="index"></el-option>
            </template>
            <template v-if="!cmd.ifFirstHead">
              <el-option :value="index" :label="index" v-for="(item,index) in columnList" :key="index"></el-option>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="类别" prop="labels">
          <el-select v-model="cmd.categoriesColumn" style="width: 300px" @change="refreshList">
            <template v-if="cmd.ifFirstHead">
              <el-option :value="index" :label="item" v-for="(item,index) in columnList" :key="index"></el-option>
            </template>
            <template v-if="!cmd.ifFirstHead">
              <el-option :value="index" :label="index" v-for="(item,index) in columnList" :key="index"></el-option>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="日期" prop="labels">
          <el-select v-model="cmd.timestamp" style="width: 300px" @change="refreshList">
            <template v-if="cmd.ifFirstHead">
              <el-option :value="index" :label="item" v-for="(item,index) in columnList" :key="index"></el-option>
            </template>
            <template v-if="!cmd.ifFirstHead">
              <el-option :value="index" :label="index" v-for="(item,index) in columnList" :key="index"></el-option>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="标签" prop="labels">
          <el-select v-model="cmd.labels" style="width: 300px" @change="refreshList">
            <template v-if="cmd.ifFirstHead">
              <el-option :value="index" :label="item" v-for="(item,index) in columnList" :key="index"></el-option>
            </template>
            <template v-if="!cmd.ifFirstHead">
              <el-option :value="index" :label="index" v-for="(item,index) in columnList" :key="index"></el-option>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="labels">
          <el-select v-model="cmd.description" style="width: 300px" @change="refreshList">
            <template v-if="cmd.ifFirstHead">
              <el-option :value="index" :label="item" v-for="(item,index) in columnList" :key="index"></el-option>
            </template>
            <template v-if="!cmd.ifFirstHead">
              <el-option :value="index" :label="index" v-for="(item,index) in columnList" :key="index"></el-option>
            </template>
          </el-select>
        </el-form-item>
        <br/>
        <el-form-item label=" ">
          <el-checkbox label="第一行为表头" v-model="cmd.ifFirstHead" @change="refreshList"></el-checkbox>
        </el-form-item>
      </el-form>
      <el-table :data="list" style="width: 100%" height="400" v-show="list.length > 0">
        <el-table-column type="index" label="行号" width="60"></el-table-column>
        <el-table-column prop="id" :label="'ID('+(cmd.ifFirstHead ? columnList[cmd.id] : cmd.id)+')'"></el-table-column>
        <el-table-column prop="hidden"
                         :label="'是否隐藏('+(cmd.ifFirstHead ? columnList[cmd.hidden] : cmd.hidden)+')'"></el-table-column>
        <el-table-column prop="categoriesColumn"
                         :label="'类别('+(cmd.ifFirstHead ? columnList[cmd.categoriesColumn] : cmd.categoriesColumn)+')'">
          <template v-slot="scope">
            <el-tag v-for="item in scope.row.categoriesColumn" :key="item" v-show="item.length > 0">{{ item }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="timestamp"
                         :label="'日期('+(cmd.ifFirstHead ? columnList[cmd.timestamp] : cmd.timestamp)+')'"></el-table-column>
        <el-table-column prop="labels" :label="'标签('+(cmd.ifFirstHead ? columnList[cmd.labels] : cmd.labels)+')'">
          <template v-slot="scope">
            <label style="color: red" v-if="scope.row.errorFlag">JSON格式化异常</label>
            <label v-if="!scope.row.errorFlag">{{ scope.row.labels }}</label>
          </template>
        </el-table-column>
        <el-table-column prop="description"
                         :label="'描述('+(cmd.ifFirstHead ? columnList[cmd.description] : cmd.description)+')'"></el-table-column>
      </el-table>
      <el-button type="primary" class="submit-btn" @click="confirmSubmit" :disabled="list.length === 0">确认提交
      </el-button>
    </div>
  </div>
</template>

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

var _this;
export default {
  name: "ImportUser",
  data() {
    return {
      config: /* Papa Parse config object */ {
        delimiter: "", // auto-detect
        newline: "", // auto-detect
        quoteChar: '"',
        escapeChar: '"',
        header: true,
        dynamicTyping: true,
        preview: 0,
        encoding: "",
        delimitersToGuess: [',']
        // ?? callback function ??
      },
      cmd: {
        field: ',',
        categories: '|',
        id: '',
        hidden: '',
        timestamp: '',
        categoriesColumn: '',
        description: '',
        labels: '',
        ifFirstHead: true
      },
      file: [],
      originList: [], // 原始的可能包含表头的数据，默认存储最多21行（如果数据不止21行的话）
      list: [], // 页面table显示的数据
      columnList: [],// 上传csv的表头
      rules: {
        fid: [
          {required: true, message: '请选择文件'}
        ],
        field: [
          {required: true, message: '字段分隔符不能为空'}
        ],
        categories: [
          {required: true, message: '类别分隔符不能为空'}
        ],
      },
    }
  },
  mounted() {
    _this = this;
  },
  methods: {
    handleFileChange(file, fileList) {
      _this.file = file.raw;
      if(_this.cmd.field.length > 0) {
        _this.handleFieldChange();
      }
    },
    handleFieldChange() {
      this.$papa.parse(_this.file, {
        delimiter: _this.cmd.field,
        complete: (results) => {
          _this.originList = results.data.slice(0, 21);
          // 提前填充一个默认的值给对应的ID列和标签列
          _this.prepareFieldAndLabels();
          _this.refreshList();
        }
      })
    },
    prepareFieldAndLabels() {
      _this.columnList = _this.originList[0];
      _this.cmd.id = 0;
      _this.cmd.hidden = 1;
      _this.cmd.categoriesColumn = 2;
      _this.cmd.timestamp = 3;
      _this.cmd.labels = 4;
      _this.cmd.description = 5;
    },
    refreshList() {
      // 处理原始数据，将行文本截取成数组放入list
      _this.list = [];
      if (_this.cmd.field.length === 0) {
        return;
      }

      for (let i in _this.originList) {
        if (_this.cmd.ifFirstHead && i == 0) {
          // 第一行是表头，跳过list塞入
          continue;
        }
        let row = _this.originList[i];
        let errorFlag = false;

        let _labels = row[_this.cmd.labels].replaceAll('""', "'");
        try {
          JSON.parse(_labels);
        } catch (e) {
          errorFlag = true;
        }
        let categoriesArr = row[_this.cmd.categoriesColumn].split(_this.cmd.categories);
        _this.list.push({
          id: row[_this.cmd.id],
          labels: _labels,
          hidden: row[_this.cmd.hidden],
          categoriesColumn: categoriesArr,
          timestamp: row[_this.cmd.timestamp],
          description: row[_this.cmd.description],
          errorFlag: errorFlag
        });
      }
    },
    confirmSubmit() { // 提交确认
      this.$refs.cmd.validate((valid) => {
        let formData = new FormData();
        formData.append("sep", _this.cmd.field);
        formData.append("has-header", _this.cmd.ifFirstHead);
        formData.append("label-sep", _this.cmd.categories);
        formData.append("file", _this.file);
        let idIndex = _this.cmd.id;
        let labelIndex = _this.cmd.labels;
        let hiddenIndex = _this.cmd.hidden;
        let categoriesColumnIndex = _this.cmd.categoriesColumn;
        let timestampIndex = _this.cmd.timestamp;
        let descriptionIndex = _this.cmd.description;
        let _format = '';
        for (let i = 0; i <= Math.max(idIndex, labelIndex, hiddenIndex, categoriesColumnIndex, timestampIndex, descriptionIndex); i++) {
          if (i == idIndex) {
            _format += "i";
          } else if (i == hiddenIndex) {
            _format += "h";
          } else if (i == categoriesColumnIndex) {
            _format += "c";
          } else if (i == timestampIndex) {
            _format += "t";
          } else if (i == labelIndex) {
            _format += "l";
          } else if (i == descriptionIndex) {
            _format += "d";
          } else {
            _format += "_";
          }
        }
        console.log(_format)
        formData.append("format", _format);
        // request({
        //   url: '/gorse/bulk/items',
        //   method: 'put',
        //   data: formData
        // }).then(res => {
        //   if(res.data && res.data.RowAffected) {
        //     _this.$message.success(`成功导入${res.data.RowAffected}条记录`);
        //   } else {
        //     _this.$message.warning("导入异常");
        //   }
        // });
      });
    },
    backBtn() {
      this.$router.push({
        path: "entrysManage", query: {
          qo: JSON.stringify({
            pageNo: 1,
            pageSize: 10,
            LIKES_fid: '',
          })
        }
      });
    },

  }
}
</script>
<style src="../../../css/back.css" scoped></style>
<style scoped lang="scss">

.block_box {
  margin: 25px;
  background: #FFFFFF;
  border-radius: 3px;

  .title {
    border-bottom: 1px solid #ccc;
    padding: 15px 25px;
  }

  > div {
    padding: 25px;

  }

  .submit-btn {
    margin-left: auto;
    margin-top: 20px;
    display: flex;
  }
}
</style>
