<template>
  <modal :show.sync="show"  v-ref:modal large backdrop="false">
    <header slot="modal-header" class="modal-header">
      <p class="bg-info text-center" style="padding: 8px;">数据权限选择</p>
      <div novalidate class="form-inline auto" partial>
        <div class="form-group">
          <input type="text" class="form-control"
                 style="width:150px" v-model="filterstr"
                 placeholder='请输入搜索'>
        </div>
        <div class="form-group">
          <button class="button_search button_spacing" style="width:80px;margin-left:30px;" @click="buluer()" v-el:cx>查询</button>
        </div>
      </div>
    </header>
    <article slot="modal-body" class="modal-body">
      <div class="auto" id="orgPermission" style="font-size: large;height:450px;overflow:auto;">
        <tree :filter="strsign" :model="model" :is-open="true" v-ref:tree id='defaultTreeOpen'>
      <span partial>{{row.data.name}}
        <input  :id="'org' + row.id"
                type="checkbox" v-model="$parent.$parent.$parent.ids"
                :value="row.id" @click="$parent.$parent.$parent.modifyMark($index, $event, row)"
                style="zoom: 150%">
      </span>
        </tree>
      </div>
    </article>
    <footer slot="modal-footer" class="modal-footer">
      <button class="button_search button_spacing" @click="confirm">确认</button>
      <button class="button_clear button_spacing" @click="cancel">取消</button>
    </footer>
  </modal>
</template>

<script>

  import {HttpResetClass} from 'vue-client'

  let getRightData = async function (self) {
    // 将原有的树进行初始化操作
    let http = new HttpResetClass()
    let res = await http.load('POST', 'rs/license/getData', {parentid:self.data.id, type: 'org'},{resolveMsg: null, rejectMsg: null})
    console.log('获取数据权限', res.data)
    if (res.data) {
      res.data.forEach((item) => {
        self.$refs.tree.toNode.forEach((node) => {
          if (item.byresourceid == node.id && node.children.length == 0) {
            self.dealChildren(node, 'add')
            self.dealParent(node, 'add')
          }
        })
      })
    }
  }

  let getFunctions = async function (self) {
    let http = new HttpResetClass()
    let data = {
      source: 'tool.getFullTree(this.getRights().where(row.getType() == $department$))',
      userid: self.$login.f.id
    }
    if(self.filterstr.length>0){
      data.source='tool.getFullTree(this.getRights().where(row.getType() == $department$).where(row.getPath().indexOf($'+self.filterstr+'$) != -1))'
    }
    let ret = await http.load('POST', '/rs/search',data, {resolveMsg:null, rejectMsg: '获取功能树出错！！请联系管理员！！'})
    if (ret.data[0].children.length > 0 ) {
      self.model = ret.data[0].children[0].children
    } else {
      self.$showAlert('暂无数据', 'warning', 2000)
    }
  }

  export default {
    title: '角色权限',
    data () {
      return {
        filterstr:'',
        strsign:'',
        model: [],
        isTree: true  // 验证修改时树组件需要重新渲染
      }
    },
    props: {
      data: {
        type: Object
      },
      //当前人对象
      user: {
        type: Object
      },
      type: {
        type: String,
        default: 'function'
      },
      show: {
        type: Boolean,
        default: false
      },
      ids: {
        type: Array,
        default: []
      },
      orgs: {
        type: Array,
        default: []
      }
    },
    ready () {
      this.initData()
      this.filterstr=''
    },
    watch: {
      'data' () {
        this.initData()
      },
      user: {
        handler(n, o) {
          if(this.user&&this.user.parentid){
            this.$refs.tree.toNode.forEach((node) => {
              if (this.user.parentid == node.id ) {
                console.log('noed...',node)
                this.ids=[]
                this.orgs=[]
                this.dealChildren(node, 'add')
                this.dealParent(node, 'add')
              }
            })
          }
        },
        deep: true //对象内部属性的监听，关键。
      },
    },
    methods: {
      async buluer () {
        this.strsign=this.filterstr
        await new Promise(resolve => {
          this.$nextTick(() => {
            resolve()
          })
        })
        if(this.filterstr.length==0){
          await this.$refs.tree.openAll()
        }
      },
      confirm () {
        this.show = false
      },
      cancel () {
        this.show = false
      },
      async initData (flag) {
        // 获取功能树
        if (this.model.length == 0||flag) {
          await getFunctions(this)
        }
        // 获取具有的权限
        await this.initTree()
        if(flag){
          await this.$refs.tree.openAll()
        }
        if (this.data && this.data.id) {
          await getRightData(this)
        }
        if(this.user&&this.user.parentid){
          this.$refs.tree.toNode.forEach((node) => {
            console.log('noed遍历...',node)
            if (this.user.parentid == node.id ) {
              console.log('noed...',node)
              this.dealChildren(node, 'add')
              this.dealParent(node, 'add')
            }
          })
        }
      },

      async initTree() {
        // 将选中的节点取消掉
        this.ids = []
        this.orgs = []
        this.$refs.tree.toNode.forEach((node) => {
          this.dealChildren(node, 'del')
          this.dealParent(node, 'del')
        })
      },

      modifyMark (index, event, row) {
        if (event.target.checked) {
          // 选中
          // 处理子和父的数据
          this.dealChildren(row, 'add')
          this.dealParent(row, 'add')
        } else {
          // 取消
          this.dealChildren(row, 'del')
          this.dealParent(row, 'del')
        }
      },
      dealChildren(row, type) {
        // 如果有子全部全选
        if (type === 'add') {
          if (!this.ids.includes(row.id)) {
            this.ids.push(row.id)
          }
        } else {
          if (this.ids.includes(row.id)) {
            this.ids.$remove(row.id)
          }
        }
        // 向下修改
        if (row.children && row.children.length > 0) {
          row.children.forEach((obj) => {
            this.dealChildren(obj, type)
          })
        }
        if (type === 'add') {
          this.orgs.push(row)
        } else {
          this.removeOrg(row)
        }
        // type === 'add' ? this.orgs.push({id: row.id}) : this.orgs.$remove(row)
      },
      async dealParent (row, type) {
        if (row.parent) {
          let selectedChild = []
          if (type === 'add') {
            // 判断它的子是否全选
            row.parent.children.forEach((item) => {
              if (this.ids.includes(item.id) && document.getElementById('org' + item.id).indeterminate == false) {
                selectedChild.push(item.id)
              }
            })
            if (selectedChild.length === row.parent.children.length) {
              // 全选了
              let val = this.orgs.filter((res) => {
                return res.id == row.parent.id
              })
              let http = new HttpResetClass()
              let getLen = await http.load('POST','rs/logic/ldap_getAllChildrenByNode', {id: row.parent.id}, {resolveMsg: null, rejectMsg: null})

              if (val.length == 0) {
                row.parent.byisinherit = selectedChild.length === getLen.data ? '是' : '否'
                this.orgs.push(row.parent)
              } else {
                // this.orgs.$remove(row.parent)
                this.removeOrg(row.parent)
                row.parent.byisinherit = selectedChild.length === getLen.data ? '是' : '否'
                this.orgs.push(row.parent)
              }
              if (document.getElementById('org' + row.parent.id)) {
                document.getElementById('org' + row.parent.id).indeterminate = false
              }
            } else {
              // 没有全选
              // 将当前所在组织 byisinherit 设为 否
              // 判断orgs中是否有row.parent
              let val = this.orgs.filter((res) => {
                return res.id == row.parent.id
              })

              if (val.length == 0) {
                row.parent.byisinherit = '否'
                this.orgs.push(row.parent)
              }

              if (document.getElementById('org' + row.parent.id)) {
                document.getElementById('org' + row.parent.id).indeterminate = true
              }
            }
            if (!this.ids.includes(row.parent.id)) {
              this.ids.push(row.parent.id)
            }
          } else {
            // 判断它的子是否全被取消
            row.parent.children.forEach((item) => {
              if (this.ids.includes(item.id)) {
                selectedChild.push(item.id)
              }
            })
            if (selectedChild.length == 0) {
              // 全部取消
              this.ids.$remove(row.parent.id)
              // this.orgs.$remove(row.parent)
              this.removeOrg(row.parent)
              if (document.getElementById('org' + row.parent.id)) {
                document.getElementById('org' + row.parent.id).indeterminate = false
              }
            } else {
              // 将此父节点设置为byisinherit = '否'
              let val = this.orgs.filter((res) => {
                return res.id == row.parent.id
              })

              if (val.length == 0) {
                row.parent.byisinherit = '否'
                this.orgs.push(row.parent)
              } else {
                // this.orgs.$remove(row.parent)
                this.removeOrg(row.parent)
                row.parent.byisinherit = '否'
                this.orgs.push(row.parent)
              }

              if (document.getElementById('org' + row.parent.id)) {
                document.getElementById('org' + row.parent.id).indeterminate = true
              }
            }
          }
          this.dealParent(row.parent, type)
        }
      },
      removeOrg(row) {
        this.orgs = this.orgs.filter((res) => {
          return res.id !== row.id
        })
      }
    }
  }
</script>
<style>

  #orgPermission div{
    margin-left: 0px;
    margin-bottom: 0px;
    color: #000;
  }
  #orgPermission span {
    color: #000;
  }
  #orgPermission .list-group-item {
    background-color: #fff;
    border: none;
  }
  #orgPermission .list-group-item.active,
  #orgPermission  .list-group-item.active:hover,
  #orgPermission  .list-group-item.active:focus {
    background-color: #fff;
  }

</style>
