<template>
  <div class="addMedicalMultRelationWrapper">
    <crumbs :title="minTitle" fix="fixed" linkTo=""></crumbs>
    <TreeTab @getTreeList="getTreeList" />
    <div class="contents">
      <div class="content">
        <div class="addBtn" v-if="list.length == 0">
          <!-- <el-button
            @click="addConcept"
          >+ 新 增</el-button> -->
        </div>

        <div class="tree">
          <el-tree
            :data="list"
            :props="defaultProps"
            node-key="conceptId"
            draggable
            :allow-drag="allowDrag"
            :allow-drop="allowDrop"
            :expand-on-click-node="true"
            :render-after-expand="true"
            :highlight-current="true"
            :default-expanded-keys="defaultExpandedArr"
            @node-click = "handleNodeClick"
          >
            <span class="custom-tree-node" slot-scope="{ node, data }" >
                <span class="custom-tree-node-name ellipsis" :class="{colorGray: data.isDeletedConcept == 'Y'}" :title="node.label">{{ node.label }}</span>
                <span class="btn-box">
                  <el-button
                      class="btn-add fl"
                      v-show="data.level < 2"
                      type="text"
                      size="mini"
                      @click="(e) => append(data, e)">
                      + 增加
                  </el-button>
                  <el-button
                      class="btn-del fr"
                      v-show="data.level != 0"
                      type="text"
                      size="mini"
                      @click="() => remove(node, data)">
                      删除
                  </el-button>
                </span>
            </span>
          </el-tree>
        </div>
        <div class="btn">
          <el-button
            type="primary"
            :disabled = 'saveDisable'
            @click="confirm"
          >确 定</el-button>
        </div>
      </div>
    </div>
    <SearchList 
      v-if="showSearch" 
      :conceptList="conceptList" 
      :addLevel="addLevel"
      @closeSearch="closeSearch" 
      @selectConcept="selectConcept" 
      @searchConcept="searchConcept" />
  </div>
</template>
<script type="text/javascript">
import api from '@api/knowledgeTree.js';
import SearchList from '../basicKnow/SearchList.vue';
import TreeTab from '../basicKnow/TreeTab.vue';

export default {
    name:'KnowledgeAll',
    components:{
      SearchList,TreeTab
    },
    data(){
      return{
        minTitle:'树形结构维护',
        tab:[
          {name:'ICD10疾病类别',id:'1'},
          {name:'科室疾病类别',id:'2'},
          {name:'药物类别',id:'3'},
          {name:'症状类别',id:'4'},
          {name:'手术和操作类别',id:'5'},
          {name:'实验室检查类别',id:'6'},
          {name:'辅助检查类别',id:'7'},
        ],
        curId:'1',
        list: [],
        defaultProps: {
          children: 'nodeList',
          label: 'conceptName'
        },
        conceptList: [], //概念列表
        showSearch: false,
        addLevel: 0,  //添加级别
        excludedConceptIds:[],
        operaList: [],
        relationConceptId: '', //关联父类ID
        level: 0, //层级（修改时只能显示三级）
        saveDisable: false,  //保存按钮禁止点击
        defaultExpandedArr: [],
        relationTypes:[]
      }
    },
    created(){
      this.getTreeList(1)
    },
    methods:{
      getTreeList(id){
        if(id != this.id){
          this.id = id
          this.showSearch = false
        }
        const params = {
          "type": id,
        }
        api.getlistTree(params).then((res) => {
          const { data } = res
          if(data.code == '0') {
            let result = data.data.treeDTO||{}
            this.relationTypes = data.data.types||[]
            const itemStr = JSON.stringify(result)
            let tmp = itemStr.replace(/nextTree/g,'nodeList').replace(/id/g,'conceptId').replace(/name/g,'conceptName')
            let item = JSON.parse(tmp)
            item.level = 0
            item.isExpanded = false
            item.nodeList = this.IteraNodeList(item.nodeList, [], 1)
            let arr = []
            arr[0] = item
            this.list = [...arr]
          } else {
            this.message(data.msg);
          }
          this.saveDisable = false;
        })
      },
      allowDrop(draggingNode, dropNode, type) {
        if(draggingNode.parent.data.conceptName !== dropNode.parent.data.conceptName){
          return false
        }else{
          return type !== 'inner'
        }
      },
      allowDrag(draggingNode) {
        return draggingNode.data.level != 0;//一级不可拖动
      },
      handleNodeClick(data) {
          if(data.nodeList.length > 0) {
            if(!data.isExpanded) {
              this.defaultExpandedArr.push(data.conceptId)
            } else {
              this.defaultExpandedArr = this.defaultExpandedArr.filter(item => item !== data.conceptId)
            }
            this.$set(data, 'isExpanded', !data.isExpanded);
          }
      
      },
      // addConcept(e) {
      //   console.log(e)
      //   this.addLevel = 0;
      //   this.openSearch(e);
      // },
      confirm() { 
        if(!this.list[0] || this.list[0].nodeList.length == 0) {
          this.message('请输入数据信息');
          return
        }
        const param = {
          conceptId: this.list[0].conceptId,
          sonRelationId: 17,
          isOrderBy: 1
        }
        const nodeListResult = []
        this.IteraNodeList(this.list[0].nodeList, nodeListResult, 0)
        param.nodeList = nodeListResult
        this.saveDisable = true  //提交保存按钮不可点击，返回结果时才可点击，防止频繁发送请求
        api.addTreeRelation(this.reparams(param)).then((res) => {
          const { data } = res
          if(data.code == '0') {
            this.message(res.data.msg||'术语关系建立成功','success');
          } else {
            this.message(data.msg);
          }
          this.saveDisable = false;
        })
      },
      IteraNodeList(nodeList,  nodeListResult, type, level = 1) {
        this.level= level + 1
        for(let i = 0; i <nodeList.length; i++) {
          let newChild;
          if(type == '0') { //添加的时候保存所有的id列表
            newChild = {conceptId: nodeList[i].conceptId, relationId: 17,nodeList:[],sonRelationId: 17, isExpanded:false}
          } else if(type == '1') {  //修改的时候添加层级
            const item = JSON.parse(JSON.stringify(nodeList[i]))
            newChild = Object.assign(item, {level:  level, nodeList: [],sonRelationId: 17, isExpanded:false})
          } else if(type == '2') { //移除节点的时候同时移除节点（搜索时排除的id列表）
            newChild = nodeList[i].conceptId
          }
          
          if(nodeList[i].nodeList &&nodeList[i].nodeList.length > 0&&level < 3) {
            if(type == '0' || type =='1') {
              this.IteraNodeList(nodeList[i].nodeList,  newChild.nodeList, type, level+1)
            } else if(type == '2') {
              this.IteraNodeList(nodeList[i].nodeList,  nodeListResult, type, level+1)
            }
            
          }
          nodeListResult.push(newChild)
        }
        return nodeListResult
      },
      searchConcept(txt) {
        let  excludedConceptIds = [];
        if(!txt){
          this.conceptList = []
          return
        }
        if(this.list[0]) {
          excludedConceptIds.push(this.list[0].conceptId)
          this.excludedConceptIds = this.IteraNodeList(this.list[0].nodeList,excludedConceptIds, 2)
        }
        const params = {
          "typeId": this.addLevel === 1 ? this.relationTypes[2] : this.addLevel === 2 ? this.relationTypes[4] : 1,
          "name": txt,
          "excludedConceptIds": this.excludedConceptIds,
          "relationId": this.addLevel === 1 ? this.relationTypes[1] : this.addLevel === 2 ? this.relationTypes[3] : 1,
          "relationConceptId": this.relationConceptId,
        }
        api.getTreeSearchList(params).then((res) => {
          const { data } = res
          if(data.code == '0') {
            this.conceptList = data.data
          }
        })
      },
      selectConcept(item) {
        if(this.addLevel == 0) {
          this.list.push(Object.assign({}, item,  {nodeList: [], level: 0, conceptId: item.conceptId, sonRelationId: 17}))
          this.list = JSON.parse(JSON.stringify(this.list))
        }else { 
          const data = this.operaList
          const newChild = Object.assign({}, item,  {nodeList: [], level: data.level+1, conceptId: item.conceptId, relationId: 17,sonRelationId: 17});
          // const newChild = { id: id++, label: 'nodeList', level: data.level+1, children: [] };
          if (!data.nodeList) {
          this.$set(data, 'nodeList', []);
          }
          data.nodeList.push(newChild);
        }
        this.conceptList = [];
        this.closeSearch();
      },
      openSearch(e) {
        this.showSearch = true
      },
      closeSearch() {
        this.conceptText = ''
        this.conceptList = []
        this.showSearch = false
      },
      append(data, e) {
          this.addLevel = data.level+1;
          this.relationConceptId = data.conceptId
          this.operaList = data;
          this.openSearch(data);

          // const newChild = { id: id++, label: 'testtest', level: data.level+1, nodeList: [] };
          // if (!data.nodeList) {
          // this.$set(data, 'nodeList', []);
          // }
          // data.nodeList.push(newChild);
      },

      remove(node, data) {
          const parent = node.parent;
          const nodeList = parent.data.nodeList || parent.data;
          const index = nodeList.findIndex(d => d.conceptId === data.conceptId);
          nodeList.splice(index, 1);
      },
      reparams(param){
        let params = []
        const tmplis = param.nodeList||[];
        for(let i = 0;i < tmplis.length;i++){
          let item = tmplis[i],sonIds=[]
          if(item.nodeList&&item.nodeList.length>0){
            for(let j = 0;j < item.nodeList.length;j++){
              sonIds.push(item.nodeList[j].conceptId)
            }
          }
          let obj = {
            "eid": item.conceptId,
            "eids": sonIds,
            "rid": this.relationTypes[1],
            "sid": param.conceptId,
            "srid": this.relationTypes[3]
          }
          params.push(obj)
        }
        return params
      },
      message(msg,type){
        this.$message({
          showClose: true,
          message:msg,
          type:type||'warning'
        })
      },
      
    }
}
</script>
<style lang="less" scoped>
@import "../../less/admin.less";
.el-button+.el-button {
  margin-left: 0;
}
.content {
  min-width: auto;
  box-sizing: border-box;
}
.contents {
  box-sizing: border-box;
  box-sizing: border-box;
}

.addMedicalMultRelationWrapper {
  height: calc(100% - 70px);
}
.tree {
  margin-bottom: 230px;
}
.contents {
  height: 100%;
  padding-top: 120px;
}
.btn-box {
  position: absolute;
  left: 350px;
}
.btn-del {
  color: #8F8F8F;
  padding-left: 28px;
}
.addBtn { 
  width: 66px;
  order: 1px solid #21CBC7;
  border-radius: 2px;
}
.conceptSearch {
  position: fixed;
  right: 20px;
  top: 180px;
  bottom: 10px;
  width: 300px;
  background: #fff;
  border: 1px solid #C9C9C9;
  text-align: center;
  z-index: 2;
  padding: 30px;
  box-sizing: border-box;
  .conceptTitle {
    width: 100%;
    text-align: center;
    padding: 20px 0;
  }
  .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;
  }
  .closeSearch {
    position: absolute;
    width: 30px;
    right: 0;
    top: 0;
  }
  .searchWrap {
    position: relative;
    .search {
      position: absolute;
      right: 7px;
      top:8px;
    }
  }
}
.delete {
  cursor: pointer;
}
.content{
  background: #fff;
  padding: 40px 20px 30px;
  color: #545455;
 
}

.btn {
  text-align: right;
  margin-top: 20px;
}
.custom-tree-node-name {
  display: inline-block;
  width: 270px;
}
.colorGray {
  color: #c1c1c1;
} 
</style>