<template>
  <div>
    <div style="height: 25px;padding-top:30px;padding-bottom: 37px;padding-left: 10px" v-show="ztreeNameShow || isShowDep">
      <div style="float: left;font-size:14px;font-weight:bold;" v-show="ztreeNameShow">{{ztreeName}}</div>
      <div style="float: right;font-size: 15px;margin-right: 4px">
        <Checkbox  v-model="checkDep" v-show="isShowDep" @on-change="treeChange">显示机构</Checkbox>
      </div>
    </div>
    <Row :gutter="2">
      <Divider style="margin-top: 2px;margin-bottom: 8px"/>
      <i-col v-if="sequence" :span="leftCol">
        <Select v-model="treeParams.sequence" placeholder="请选择序列" clearable >
          <Option v-for="item in sequenceList" @click.native="loadData(item.value)" :value="item.value" :key="item.value">{{ item.label }}</Option>
        </Select>
      </i-col>
      <i-col :span="rightCol">
      <Input search class="ztree-searchbt"  placeholder="请输入关键字搜索..." :id="searchId" :name="searchId" enter-button></Input>
      </i-col>
    </Row>
    <div :style="{overflowY:'auto',overflowX:'hidden',height:height+ 'px'}">
      <ul :id="treeId" class="ztree"></ul>
    </div>
  </div>
</template>

<script>
  let _this;
  import {getAllTree, getCompanyTree,getTreeData,getSequenceTree} from './tree'
  import 'ztree/js/jquery.ztree.exhide'
  import {fuzzySearch} from '../bc-ztree/ztreeSearch.js'
  export default {
    name: 'bcTree',
    props: {
      treeId:{ type: String, default: 'bc-tree' },
      searchId:{ type: String, default: 'keyword' },
      height:{ type: Number, default: 600 },
      reload:{ type: Boolean, default: false },//重新加载
      showLine:{ type: Boolean, default: false }, //设置 zTree 是否显示节点之间的连线。
      showIcon:{ type: Boolean, default: false }, //设置 zTree 是否显示节点的图标。
      icon:{ type: String, default: '' }, //设置 zTree 是否显示节点的图标。
      selectedMulti:{ type: Boolean, default: false }, //设置是否允许同时选中多个节点。
      dblClickExpand:{ type: Boolean, default: true }, //双击节点时，是否自动展开父节点的标识.
      checkEnable:{ type: Boolean, default: false }, //设置 zTree 的节点上是否显示 checkbox / radio
      chkboxType: Object, //勾选 checkbox 对于父子节点的关联关系。[setting.check.enable = true 且 setting.check.chkStyle = "checkbox" 时生效]
      treeType:{ type: String, default: 'common' }, //树类型，区域(area)/单位(company)/通用(common)
      sequence:{ type: Boolean, default: false },
      url:{ type: String, default: '' }, //
      params: {type:Object,default:function() {return null}},
      setting: {type:Object,default:function() {return null}},
      selectedId:{type:String,default:''},//默认选中的节点id,如果传入first,那就是默认选中第一个
      selectedType:{type:Array,default:() => {return []}},//可以选择的节点类型,是数组,允许配置多种类型 属性 type 一般是company dep person
      reSelect: { type: Boolean, default: false },//是否重新去选中默认节点
      showDep:{type: Boolean, default: false},//是否显示机构复选框
      ztreeName:{type: String, default: '组织机构树'},
      ztreeNameShow:{type: Boolean, default: false}//是否展示树文字说明
    },
    data(){
      return{
        chkbType:{ "Y": "ps", "N": "ps" },
        loadTreeData:getTreeData,
        treeUrl:'',
        checkDep:false,
        sequenceValue:'',
        isShowDep:false,
        leftCol:10,
        rightCol:14,
        treeParams:{},
        depIdList:[],
        areaUrl: 'cas/api/v1/basedata/area/tree/byIds',
        areaParams:{
          areaIds : '0',
          isFull:true,
        },
        companyUrl: 'cas/api/v1/base/company/tree/0/1',
        companyParams:{
          areaId : ''
        },
        defSetting: {//ztree树初始化设置
          view: {
            showLine: this.showLine,
            showIcon: this.showIcon,
            selectedMulti: this.selectedMulti,
            dblClickExpand: this.dblClickExpand,
            showTitle:true
          },
          data: {
            simpleData: {
              enable: true,
              idKey: "id",
              pIdKey: "pId",
              rootPId: null
            }
          },
          callback: {
            onClick: this.clickNode,
            onCheck: this.checkNode,
            onExpand: this.expandNode,
          },
          check:{
            enable: this.checkEnable,
            chkboxType: this.chkbType,
          }
        },
        sequenceList:[
          {value:'0', label:"全部序列"},
          {value:'1', label:"党群序列"},
          {value:'2', label:"政府序列"},
          {value:'3', label:"政法序列"},
          {value:'4', label:"工交序列"},
          {value:'5', label:"农水序列"},
          {value:'6', label:"文教序列"},
          {value:'7', label:"乡镇序列"},
          {value:'8', label:"其他序列"},
        ],
      }
    },methods: {
      clickNode(event, treeId, treeNode){
        if(treeNode.id){
          this.depIdList.push(treeNode.id);
        }
        this.setDepId(treeNode);
        treeNode.depId__in = this.depIdList.join('|');
        this.$emit('onClick',event, treeId, treeNode);
        this.depIdList=[];
      },
      setDepId(data){
        //点击父节点递归查询该节点下所有子节点
        if(data.children){
          for(let children of data.children){
            this.depIdList.push(children.id);
            this.setDepId(children);
          }
        }
      },
      checkNode(event, treeId, treeNode){
        this.$emit('onCheck',event, treeId, treeNode);
      },
      expandNode(event, treeId, treeNode){
        this.$emit('onExpand',event, treeId, treeNode);
      },
      loadData(value) {
        if(this.params){
          this.treeParams=this.params
        }
        if(value){
          this.treeParams.sequence = value;
        }
        this.loadTreeData(this.treeUrl, this.treeParams).then(res => {
          //循环将name备份到ename属性中,避免受到模糊搜索的影响
          res.result.forEach((n, index) => {
            n.ename = n.name;
            //n.iconSkin = 'pnode';
            if(this.icon){
              n.icon = this.icon;
            }
            if (index === 0) {
              n.open = true;
            }
          });
          if(this.setting){
            this.defSetting = this.setting
          }
          this.$emit('update:reload', false);
          $.fn.zTree.init($("#"+this.treeId), this.defSetting, res.result);
          fuzzySearch(this.treeId, this.searchId, null, false);//搜索功能
          //如果有默认选中的需要,就进行选中
          this.doSelectOne()
        })
      },
      doSelectOne(){
        var treeObj = $.fn.zTree.getZTreeObj(this.treeId);
        if (treeObj) {
          if(this.selectedId && this.selectedId!='first'){
            var node = treeObj.getNodeByParam("id",this.selectedId,null);
            if(node!=null){
              treeObj.selectNode(node,true);
              this.clickNode(null,this.treeId,node);
            }
          }else if (this.selectedId && this.selectedId=='first'){
            let node = this.getRightNode(treeObj.getNodes())
            if(node!=null){
              treeObj.selectNode(node,true);
              this.clickNode(null,this.treeId,node);
            }
          }
        }
        this.$emit('update:reSelect', false);
      },
      getRightNode(nodes){//循环找出第一个对的节点
        if (!this.selectedType || this.selectedType.length===0){
          return nodes[0]
        }
        for (let i = 0; i < nodes.length; i++) {
          let n = nodes[i]
          if(this.selectedType.indexOf(n.type)>=0){
            return n
          }else if (n.children && n.children.length>0){
            return this.getRightNode(n.children)
          }
        }
        return null
      },
      treeChange(e) {
        if (e) {
          this.params.isDepart = '1'
        } else {
          this.params.isDepart = '0'
        }
        this.loadData();
      },
    },mounted: function(){
      _this = this;
      if(this.chkboxType){
        this.chkbType = this.chkboxType;
        this.defSetting.check.chkboxType=this.chkboxType;
      }
      this.treeUrl = this.url;
      if(this.params!=null){
        this.treeParams = this.params;
      }
      if(this.treeType == 'area'){
        if(this.url ==''){
          this.treeUrl = this.areaUrl;
        }
        if(this.params==null){
          this.treeParams = this.areaParams;
        }
        this.loadTreeData = getAllTree;
      }else if(this.treeType == 'company'){
        if(this.url ==''){
          this.treeUrl = this.companyUrl;
        }
        if(this.params==null){
          this.treeParams = this.companyParams;
        }
        /*if(this.sequence){
          this.leftCol = 10;
          this.rightCol = 14;
          this.loadTreeData = getSequenceTree;
        }else{
          this.loadTreeData = getCompanyTree;
          this.rightCol = 24;
        }*/
      }
      if(this.sequence){
        this.leftCol = 10;
        this.rightCol = 14;
      }else{
        this.rightCol = 24;
      }
      this.treeParams.sequence = '0';
      this.isShowDep = this.showDep;
      if(this.isShowDep){
        this.checkDep = true;
        this.params.isDepart = '1'
      }
      this.loadData();
    },watch:{
      reload: {
        immediate: true,
        handler: function () {
          if(this.reload){
            this.loadData();
          }
        }
      },
      reSelect: {
        immediate: true,
        handler: function () {
          if (this.reSelect){
            this.doSelectOne();
          }
        }
      },
    }
  }
</script>

<style>
  /*.ztree li span.button.pnode_ico_open{
    margin-right:2px;background: url(./zTreeStandard.png) ;background-position:-125px -159px;vertical-align:top;*vertical-align:middle;
  }
  .ztree li span.button.pnode_ico_close{
    margin-right:2px;background: url(./zTreeStandard.png) ;background-position:-125px -175px;vertical-align:top;*vertical-align:middle;
  }
  .ztree li span.button.cnode_ico_open{

  }
  .ztree li span.button.cnode_ico_close{

  }*/
</style>
