<template>
  <div>
    <div style="margin:2px 2px 5px 2px;display: flex;justify-content:space-between;">
      <div>
        <el-input  placeholder="输入关键字进行过滤" v-model="filterText" size="small" />
      </div>
      <div v-show="isRole && checkPagePriv(pagePriv.privs,'提交')">
        <el-button @click="btnSubmit" size="small">提交</el-button>
      </div>
    </div>
    <div style="overflow: scroll;height:450px;">
      <el-tree :data="menuInfoView" :props="customerOrg.treeprops" 
        node-key="id" :filter-node-method="filterNode" show-checkbox
        default-expand-all 
        :default-expanded-keys="customerOrg.defaultExpandedKeys"         
        @check-change="handleCheckChange" highlight-current ref="customerOrgTree"/>
    </div>
  </div>
</template>
<script>
import { mapState, mapMutations } from "vuex";
import { getapi, postapi, putapi, deletapi } from "@/api/api";
import { getPagePriv,checkPagePriv, deepCopy,tcdate,arrayExistObj } from "../../utlis/proFunc";
import { getTreeNode, getTreeAllChildIdsByNode, getTreeAllChildIdsById, getTreePids } from "../../utlis/tree";


export default {
  components: {},
  props:["params"], // params = { opra: role/user 用户/角色, idVal: roleId/userId}
  data() {
    return {
      pagePriv:{
        routeUrlorPageName:'MenuInfoSet', //当前页面归属路由或归属页面权限名称
        privs:[] // 页面权限
      },   
      menuInfoView:[], //显示菜单
      menuInfoSet:[],  //设置菜单
      checkedKeys:[],  //勾选的菜单节点ID
      filterText:''
    };
  },
 
  computed: {
    ...mapState(["window", "dialogWin", "dataTransOpts", "customerOrg" ]),

    // 是否角色
    isRole(){      
      let ret = true
      if(this.params && this.params.opra == "user"){
        ret = false
      }
      return ret      
    },

  },

  //创建组件后
  created() { 
    //获取用户当前页面的权限
    let userPriv = window.sessionStorage.getItem('userPriv')
    if(userPriv) this.pagePriv.privs = deepCopy(getPagePriv(this.pagePriv.routeUrlorPageName))   
  },

  //挂载组件完成
  mounted() {
    
  },

  methods: {
    ...mapMutations(["setData"]),checkPagePriv,

    // 初始化数据，获取菜单列表树信息 及角色的授权菜单
    initData(roleOrUser_Id) {        
      getapi("/api/app/menuinfo/getmenuinfotreelist").then((res) => {
        if(res.code != -1){
          this.menuInfoView = res.data             
          tcdate(this.menuInfoView);
          // 如果不是角色，则不允许编辑权限
          if(!this.isRole){
            this.setTreeDisabled(this.menuInfoView,"treeChildren")
          }
          if(this.isRole){
            return getapi(`/api/app/rolemenuinfo/getrolemenuinfolist?RoleId=${roleOrUser_Id}`) //
          }else{
            return getapi(`/api/app/menuinfo/getmymenuinfolistinuser?UserId=${roleOrUser_Id}`)           
          }
        }
      }).then(res =>{
        if(res && res.code != -1){
          // 勾选赋值
          this.menuInfoSet = res.data
          this.setCheckedKeys()
        }
      }).catch(err =>{
        console.log(err)
      });
    },

    // 用户只允查看权限，暂不允许修权限
    setTreeDisabled(tree,childrenNodeName){
      tree.forEach(e => {
        e.disabled = true
        if(e[childrenNodeName]) this.setTreeDisabled(e[childrenNodeName],childrenNodeName)
      });
    },

    // 初始设置菜单勾选
    setCheckedKeys(){  
      this.checkedKeys = [] 
      if(!this.isRole){
        this.menuInfoSet.forEach(e => {
          e.menuInfoId = e.id
        });
      }
      this.menuInfoSet.forEach(e => {
        // 无下级节点时，勾选；有下级节点时，所有下级节点全部勾选时，才勾选
        let node = getTreeNode(this.menuInfoView, "treeChildren", "id", e.menuInfoId)
        if(node.treeChildren){
          //获取所有下级节点值
          let menuInfoIds = getTreeAllChildIdsByNode(node, "treeChildren", "id")
          let count = 0
          menuInfoIds.forEach(item => {
            let lfind = arrayExistObj(this.menuInfoSet,"menuInfoId",item)
            if(lfind > -1) count++
          });
          if(menuInfoIds.length == count) this.checkedKeys.push(e.menuInfoId)
        }else{
          this.checkedKeys.push(e.menuInfoId)
        }
      });      
      this.$refs["customerOrgTree"].setCheckedKeys(this.checkedKeys);
    },

    //提交按钮（保存角色权限）
    btnSubmit(){
      let body = {
        roleId:this.dataTransOpts.tableS.adp_roles.id,
        menuInfoIds:[]
      }

      this.menuInfoSet.forEach(e => {
        if(e.menuInfoId) body.menuInfoIds.push(e.menuInfoId)
      });
   

      postapi('/api/app/rolemenuinfo/setrolemenuinfo',body).then(res =>{
        if(res.code != -1){
          console.log('操作成功！')
          this.dialogWin.MenuPageSet = false 
        }
      })
    },

    //勾选节点
    handleCheckChange(data, checked, indeterminate) {
      console.log('data, checked, indeterminate,this.menuInfoSet',data, checked, indeterminate,this.menuInfoSet);
      let lfind = 0,count = 0
      if(checked){   
        // 获取所有上级节点
        let pids = getTreePids(this.menuInfoView, "treeChildren", "parentId", "id", data.id)
        pids.push(data.id) //添加自身节点
        pids.forEach(e => {
          if(e){
            lfind = arrayExistObj(this.menuInfoSet,'menuInfoId',e)
            if(lfind == -1) this.menuInfoSet.push({ menuInfoId:e })
          }
        }); 
      }else if(!indeterminate){
        // 取消授权时        
        lfind = arrayExistObj(this.menuInfoSet,'menuInfoId',data.id)
        if(lfind > -1) this.menuInfoSet.splice(lfind,1)
        // 如果有下级节点，则取消所有下级节点的授权      
        // let node = getTreeNode(this.menuInfoView, "treeChildren", "id", data.id)
        // if(node.treeChildren){       
        //   let childs = getTreeAllChildIdsByNode(node, "treeChildren", "id")    
        //   childs.forEach(id => {
        //     lfind = arrayExistObj(this.menuInfoSet,'menuInfoId',id)
        //     if(lfind > -1) this.menuInfoSet.splice(lfind,1)
        //   });
        // }

        // 所有平级节点都被取消时，上级节点也应取消
        let parentIds = getTreePids(this.menuInfoView, "treeChildren", "parentId", "id", data.id)
        parentIds.forEach(e => {
          if(e){
            let pNode = getTreeNode(this.menuInfoView, "treeChildren", "id", e)
            count = pNode["treeChildren"].length
            pNode["treeChildren"].forEach(item => {
              lfind = arrayExistObj(this.menuInfoSet,'menuInfoId',item.id)
              if(lfind == -1) count--
            });
            if(count == 0){
              lfind = arrayExistObj(this.menuInfoSet,'menuInfoId',e)
              if(lfind > -1) this.menuInfoSet.splice(lfind,1)
            }
          }
        }); 
      }
      console.log('this.menuInfoSet',this.menuInfoSet)
    },

    //树过滤
    filterNode(value, data) {
      //console.log(value,data)
      if (!value) return true;
      return data['displayName'].indexOf(value) !== -1 || data['simpleCode'].indexOf(value.toUpperCase()) !== -1;
    }
  },

  watch: {
    // 刷新菜单
    "dataTransOpts.refresh.role_menu_info.M":{
      immediate:true,
      handler(newVal, oldVal) {        
        let roleOrUser_Id
        if(this.isRole){
          roleOrUser_Id = this.dataTransOpts.tableS.adp_roles.id
        }else{
          roleOrUser_Id = this.dataTransOpts.tableS.adp_users.id
        }
        console.log(`watch ${this.isRole ? '角色':'用户'} 权限 newVal:${newVal} oldVal:${oldVal} registerCheckId: ${roleOrUser_Id}`); 

        this.initData(roleOrUser_Id)
      }
    },

    "customerOrg.treeCurrentNodekey"(newVal,oldVal){
      //console.log('watch:customerOrg.treeCurrentNodekey',newVal,oldVal)
      if(newVal && newVal != oldVal){
        this.$nextTick(() => {
          this.$refs['customerOrgTree'].setCurrentKey(newVal);
        })
      }
    }, 

    "filterText"(newVal,oldVal){ //过滤菜单
      this.$refs['customerOrgTree'].filter(newVal);
    }
  },
 
};
</script>
<style scoped>
@import "../../assets/css/global.css";
@import "../../assets/css/global_table.css";

</style>
