<style lang="less" scoped>
// @import "../../less/admin.less";
#AddRuleContent {
  width: 100%;
  min-width: 1000px;
  padding: 20px;
  padding-top: 50px;
  padding-bottom: 0;
  box-sizing: border-box;
  .form {
    width: 100%;
  }
  .remark {
    font-size: 14px;
    color: #606266;
    position: relative;
    left: 34px;
    top: -10px;
    padding-right: 30px;
  }

  .left_header {
    height: 40px;
    display: flex;
    justify-content: space-between;
    .tips {
      margin-top: 15px;
    }
    .inp {
      width: 150px;
      /deep/.el-input__inner {
        height: 30px;
        margin-top: 10px;
      }
    }
  }
  .right_header {
    display: flex;
  }
  .table_form {
    width: 100%;
    box-sizing: border-box;
    background: #fff;
    padding: 20px;
    padding-bottom: 0;
    display: flex;
    flex-wrap: wrap;
  }
  .table_content {
    margin-top: 10px;
    overflow: hidden;
    .table_left {
      width: 45%;
      float: left;
      margin-right: 10px;
      background: #ffffff;
      padding: 0 2%;
      .left_box {
        margin: 30px 0;
        overflow: hidden;
        min-height: calc(100vh - 410px);
      }
      .tabs {
        max-width: 100%;
        min-width: 100%;
        border-color: #DCDFE6;
      }
      .form_btn {
        display: flex;
        justify-content: flex-end;
        padding-bottom: 15px;
      }
    }
    .table_right {
      width: 45%;
      float: right;
      background: #ffffff;
      padding: 0 2%;
      .right_box {
        margin: 30px 0;
        overflow: hidden;
        min-height: calc(100vh - 410px);
      }
      .tabs {
        max-width: 100%;
        min-width: 100%;
        border-color: #DCDFE6;
      }
      .inp {
        width: 100px;
        /deep/.el-input__inner {
          height: 30px;
          margin-top: 10px;
        }
      }
      .inps {
        margin-right: 10px;
      }
      .form_btn {
        display: flex;
        justify-content: space-between;
        padding-bottom: 15px;
      }
    }
  }
  /deep/.el-select-dropdown__item.hover,
  .el-select-dropdown__item:hover {
    color: #48c5d7;
  }
  /deep/ .el-form--inline .el-form-item__label {
    font-size: 14px;
    color: #606266;
  }
  /deep/ .el-input--mini .el-input__inner,
  .el-select {
    width: 100%;
    font-size: 14px;
  }
  /deep/ .el-form-item.is-success .el-input__inner,
  .el-form-item.is-success .el-textarea__inner {
    border-color: #c9c9c9 !important;
  }
  /deep/ .el-form-item.is-success .el-textarea__inner {
    border-color: #c9c9c9 !important;
  }
  /deep/ .el-form-item.is-success .el-textarea__inner {
    border-color: #c9c9c9 !important;
  }
  /deep/ .el-table th.gutter {
    display: table-cell !important;
  }
  /deep/.el-table .cell,
  .el-table--border td:first-child .cell,
  .el-table--border th:first-child .cell {
    padding-right: 14px;
  }
  /*table边框颜色*/
  /deep/ .el-table--border:after,
  .el-table--group:after,
  .el-table:before {
    background-color: #DCDFE6;
  }
  /deep/ .el-table--border,
  .el-table--group {
    border-color: #DCDFE6;
  }
  /deep/ .el-table td,
  .el-table th.is-leaf {
    border-bottom: 1px solid #DCDFE6;
  }

  /deep/ .el-table--border th,
  .el-table--border th.gutter:last-of-type {
    border-bottom: 1px solid #DCDFE6;
  }

  /deep/ .el-table--border td,
  .el-table--border th {
    border-right: 1px solid #DCDFE6;
  }
}
.test_box {
  min-height: 300px;
  max-height: 300px;
  outline: 0;
  border: 1px solid #dcdfe6;
  font-size: 14px;
  line-height: 1.5;
  word-wrap: break-word;
  overflow-x: hidden;
  overflow-y: auto;
  border-radius: 4px;
  margin-top: 6px;
  padding: 10px 15px;
}
</style>
<style scoped>
</style>
<template>
  <div>
    <crumbs :title="title" :param="$route.params" linkTo="TermSet"></crumbs>
    <div id="AddRuleContent">
      <div class="table_form">
        <el-form
          size="mini"
          :inline="true"
          class="demo-form-inline form"
          :model="form"
          :rules="rules"
        >
          <el-form-item label-width="130px" label="术语集合类型：" prop="collectionLibType">
            <el-select
              v-model="form.collectionLibType"
              placeholder="请选择"
              @change="getConceptLibType"
              :disabled="sign==2?true:false"
              :title="form.collectionLibName"
            >
              <el-option
                v-for="item in ruleTypeList"
                :key="item.val"
                :label="item.name"
                :value="item.val"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 规则术语类型： -->
          <el-form-item label-width="130px" label="术语集合名称：" prop="collectionLibName">
            <el-select
              clearable
              remote
              filterable
              v-model.trim="form.collectionLibName"
              placeholder="请输入"
              :remote-method="searchLibName"
              @change="getCollectionLib"
              :disabled="sign==2?true:false"
              value-key="conceptId"
              :title="form.collectionLibName"
            >
              <el-option
                v-for="item in ruleTermTypeList"
                :key="item.conceptId"
                :label="item.conceptName"
                :value="item.conceptName"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div class="remark">说明：{{form.collectionRemark}}</div>
      </div>
      <div class="table_content" v-if="onshow">
        <div class="table_left">
          <div class="left_header">
            <h5 class="tips">关联的术语({{form.concepts.length}})</h5>
            <div style="display:flex">
              <el-input v-model.trim="searchtext" @input="searchList" placeholder="关键词" class="inp"></el-input>
              <span style="display:flex;align-items: center;margin:0 5px">-</span>
              <el-input
                v-model.trim="searchtext2"
                @input="searchList"
                placeholder="关键词"
                class="inp"
              ></el-input>
            </div>
          </div>

          <div class="left_box">
            <el-table
              :data="leftList"
              border
              style="min-height: 200px"
              height="calc(100vh - 393px)"
              class="tabs"
              ref="table"
              :header-row-style="{height:'40px'}"
              :header-cell-style="{height:'40px',borderColor:'#DCDFE6'}"
            >
              <el-table-column prop="conceptLibName" :show-overflow-tooltip="true" label="术语名称"></el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    size="small"
                    class="delete"
                    @click="showDelDialog(scope.row)"
                  >移除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <div class="form_btn">
            <el-button type="primary" size="medium " @click="saveSet">确定</el-button>
          </div>
        </div>
        <div class="table_right">
          <div class="right_header">
            <el-select
              v-model="formInline.logicalOperator"
              class="inp inps"
              @change="searchConcept"
            >
              <el-option label="and" value="0"></el-option>
              <el-option label="or" value="1"></el-option>
            </el-select>
            <el-input
              v-model.trim="formInline.name1"
              @input="searchConcept"
              placeholder="关键词"
              class="inp"
            ></el-input>
            <span style="display:flex;align-items: center;margin:0 5px">-</span>
            <el-input
              v-model.trim="formInline.name2"
              @input="searchConcept"
              placeholder="关键词"
              class="inp"
            ></el-input>
            <span style="display:flex;align-items: center;margin:0 5px">-</span>
            <el-input
              v-model.trim="formInline.name3"
              @input="searchConcept"
              placeholder="关键词"
              class="inp"
            ></el-input>
          </div>

          <div class="right_box">
            <el-table
              :data="conceptList"
              border
              style="min-height: 200px"
              height="calc(100vh - 393px)"
              class="tabs"
              ref="tables"
              @row-click="btn"
              :header-row-style="{height:'40px'}"
              :header-cell-style="{height:'40px',borderColor:'#DCDFE6'}"
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection"></el-table-column>
              <el-table-column prop="conceptName" :show-overflow-tooltip="true" label="术语名称"></el-table-column>
            </el-table>
          </div>
          <div class="form_btn">
            <el-button size="medium " @click="add" icon="el-icon-caret-left">添加</el-button>
            <el-button size="medium " @click="dialogVisible = true">文本批量添加</el-button>
          </div>
        </div>
      </div>
    </div>
    <el-dialog
      :title="'请输入要添加到关联的标准术语（每行一个）'+'共'+len+'行'"
      :visible.sync="dialogVisible"
      width="30%"
      :close-on-click-modal="false"
      :showClose="false"
    >
      <div
        class="test_box"
        contenteditable="true"
        ref="msg"
        style="white-space: pre-wrap"
        @input="handleInput"
      ></div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="collectcancel">保存并关闭</el-button>
        <el-button type="primary" @click="collectionMatch">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script type="text/javascript">
import api from '@api/knowledgeLib.js';
import AddNewRuleTable from './AddNewRuleTable';
import axios from 'axios';
export default {
  name: 'AddRule',
  data() {
    return {
      title: '术语集合内容维护-添加',
      formInline: {
        logicalOperator: '0',
        name1: '',
        name2: '',
        name3: ''
      },
      innerText: '',
      ruleTypeList: [],
      ruleTermTypeList: [],
      conceptList: [],
      conceptText: '',
      excludedConceptIds: [],
      type: [],
      leftList: [],
      multipleSelection: [],
      sign: 1,
      searchtext: '',
      searchtext2: '',
      dialogVisible: false,
      form: {
        collectionLibType: '',
        collectionLibName: '',
        concepts: [],
        conceptLibType: '',
        collectionRemark: '',
        collectionId: ''
      },
      whether: false,
      editCount: -1, // 页面会否被编辑 >0被编辑   =0 未编辑
      startCount: -1,
      isSaveSuccess: false, // 是否保存成功
      timeout: null,
      rules: {
        collectionLibType: [
          { required: true, message: '请选择术语集合类型', trigger: 'change' }
        ],
        collectionLibName: [
          { required: true, message: '请选择术语集合名称', trigger: 'change' }
        ]
      }
    };
  },
  created() {
    this.getDict();
    const param = this.$route.params;
    let type = param.type;
    if (type == 2) {
      this.title = '术语集合内容维护-' + '修改';
      this.getInfo(param.id);
      this.sign = 2;
    }
    setTimeout(() => {
      this.startCount = this.editCount;
    }, 500);
  },
  methods: {
    handleInput(event) {
      let text = event.target.innerText;
      this.innerText = text.replace(/(^\s*)|(\s*$)/g, '');
    },
    getInfo(id) {
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      api
        .getRecordById({ id })
        .then(res => {
          loading.close();
          if (res.data.code == '0') {
            const data = res.data.data;
            this.form.collectionLibType = JSON.stringify(
              data.collectionLibType
            );
            this.form.collectionLibName = data.collectionLibName;
            this.form.concepts = data.concepts;
            this.form.conceptLibType = data.concepts[0].conceptLibType;
            this.form.collectionId = data.collectionId;
            this.form.collectionRemark = data.collectionRemark;
            this.leftList = data.concepts;
            this.$nextTick(() => {
              this.getIds(this.form.concepts);
              this.getTreeSearchList();
            });
          }
        })
        .catch(error => {
          loading.close();
          this.warning('获取详情失败，请重试');
        });
    },
    collectcancel() {
      this.dialogVisible = false;
    },
    cancelRequest() {
      if (typeof this.source === 'function') {
        this.source('终止请求');
      }
    },
    getDict() {
      api
        .zskgetDict()
        .then(res => {
          if (res.data.code == '0') {
            const data = res.data.data;
            this.ruleTypeList = data[63];
            this.type = data[61];
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    //过滤集合id
    getIds(arr) {
      arr.forEach((item, index) => {
        this.excludedConceptIds.push(item.conceptId);
      });
    },
    //获取术语集合名称
    searchLibName(val) {
      api
        .getSearchConcept({
          excludedConceptIds: [0],
          libType: this.form.collectionLibType,
          name: val
        })
        .then(res => {
          if (res.data.code == '0') {
            const data = res.data.data;
            this.ruleTermTypeList = data;
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    searchList() {
      let concepts, val;
      if (
        (this.searchtext != '' && this.searchtext2 == '') ||
        (this.searchtext == '' && this.searchtext2 != '')
      ) {
        concepts = JSON.parse(JSON.stringify(this.form.concepts));
        val = this.searchtext != '' ? this.searchtext : this.searchtext2;
      } else if (this.searchtext != '' && this.searchtext2 != '') {
        concepts = JSON.parse(JSON.stringify(this.leftList));
        val = this.searchtext2;
      } else if (this.searchtext == '' && this.searchtext2 == '') {
        this.leftList = JSON.parse(JSON.stringify(this.form.concepts));
        return;
      }
      let str = '.*' + val + '.*';
      let reg = new RegExp(str);
      let arr = [];
      //通过附加信息查询
      for (var i = 0; i < concepts.length; i++) {
        if (reg.test(concepts[i].conceptLibName)) {
          arr.push(concepts[i]);
        }
      }
      this.$refs.table.bodyWrapper.scrollTop = 0;
      this.leftList = arr;
    },
    getCollectionLib(newValue) {
      this.ruleTermTypeList.forEach(item => {
        if (newValue == item.conceptName) {
          // this.form.collectionLibName = item.conceptName;
          this.form.collectionId = item.conceptId;
          this.form.collectionRemark = item.remark;
        }
      });
    },
    // 基础术语
    searchConcept(e) {
      if (this.timeout) {
        clearTimeout(this.timeout);
      }
      this.timeout = setTimeout(() => {
        this.getTreeSearchList();
        this.$refs.tables.bodyWrapper.scrollTop = 0;
      }, 800);
    },
    async getTreeSearchList() {
      this.whether = true;
      const params = {
        libType: this.form.conceptLibType,
        names: [
          this.formInline.name1,
          this.formInline.name2,
          this.formInline.name3
        ],
        excludedConceptIds: this.excludedConceptIds,
        logicalOperator: this.formInline.logicalOperator
      };
      const data = await api.searchCollectionConceptVO(params);
      if (data.data.code == '0') {
        this.conceptList = data.data.data;
        this.whether = false;
      }
    },
    btn(row) {
      if (this.whether) {
        return;
      }
      let concepts = {
        conceptId: row.conceptId,
        conceptLibType: row.libType,
        conceptLibName: row.conceptName
      };
      this.excludedConceptIds.push(row.conceptId);
      this.form.concepts.push(concepts);
      this.leftList = this.form.concepts;
      this.conceptList = [];
      this.searchtext = '';
      this.searchtext2 = '';
      this.$nextTick(() => {
        setTimeout(() => {
          this.getTreeSearchList();
        }, 150);
      });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    add() {
      if (this.multipleSelection.length == 0) {
        this.$message({
          message: '添加数据不能为空',
          type: 'warning'
        });
        return;
      }
      this.processing(this.multipleSelection);
      this.searchtext = '';
      this.searchtext2 = '';
    },
    //去重
    unique(arr) {
      let obj = {};
      arr = arr.reduce(function(item, next) {
        obj[next.conceptId]
          ? ''
          : (obj[next.conceptId] = true && item.push(next));
        return item;
      }, []);
      return arr;
    },
    //过滤数组去重
    unique2(arr) {
      let obj = {};
      arr = arr.reduce(function(item, next) {
        obj[next] ? '' : (obj[next] = true && item.push(next));
        return item;
      }, []);
      return arr;
    },
    //处理数据
    processing(arr) {
      if (this.whether) {
        return;
      }
      arr.forEach(it => {
        let concepts = {
          conceptId: it.conceptId,
          conceptLibType: it.libType ? it.libType : it.conceptLibType,
          conceptLibName: it.conceptName ? it.conceptName : it.conceptLibName
        };
        this.excludedConceptIds.push(it.conceptId);
        this.form.concepts.push(concepts);
      });

      this.form.concepts = this.unique(this.form.concepts);
      this.excludedConceptIds = this.unique2(this.excludedConceptIds);
      this.leftList = this.form.concepts;
      this.conceptList = [];
      this.multipleSelection = [];
      this.$nextTick(() => {
        setTimeout(() => {
          this.getTreeSearchList();
        }, 150);
      });
    },
    // 切换术语类型
    getConceptLibType() {
      this.type.forEach(it => {
        let id = it.val.split('-');
        if (this.form.collectionLibType == id[0]) {
          this.form.conceptLibType = id[2];
        }
      });
      this.clearData();
    },
    // 移除术语
    showDelDialog(row) {
      if (this.searchtext == '' && this.searchtext2 == '') {
        this.form.concepts.forEach((item, index) => {
          if (item.conceptId == row.conceptId) {
            this.form.concepts.splice(index, 1);
            this.excludedConceptIds.splice(index, 1);
          }
        });
        this.leftList = this.form.concepts;
      } else {
        this.leftList.forEach((item, index) => {
          if (item.conceptId == row.conceptId) {
            this.leftList.splice(index, 1);
          }
        });
        this.form.concepts.forEach((item, index) => {
          if (item.conceptId == row.conceptId) {
            this.form.concepts.splice(index, 1);
            this.excludedConceptIds.splice(index, 1);
          }
        });
      }
      this.getTreeSearchList();
    },
    saveSet() {
      let params = {
        ...this.form,
        relationId: 0
      };
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      api.saveOrUpdateRecord(params).then(res => {
        loading.close();
        if (res.data.code == 0) {
          this.$message({
            message: '操作成功',
            type: 'success'
          });
          this.loading2 = false;
          this.isSaveSuccess = true;
          this.$router.push({
            name: 'TermSet',
            params: Object.assign({}, this.$route.params, { currentPage: 1 })
          });
        } else {
          this.$message({
            message: res.data.msg,
            type: 'error'
          });
          loading.close();
        }
      });
    },
    collectionMatch() {
      if (this.innerText.length == 0) {
        this.$message({
          message: '术语名称不能为空',
          type: 'error'
        });
        return;
      }
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      let params = {
        conceptLibNames: this.innerText,
        conceptLibType: this.form.conceptLibType
      };
      api
        .collectionMatch(params)
        .then(res => {
          loading.close();
          if (res.data.code == '0') {
            const data = res.data.data;
            let text = '';
            if (data.matchList.length > 0) {
              this.processing(data.matchList);
              if (
                data.unMatchList.length == 0 &&
                data.disableList.length == 0
              ) {
                this.dialogVisible = false;
              }
            }
            if (data.unMatchList.length > 0 || data.disableList.length > 0) {
              this.$message({
                message: '列表中存在非标准术语或禁用术语',
                type: 'error'
              });
              let arr = data.unMatchList.concat(data.disableList);
              arr.forEach(it => {
                text += it.conceptLibName + '\n';
              });
            }
            this.$refs.msg.innerHTML = text;
            this.innerText = text;
          }
        })
        .catch(error => {
          console.log(error);
          loading.close();
        });
    },
    clearData() {
      this.form.collectionLibName = '';
      this.conceptText = '';
      this.ruleTermTypeList = [];
      this.form.concepts = [];
      this.leftList = [];
      this.getTreeSearchList();
    }
  },
  watch: {
    form: {
      handler(newName, oldName) {
        this.editCount++;
      },
      deep: true,
      immediate: true
    }
  },
  beforeRouteLeave(to, from, next) {
    if (
      this.startCount !== this.editCount &&
      this.form.concepts.length > 0 &&
      !this.isSaveSuccess
    ) {
      this.$alert('还有未保存的内容,确定要退出当前页面吗?', '提示', {
        confirmButtonText: '确定',
        // cancelButtonText: '取消',
        // cancelButtonClass: 'leaveBtn',
        // customClass: 'leaveBox',
        type: 'warning'
      })
        .then(() => {
          next();
        })
        .catch(() => {});
    } else {
      next();
    }
  },
  computed: {
    onshow() {
      return (
        this.form.collectionLibType != '' && this.form.collectionLibName != ''
      );
    },
    len() {
      let arr = this.innerText.split('\n');
      let len = 0;
      arr.forEach(it => {
        if (it != '') {
          len++;
        }
      });
      return len;
    }
  }
};
</script>
