<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 {
    display: flex;
    justify-content: space-between;
    .tips {
      font-size: 14px;
      margin-top: 15px;
    }
    .inp {
      width: 280px;

      /deep/.el-input__inner {
        height: 30px;
        margin-top: 10px;
      }
    }
  }

  .table_form {
    width: 100%;
    box-sizing: border-box;
    background: #fff;
    padding: 20px;
    padding-bottom: 0;
    display: flex;
    flex-wrap: wrap;
  }
  .table_content {
    min-height: 200px;
    height: calc(100vh - 264px);
    margin-top: 10px;
    display: flex;
    justify-content: space-between;
    .table_left {
      flex: 1;
      margin-right: 10px;
      background: #ffffff;
      padding: 0 50px;

      .left_box {
        margin: 30px 0;
        overflow: hidden;
        overflow-y: auto;
        height: calc(100vh - 410px);
      }
      .tabs {
        float: left;
        max-width: 49%;
        min-width: 49%;
      }
      .form_btn {
        display: flex;
        justify-content: flex-end;
      }
    }
    .table_right {
      width: 300px;
      background: #ffffff;
    }
  }
  /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;
  }
  .conceptSearch {
    width: 100%;
    text-align: center;
    z-index: 2;
    padding: 30px;
    box-sizing: border-box;
    .conceptTitle {
      width: 100%;
      text-align: center;
      padding: 20px 0;
      font-size: 14px;
    }
    .searchText {
      padding: 0 35px 0 15px;
      width: 100%;
      height: 34px;
      border: 1px solid #c9c9c9;
      box-sizing: border-box;
    }
    .conceptList {
      min-height: 200px;
      max-height: 300px;
      margin: -2px auto 0;
      border: 1px solid #e1dfdf;
      overflow: hidden;
      overflow-y: auto;
    }
    .conceptItem {
      height: 34px;
      line-height: 34px;
      text-align: left;
      padding: 0 15px;
      cursor: pointer;
    }
    .conceptItem:hover {
      background: #f5f7fa;
    }
    .searchWrap {
      position: relative;
      .search {
        position: absolute;
        right: 7px;
        top: 8px;
      }
    }
  }
  .noresult {
    padding: 20px 0;
    color: #ccc;
  }
}
</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"
              ></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">
            <h4 class="tips">关联的术语({{form.concepts.length}})</h4>
            <el-input v-model="searchtext" @input="searchList" placeholder="请搜索" class="inp"></el-input>
          </div>

          <div class="left_box">
            <el-table
              v-if="firstList.length>0"
              :data="firstList"
              border
              class="tabs"
              :header-row-style="{height:'40px'}"
              :header-cell-style="{height:'40px',padding:'0',background:'#f7f7f7'}"
            >
              <el-table-column prop="conceptLibName" :show-overflow-tooltip="true" label="术语名称"></el-table-column>
              <el-table-column label="操作" fixed="right">
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    size="small"
                    class="delete"
                    @click="showDelDialog(scope.row)"
                  >移除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-table
              v-if="lastList.length>0"
              :data="lastList"
              border
              class="tabs"
              :header-row-style="{height:'40px'}"
              :header-cell-style="{height:'40px',padding:'0',background:'#f7f7f7'}"
            >
              <el-table-column prop="conceptLibName" :show-overflow-tooltip="true" label="术语名称"></el-table-column>
              <el-table-column label="操作" fixed="right">
                <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="conceptSearch" ref="conceptSearch">
            <h4 class="conceptTitle">添加关联术语</h4>
            <p class="searchWrap">
              <img class="search" src="../../images/search.png" alt="搜索" />
              <input
                v-model.trim="conceptText"
                @input="searchConcept"
                type="text"
                ref="conceptInput"
                class="searchText"
                placeholder="请输入关键词搜索"
              />
            </p>
            <ul class="conceptList" ref="conceptList">
              <li
                v-for="item in conceptList"
                class="conceptItem ellipsis"
                :title="item.conceptName"
                @click="selectConcept(item)"
                :key="item.conceptId"
              >{{item.conceptName}}</li>
              <li class="noresult" v-if="conceptList.length==0">暂无结果~</li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script type="text/javascript">
import api from '@api/knowledgeLib.js';
import AddNewRuleTable from './AddNewRuleTable';
export default {
  name: 'AddRule',
  data() {
    return {
      title: '术语集合内容维护-添加',
      ruleTypeList: [],
      ruleTermTypeList: [],
      conceptList: [],
      conceptText: '',
      excludedConceptIds: [],
      type: [],
      firstList: [],
      lastList: [],
      sign: 1,
      searchtext: '',
      len: null,
      form: {
        collectionLibType: '',
        collectionLibName: '',
        concepts: [],
        conceptLibType: '',
        collectionRemark: '',
        collectionId: ''
      },
      whether: false,
      editCount: -1, // 页面会否被编辑 >0被编辑   =0 未编辑
      startCount: -1,
      isSaveSuccess: false, // 是否保存成功
      rules: {
        collectionLibType: [
          { required: true, message: '请选择术语集合类型', trigger: 'change' }
        ],
        collectionLibName: [
          { required: true, message: '请选择术语集合名称', trigger: 'change' }
        ]
      }
    };
  },
  created() {
    this.getDict();
    const param = this.$route.params;
    let info = param.data;
    if (info) {
      this.title = '术语集合内容维护-' + '修改';
      this.form.collectionLibType = JSON.stringify(info.collectionLibType);
      this.form.collectionLibName = info.collectionLibName;
      this.form.concepts = info.concepts;
      this.form.conceptLibType = info.concepts[0].conceptLibType;
      this.form.collectionId = info.collectionId;
      this.form.collectionRemark = info.collectionRemark;
      this.sign = 2;
      this.$nextTick(() => {
        this.getList(this.form.concepts);
        this.getIds(this.form.concepts);
        this.searchConcept()
      });
    }
    setTimeout(() => {
      this.startCount = this.editCount;
    }, 500);
  },
  methods: {
    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(val) {
      let concepts = JSON.parse(JSON.stringify(this.form.concepts));
      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.getList(arr);
    },
    getCollectionLib(newValue) {
      this.form.collectionLibName = newValue.conceptName;
      this.form.collectionId = newValue.conceptId;
      this.form.collectionRemark = newValue.remark;
    },
    // 基础术语
    async searchConcept() {
      this.whether = true;
      const params = {
        typeId: this.form.conceptLibType,
        name: this.conceptText,
        excludedConceptIds: this.excludedConceptIds
      };
      const data = await api.getTreeSearchList(params);
      if (data.data.code == '0') {
        this.conceptList = data.data.data;
        this.whether = false;
      }
    },
    // 选择基础术语
    selectConcept(item) {
      if (this.whether) {
        return;
      }
      let concepts = {
        conceptId: item.conceptId,
        conceptLibType: item.conceptNameType,
        conceptLibName: item.conceptName
      };
      this.excludedConceptIds.push(item.conceptId);
      this.form.concepts.push(concepts);
      this.getList(this.form.concepts);
      this.$nextTick(() => {
        this.searchConcept();
      });
    },
    // 切换术语类型
    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) {
      this.form.concepts.forEach((item, index) => {
        if (item.conceptId == row.conceptId) {
          this.form.concepts.splice(index, 1);
          this.excludedConceptIds.splice(index, 1);
        }
      });
      this.searchConcept();
      if (this.searchtext != '') {
        this.searchList(this.searchtext);
      } else {
        this.getList(this.form.concepts);
      }
    },
    getchk(num) {
      return num % 2 == 0 ? '偶数' : '奇数'; //判断是否能整除2
    },
    getList(arr) {
      this.firstList = [];
      this.lastList = [];
      arr.forEach((item, index) => {
        if (this.getchk(index) == '偶数') {
          this.firstList.push(item);
        } else {
          this.lastList.push(item);
        }
      });
    },
    saveSet() {
      let params = {
        ...this.form,
        relationId: 0
      };
      api.saveOrUpdateRecord(params).then(res => {
        if (res.data.code == 0) {
          this.$message({
            message: '操作成功',
            type: 'success'
          });
          this.isSaveSuccess = true;
          this.$router.push({
            name: 'TermSet',
            params: Object.assign({}, this.$route.params, { currentPage: 1 })
          });
        } else {
          this.$message({
            message: res.data.msg,
            type: 'warning'
          });
        }
      });
    },
    clearData() {
      this.form.collectionLibName = '';
      this.conceptText = '';
      this.ruleTermTypeList = [];
      this.form.concepts = [];
      this.getList(this.form.concepts);
      this.searchConcept();
    }
  },
  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 != ''
      );
    }
  }
};
</script>
