<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 label="唯一标识：">
            <el-input v-model="qo.LIKES_fid" placeholder="请输入唯一标识" clearable style="width: 300px"></el-input>
          </el-form-item>
          <!--          <el-form-item label="种类：">-->
          <!--            <el-input v-model="qo.LIKES_categories" placeholder="请输入种类" clearable  style="width: 300px"></el-input>-->
          <!--          </el-form-item>-->
          <!--          <el-form-item label="标签：">-->
          <!--            <el-input v-model="qo.LIKES_labels" placeholder="请输入标签" clearable  style="width: 300px"></el-input>-->
          <!--          </el-form-item>-->
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="queryDataById()">搜 索</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="queryData(-1)">上一页</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="queryData(1)">下一页</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div style="margin: 0px 0 20px 0">
        <!--        <el-button type="primary" @click="createRow()" icon="el-icon-plus">添 加</el-button>-->
        <el-button type="primary" @click="downloadItem()" icon="el-icon-download">导出物类</el-button>
        <el-button type="primary" @click="showImportItemPage()" icon="el-icon-upload2">导入物类</el-button>
      </div>
      <div>
        <el-table :data="result.records" style="width: 100%" v-loading="loading">
          <el-table-column type="index" label="行号" width="60"></el-table-column>
          <el-table-column prop="ItemId" label="唯一标识"></el-table-column>
          <el-table-column prop="Categories" label="种类">
            <div slot-scope="scope">
              <template v-if="scope.row.Categories">
                <template v-for="(tag,index) in scope.row.Categories">
                  <el-tag :key="index" v-if="index < 5">{{ tag }}</el-tag>
                </template>
                <el-tag v-if="scope.row.Categories.length > 10">...</el-tag>
              </template>
            </div>
          </el-table-column>
          <el-table-column prop="Labels" label="标签">
            <div slot-scope="scope">
              <template v-if="scope.row.Labels">
                <template v-for="(tag,index) in scope.row.Labels">
                  <el-tag :key="index" v-if="index < 5">{{ tag }}</el-tag>
                </template>
                <el-tag v-if="scope.row.Labels.length > 5">...</el-tag>
              </template>
            </div>
          </el-table-column>
          <el-table-column prop="IsHidden" label="是否隐藏" width="100">
            <template slot-scope="scope">
              {{ scope.row.IsHidden ? '是' : '否' }}
            </template>
          </el-table-column>
          <el-table-column prop="description" label="描述">
            <template slot-scope="scope">
              {{ scope.row.Comment.substring(0, 100) }}{{ scope.row.Comment.length > 100 ? '...' : '' }}
            </template>
          </el-table-column>
          <el-table-column prop="Timestamp" label="创建时间" width="180"></el-table-column>
          <el-table-column label="操作" width="120">
            <template slot-scope="scope">
<!--              <el-button @click.native.prevent="modifyRow(scope.row)" type="text" size="small">-->
<!--                编辑-->
<!--              </el-button>-->
              <el-button @click.native.prevent="similarItem(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="dialogName"
        :visible.sync="cmdDialogVisible"
        width="40%">
      <el-form ref="cmd" label-width="100px" :rules="rules" :model="cmd">
        <el-form-item label="fid" prop="fid">
          <el-input v-model="cmd.fid" placeholder="请输入fid"></el-input>
        </el-form-item>
        <el-form-item label="种类">
          <el-tag
              :key="tag"
              v-for="(tag,index) in cmd.categoriesArr"
              closable
              :disable-transitions="false"
              @close="handleTagClose(index, 'categories')">
            {{ tag }}
          </el-tag>
          <el-input
              class="input-new-tag"
              v-if="categoriesInputVisible"
              v-model="categoriesInputValue"
              ref="saveCategoriesTagInput"
              size="small"
              @keyup.enter.native="handleInputConfirm('categories')"
              @blur="handleInputConfirm('categories')"
          >
          </el-input>
          <el-button v-else class="button-new-tag" size="small" @click="showInput('categories')">+ 种 类</el-button>
        </el-form-item>
        <el-form-item label="标签">
          <el-tag
              :key="tag"
              v-for="(tag,index) in cmd.labelsArr"
              closable
              :disable-transitions="false"
              @close="handleTagClose(index, 'labels')">
            {{ tag }}
          </el-tag>
          <el-input
              class="input-new-tag"
              v-if="labelsInputVisible"
              v-model="labelsInputValue"
              ref="saveLabelsTagInput"
              size="small"
              @keyup.enter.native="handleInputConfirm('labels')"
              @blur="handleInputConfirm('labels')"
          >
          </el-input>
          <el-button v-else class="button-new-tag" size="small" @click="showInput('labels')">+ 标 签</el-button>
        </el-form-item>
        <el-form-item label="是否隐藏" prop="isHidden">
          <el-radio v-model="cmd.isHidden" :label="true">是</el-radio>
          <el-radio v-model="cmd.isHidden" :label="false">否</el-radio>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="cmd.description" placeholder="请输入描述" type="textarea" :rows="5"></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, {getBaseUrl} from '@/utils/request';

var _this;
export default {
  name: "entrys",
  data() {
    return {
      qo: {
        pageNo: 1,
        pageSize: 10,
        LIKES_fid: '',
        LIKES_categories: '',
        LIKES_labels: '',
      },
      result: {
        records: [],
        total: 0
      },
      loading: false,
      cursorArr: [''],
      sourceTypeList: [
        {name: '自定义本体', value: 1},
        {name: '标注系统', value: 2}
      ],
      dialogName: '编辑',
      cmdDialogVisible: false,
      cmd: {},
      rules: {
        fid: [
          {required: true, message: '请输入fid'}
        ],
        isHidden: [
          {required: true, message: '请选择是否隐藏'}
        ],
      },
      categoriesInputValue: '',
      categoriesInputVisible: false,
      labelsInputValue: '',
      labelsInputVisible: false
    }
  },
  mounted() {
    _this = this;
    let _qo = _this.$route.query.qo;
    if (_qo) {
      _this.qo = JSON.parse(_qo);
    }
    _this.queryData(0);
  },
  methods: {
    queryDataById() {
      if (this.qo.LIKES_fid.length > 0) {
        this.loading = true;
        request({
          url: '/gorse/query_item/' + this.qo.LIKES_fid,
          method: 'get',
        }).then(res => {
          let item = res.data;
          if (!item) {
            _this.result.records = [];
          } else {
            _this.result.records = [item];
          }
          this.loading = false;
        });
      } else {
        this.cursorArr = [''];
        this.queryData(1);
      }
    },
    queryData(index) {// index -1 上一页，0刷新， 1下一页
      this.loading = true;
      this.cursorArr = this.cursorArr.slice(0, this.cursorArr.length - 1 + index);
      this.cursorArr = this.cursorArr.length === 0 ? [''] : this.cursorArr;
      request({
        url: '/gorse/query_items?cursor=' + this.cursorArr[this.cursorArr.length - 1],
        method: 'get',
      }).then(res => {
        this.cursorArr.push(res.data.Cursor);
        _this.result.records = res.data.Items;
        this.loading = false;
      });
    },
    handleCurrentChange(val) {
      _this.qo.pageNo = val;
      _this.queryData();
    },
    downloadItem() {
      window.open(getBaseUrl() + '/bulk/get_bulk/items');
    },
    similarItem(item) {
      _this.$router.push({
        path: "similarItem", query: {
          itemId: item.ItemId,
          qo: JSON.stringify(_this.qo)
        }
      });
    },
    showImportItemPage() {
      _this.$router.push({
        path: "importItem"
      });
    },
    removeRow(item) {
      _this.$confirm('此操作将永久删除记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        request({
          url: '/gorse/delete_item/' + item.ItemId,
          method: 'post'
        }).then(res => {
          _this.$message.success("删除成功");
          _this.queryData(0);
        });
      }).catch(() => {
      });
    },
    createRow() {
      _this.dialogName = '新建';
      _this.cmdDialogVisible = true;
      _this.$nextTick(_ => {
        _this.$refs['cmd'].clearValidate();
        _this.cmd = {
          fid: '',
          isHidden: false,
          categoriesArr: [],
          labelsArr: [],
          description: ''
        };
      })
    },
    modifyRow(item) {
      _this.dialogName = '编辑';
      _this.cmdDialogVisible = true;
      _this.$nextTick(_ => {
        _this.$refs['cmd'].clearValidate();
        _this.cmd = JSON.parse(JSON.stringify(item));
      })
    },
    submitModify() {
      this.$refs.cmd.validate((valid) => {
        if (valid) {
          if (_this.cmd.categoriesArr) {
            _this.cmd.categories = _this.cmd.categoriesArr.toString();
          }
          if (_this.cmd.labelsArr) {
            _this.cmd.labels = _this.cmd.labelsArr.toString();
          }

          if (_this.cmd.id) {
            request({
              url: '/entrys/modify',
              method: 'post',
              data: _this.cmd
            }).then(res => {
              _this.$message.success("编辑成功");
              _this.queryData();
              _this.cmdDialogVisible = false;
            });
          } else { // 新建
            request({
              url: '/entrys/create',
              method: 'post',
              data: _this.cmd
            }).then(res => {
              _this.$message.success("添加成功");
              _this.cmdDialogVisible = false;
            });
          }
        }
      });
    },
    showInput(typeName) {
      if (typeName === 'categories') {
        this.categoriesInputVisible = true;
        this.$nextTick(_ => {
          this.$refs.saveCategoriesTagInput.$refs.input.focus();
        });
      } else if (typeName === 'labels') {
        this.labelsInputVisible = true;
        this.$nextTick(_ => {
          this.$refs.saveLabelsTagInput.$refs.input.focus();
        });
      }
    },
    handleTagClose(index, typeName) {
      _this.cmd[typeName + "Arr"].splice(index, 1);
    },
    handleInputConfirm(typeName) {
      let inputValue = _this[typeName + "InputValue"];
      if (inputValue) {
        _this.cmd[typeName + "Arr"].push(inputValue);
      }
      _this[typeName + "InputVisible"] = false;
      _this[typeName + "InputValue"] = "";
    }
  }
}
</script>

<style lang="scss">
.input-new-tag {
  margin-bottom: 12px;
  height: 32px;
  width: 80px;

  input {
    height: 32px !important;
    width: 80px;
  }
}

.el-tag {
  margin-right: 10px;
  margin-bottom: 10px;
  height: 32px;
}

.button-new-tag {
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;

}
</style>
