<template>
  <dropdown :model='model' class="auto" id="res-tree" v-if="!islist" v-el:dropdown :style="{width:width}">
    <button type="button" class="btn btn-default dropdown-toggle select-style" data-toggle="dropdown" style="width: 100%">
      <span class='btn-content' :style="{textOverflow:'ellipsis',overflow: 'hidden'}">{{ orgnames }}</span>
      <span class="caret"></span>
    </button>
    <div  class="dropdown-menu auto" style="width:auto;max-height: 500px;overflow: auto" >
      <input type="text" placeholder="Search"
             placeholder='请输入'
             slot="dropdown-menu"
             v-model="searchText"
             class="form-control" autocomplete="off"
             @keydown.enter="buluer(searchText)">
      <tree :filter="strsign" :model='model' v-ref:tree  :is-click="false"  role="menu">
          <span  partial>
            <span class="glyphicon glyphicon-chevron-down" v-show="row.open&&row.data.children.length>0" style="color:balck;"></span>
            <span class="glyphicon glyphicon-chevron-right" v-show="!row.open&&row.data.children.length>0" style="color:balck;"></span>
            <span class="RightTreeCanSelect" v-if="row.data.hasright" @click.stop="$parent.$parent.$parent.selectclick(row.data)">{{row.data.name}}</span>
            <span class="RightTreeCanNotSelect" v-else>{{row.data.name}}</span>
            <span class="glyphicon glyphicon-ok " v-if="$parent.$parent.$parent.isSelect(row.data.id)" style="color:balck;"></span>
          </span>
      </tree>
    </div>

  </dropdown>
  <v-select v-if="islist"
            placeholder='请选择'
            :options='childrenOptions'
            @change="selectclick"
            :value-single="true"
            close-on-select></v-select>
</template>
<script>
import Vue from 'vue';
import co from 'co'
import { PagedList, HttpResetClass } from 'vue-client'
import * as ldapHelper from '../../utils/LdapHelper'
let saveGen = function * (self) {
  //获取分公司树
  let data = {
    source: self.source,
    userid: self.userid
  }
  // if(self.$treeorg==null || (self.$treeorg!=null&&self.$treeorg.length==0)){
  let http = new HttpResetClass()
  let ret = yield http.load('POST', `${self.Url}/rs/search`, data, {resolveMsg: null, rejectMsg: null})
  // 去掉前面的两层节点
  ret.data[0].children[0].children.forEach((item) => {
    self.model.push(item)
  })
  Vue.$treeorg = Vue.prototype.$treeorg = self.model;
  // }
  //if(self.$treeorg!=null){
  //  self.model = self.$treeorg;
  //}
  // 给资源添加父关系
  ldapHelper.procParent(self.model)
  // 树转列
  // if (self.islist) {
  //   self.treetoList(self.model)
  // }
  if(self.initresid.length>0){
    if(self.initresid[0] == ''){
      self.initresid[0] = self.$login.f.orgid;
    }
  }else{
    self.initresid = [];
    self.initresid[0] = self.$login.f.orgid;
  }
  if(self.initresid&&self.initresid.length>0){
    self.isselect = false;
    self.initTreetoList(self.model)
    self.initregion(self.childrenOptions)
    self.childrenOptions.forEach((item) => {
      if(item.id == null && item.value !=null ){
        item = item.value
      }
      if(item.id==self.initresid[0]){
        //默认加载如果已选中的和传入参数相等会取消选择，这种操作不应该被允许
        if(self.orgids==item.id){
          self.initdataone(item);
          return;
        }
        self.selectclick(item);
        self.isselect = true;
        return;
      }
    })
    //如果没有找到公司，说明是选择的是大区
    if(!self.isselect){
      self.childrenregionOption.forEach((item) => {
        if(item.id == null && item.value !=null ){
          item = item.value;
        }
        if(item.id==self.initresid[0]){
          //默认加载如果已选中的和传入参数相等会取消选择，这种操作不应该被允许
          if(self.orgids==item.id){
            self.initdataone(item);
            return;
          }
          self.selectclick(item);
          return;
        }
      })
    }
  }
  //self.selectRes()
}
export default {
  title: '资源树',
  props: {
    searchText:'',
    strsign:'',
    source: {
      type: String,
      require: true,
      default:`tool.getFullTree(this.getRights().where(row.getType() == $organization$))`
    },
    //资源初始化数据
    initresid: {
      type: Array,
      default() { return [] },
    },
    resid: {
    },
    resobjprop:"",
    islist: {
      type: Boolean,
      default: false
    },
    //是否有查看上级的权限
    Url:{
      type: String,
      default:''
    },
    width:{
      type:String,
      default:'60%'
    }
  },
  data () {
    return {
      resobj:{res:this.$login.f.orgs, resids:this.$login.f.orgid},
      userid: this.$login.f.id,
      resname:[this.$login.f.orgs],
      orgnames : "请选择",
      //单选点击 返回所有子
      orgids : null,
      orgobj:null,
      model: [

      ],
      childrenOptions: [],
      childrenregionOption:[],
      isselect: false
    }
  },
  methods: {
    selectRes () {
      let newobj={
        "res": [this.resname],
        "resids": [this.orgids],
      }
      this.$emit('re-res', newobj)
    },
    //树形结构变成list
    initTreetoList(val) {
      for (let value of val) {
        this.initErgodicList(value)
      }
    },
    //找到跟节点
    initErgodicList (val) {
      if(val.children.length > 0){
        this.childrenOptions.push(val)
        this.treetoList(val.children)
      }else{
        this.childrenOptions.push(val)
      }
    },
    initregion(val){
      if(val ==null ) return;
      val.forEach((item)=>{
        if(item.name != null){
          if(item.name.includes("公司")){
            return;
          }else{
            this.initregion(item.children)
            this.childrenregionOption.push({label:"",value:item})
            //return item;
          }
        }else{
          return;
        }
      })

    },
    async buluer (val) {
      this.strsign=val
      await new Promise(resolve => {
        this.$nextTick(() => {
          resolve()
        })
      })
    },
    //点击资源的方法
    selectclick (row) {
      if(this.orgids==row.id){
        //取消点击
        this.orgnames="请选择"
        this.orgids=null
        this.orgobj=null
        let newobj={
          "res": [],
          "resids": [],
          "orgobj": [],
        }
        this.$emit('re-res', newobj)
      }else{
        //点中点击
        this.orgnames=row.name
        this.orgids=row.id
        this.orgobj=row
        let objs=[]
        let objids=[]
        let objnames=[]
        this.addResChild(row,objs)
        objs.forEach((item) => {
          objids.push(item.id)
          objnames.push(item.name)
        })
        let newobj={
          "res": objnames,
          "resids": objids,
          "orgobj": objs,
        }
        this.$emit('re-res', newobj)
      }
    },
    initdataone(row){
      //点中点击
      this.orgnames=row.name
      this.orgids=row.id
      this.orgobj=row
      let objs=[]
      let objids=[]
      let objnames=[]
      this.addResChild(row,objs)
      objs.forEach((item) => {
        objids.push(item.id)
        objnames.push(item.name)
      })
      let newobj={
        "res": objnames,
        "resids": objids,
        "orgobj": objs,
      }
      this.$emit('re-res', newobj)
    },
    addResChild(val,objs){
      objs.push(val)
      if(val.children && val.children.length>0){
        Object.keys(val.children).forEach((key) => {
          this.addResChild(val.children[key],objs)
        })
      }
      return objs
    },
    //检查是否显示对勾
    isSelect(val) {
      if(this.orgids==val){
        return true
      }else{
        return false
      }
    },
    //树形结构变成list
    treetoList(val) {
      for (let value of val) {
        this.ergodicList(value)
      }
    },
    //找到跟节点
    ergodicList (val) {
      val.children.length > 0 ? this.treetoList(val.children) : this.childrenOptions.push({label: val.name, value: val})
    },
    //处理显示默认值
    dealResObj (val) {
      try{
        var arr=val.res.split(".")
        //截取最后一个分公司名字
        this.resname=arr[arr.length-1].toString()
        this.orgnames=arr[arr.length-1].toString()
        this.resid = val.resids
        this.orgids = val.resids
      }catch (e){
        this.resname='请选择组织'
      }
    },
    judgBoundary(){
      //判断是否超出边界，超出移动
      if(document.documentElement.offsetWidth< this.$els.dropdown.getBoundingClientRect().right){
        this.left = document.documentElement.offsetWidth - this.$els.dropdown.getBoundingClientRect().right - 25
      }
    }
  },
  events: {

  },
  ready () {
    this.dealResObj (this.resobj)
    let gen = saveGen(this)
    return co(gen)
  },
  watch: {
    'resobjprop'(){
      //tag
      this.dealResObj (this.resobjprop)
    }
  }
}
</script>
<style lang="less">
#res-tree {
  .list-group-item {
    background-color: #FFF;
    color: #000;
    padding: 5px 10px;
    border:0px;
    white-space: nowrap;
  }
}
#res-tree .list-group {
  width: auto;
  min-width: 100%;
}
.hide-text-overflow{
  overflow: hidden;
  text-overflow: ellipsis
}
.select-style {
  border: 0px;
  /*border-bottom: 2px solid #C9CCCF;*/
  border: 1px solid #93B2D3;
  border-radius: 0px;
  color: #555;
}
</style>
