<template>
  <el-dialog 
  :visible.sync="dialogVisible"  
  custom-class="dialogHeight dialogPaddingTop0 rolePermission" 
  :title="isBatch?$t('btns.resources_authorize'):$t('btns.role_authorize')" 
  width="984px">
    <div class="height100" v-loading="loading">
      <div v-if="isBatch">
        <el-row>
          <el-col :span="24">
            <p class="smallHeader rolePerTipP">{{$t('label.role_select')}}<span class="rolePerTip">{{$t('label.select_need_role')}}</span></p>
            <el-select v-model="roleIds" multiple :placeholder="$t('placeholder.select')" class="selectRoles" size="mini">
              <el-option
                v-for="item in rolesList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-col>
          
        </el-row>
        
      </div>
      <el-row :gutter="24"  :class="[isBatch?'mainDetail':' height100']">
        <el-col :span="8" class="height100">
          <el-tabs v-model="activeName" type="border-card"  class="height100 rolePermissionTabs">
            <el-tab-pane :label="$t('label.pcmenu')" name="pc" class="height100">
              <el-button type="text" class="miniFontSize padding0" @click="changePCExpandAll(true)">{{$t('btns.open_all')}}</el-button>
              <el-button type="text" class="miniFontSize padding0" @click="changePCExpandAll(false)">{{$t('btns.close_all')}}</el-button>
              <el-scrollbar style="height:calc(100% - 20px)" :native="false">
                <el-tree
                  ref="pcTree"
                  node-key="id"
                  :props="{
                    label: 'name',
                    children: 'zones',
                    isLeaf: isHasLeaf,
                    disabled:isDis,
                  }"
                  :load="loadNode"
                  :expand-on-click-node="false"
                  lazy
                  show-checkbox
                  :default-checked-keys="defaultChecked"
                  :default-expanded-keys="defaultExpandedKeys"
                  :default-expand-all="pcExpandAll"
                  :check-strictly='true'
                  @check-change="checkAllPcNode"
                ></el-tree>
              </el-scrollbar>
            </el-tab-pane>
            <el-tab-pane :label="$t('label.mobilemenu')" name="mobile" class="height100">
              <el-button type="text" class="miniFontSize padding0" @click="changeMobileExpandAll(true)">{{$t('btns.open_all')}}</el-button>
              <el-button type="text" class="miniFontSize padding0" @click="changeMobileExpandAll(false)">{{$t('btns.close_all')}}</el-button>
              <el-scrollbar style="height:calc(100% - 20px)" :native="false">
                <el-tree
                  ref="mobileTree"
                  node-key="id"
                  :props="{
                    label: 'name',
                    children: 'zones',
                    isLeaf: isHasLeaf,
                    disabled:isDis,
                  }"
                  :load="loadMobileNode"
                  :expand-on-click-node="false"
                  lazy
                  show-checkbox
                  :default-checked-keys="defaultMobileChecked"
                  :default-expanded-keys="defaultMobileExpandedKeys"
                  :default-expand-all="mobileExpandAll"
                  :check-strictly='true'
                  @check-change="checkAllMobileNode"
                ></el-tree>
              </el-scrollbar>
            </el-tab-pane>
            <el-tab-pane :label="$t('label.module_source')" name="module" class="height100">
              <el-button type="text" class="miniFontSize padding0" @click="changeModuleExpandAll(true)">{{$t('btns.open_all')}}</el-button>
              <el-button type="text" class="miniFontSize padding0" @click="changeModuleExpandAll(false)">{{$t('btns.close_all')}}</el-button>
              <el-scrollbar style="height:calc(100% - 20px)" :native="false">
                <el-tree
                  ref="tree"
                  node-key="id"
                  :props="{
                    label: 'name',
                    children: 'zones',
                    isLeaf: isLeaf,
                  }"
                  :load="loadModuleNode"
                  :expand-on-click-node='false'
                  lazy
                  :default-expanded-keys="defaultModuleExpandedKeys"
                  @node-click="moduleTreeClick"
                  :default-expand-all="moduleExpandAll"
                ></el-tree>
              </el-scrollbar>
            </el-tab-pane>
          </el-tabs>
        </el-col>
        <el-col :span="16" class="height100">
          <div v-if="activeName=='module'&& haveData " class="height100 ">
            <el-scrollbar style="height:100%" :native="false">
              <el-form label-position="top" size="mini">
                <el-row>
                  <el-col class="labelMarginBot0">
                    <el-form-item :label="$t('label.form_source')" class="rolePermissionModule">
                      <el-checkbox  v-model="checkFormAll" @change="handleCheckFormAllChange">{{$t('label.select_all')}}</el-checkbox>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row v-for="(elm) in moduleResource.forms" :key="elm.id" class="marginBot5">
                  <el-col>
                    <el-row>
                      {{elm.name}}[{{elm.permissionType=="public"?$t('label.public'):$t('label.private')}}]:
                    </el-row>
                    <el-row>
                      <el-col v-for="(el) in elm.activities" :key="el.id" class="widthAuto">
                        <el-form-item :label="el.name" class="rolePermissionModule ">
                          <el-checkbox v-model="el.checked"  :disabled="elm.permissionType=='public'?true:false"></el-checkbox>
                        </el-form-item>
                      </el-col>
                      
                    </el-row>
                    
                  </el-col>
                </el-row>
                <el-row>
                  <el-col>
                    <el-form-item :label="$t('label.view_source')" class="rolePermissionModule marginTop10">
                      <el-checkbox  v-model="checkViewAll"  @change="handleCheckViewAllChange">{{$t('label.select_all')}}</el-checkbox>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row v-for="(elm) in moduleResource.views" :key="elm.id" class="marginBot5">
                  <el-col>
                    <el-row>
                      {{elm.name}}[{{elm.permissionType=="public"?$t('label.public'):$t('label.private')}}]:
                    </el-row>
                    <el-row>
                      <el-col v-for="(el) in elm.activities" :key="el.id" class="widthAuto" >
                        <el-form-item :label="el.name" class="rolePermissionModule">
                          <el-checkbox v-model="el.checked"  :disabled="elm.permissionType=='public'?true:false"></el-checkbox>
                        </el-form-item>
                      </el-col>
                      
                    </el-row>
                    
                  </el-col>
                </el-row>
                
              </el-form>
            </el-scrollbar>
          </div>
        </el-col>
      </el-row>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-row>
        <el-col :span="24" style="text-align:right">
          <el-button @click="onCancel" size="small" type="primary" plain>{{$t('btns.cancel')}}</el-button>
          <el-button type="primary" @click="onOk" size="small">{{$t('btns.confirm')}}</el-button>
        </el-col>
      </el-row>
    </div>
  </el-dialog>

</template>

<script>
import { getPcResource, getMobileResource, updatePermissions,getModuleResource, getRoles} from "@/service/CommontoolsAPI.js";
import { getModulesTree } from "@/service/CommonApi.js";

export default {
  props: ["visible","applicationId","roleId","isBatch"],
  created() {
    // console.log("application",this.applicationId)
    
    if(this.isBatch){
      this.getRoles()
    }
  },
  data() {
    return {
      loading: false,
      activeName:'pc',
      defaultChecked:[],
      defaultExpandedKeys:[],
      defaultMobileChecked:[],
      defaultMobileExpandedKeys:[],

      defaultModuleExpandedKeys:[],

      moduleResource:[],
      checkFormAll:false,
      checkViewAll:false,
      resources:[],
      views:[],
      forms:[],
      roleIds:[],
      pcExpandAll:false,
      node:null,
      resolve:null,
      first:true,
      mobileExpandAll:false,
      mobilenode:null,
      mobileresolve:null,
      mobilefirst:true,

      moduleExpandAll:false,
      modulenode:null,
      moduleresolve:null,
      modulefirst:true,

      haveData:false,

      pcCanCheck:[], // pc菜单能选择的菜单值
      mobileCanCheck:[],
      haveCheckModule:[],//切换模块资源的时候保存已选中的资源
      params: {
        applicationId: sessionStorage.getItem("appId"),
        isMobile: false,
        parentId: "",
        roleId: ""
      },
      mobileParams: {
        applicationId: sessionStorage.getItem("appId"),
        isMobile: true,
        parentId: "",
        roleId: ""
      },
      rolesList: [], // 角色列表数据
    };
  },
  computed: {
    dialogVisible: {
      get() {
        return this.visible;
      },
      set(val) {
        this.$emit("update:visible", val);
      }
    }
  },
  methods: {
    checkAllPcNode(data,val){
      // if(!val){

      // }
      if(data.id==this.applicationId){
        if(val){
          this.pcCanCheck.forEach(elm=>{
            this.$refs.pcTree.setChecked(elm,true);
          })
        }else{
          this.pcCanCheck.forEach(elm=>{
            this.$refs.pcTree.setChecked(elm,false);
          })
        }
      }
    },
    checkAllMobileNode(data,val){
      
      if(data.id==this.applicationId){
        if(val){
          this.mobileCanCheck.forEach(elm=>{
            this.$refs.mobileTree.setChecked(elm,true);
          })
        }else{
          this.mobileCanCheck.forEach(elm=>{
            this.$refs.mobileTree.setChecked(elm,false);
          })
        }
      }
    },
    changePCExpandAll(val){
      this.pcExpandAll=val;
      this.loadNode(this.node,this.resolve)
    },
    changeMobileExpandAll(val){
      this.mobileExpandAll=val;
      this.loadMobileNode(this.mobilenode,this.mobileresolve)
    },
    changeModuleExpandAll(val){
      this.moduleExpandAll=val;
      this.loadModuleNode(this.modulenode,this.moduleresolve)
    },
    handleCheckFormAllChange(val){
      this.moduleResource.forms.forEach(elm=>{
        if(elm.permissionType=="private"){
          elm.activities.forEach(el=>{
            el.checked=val
          })
        }
      })
      this.checkFormAll=val;
    },
    handleCheckViewAllChange(val){
      this.moduleResource.views.forEach(elm=>{
        if(elm.permissionType=="private"){
          elm.activities.forEach(el=>{
            el.checked=val
          })
        }
      })
      this.checkViewAll=val;
    },
    isDis(data){
      if(data.permissionType=="public"){
        return true;
      }else{
        return false;
      }
    },
    isLeaf(data){
      if(data.hasChild){
        return true;
      }else{
        return false;
      }
    },
    /**
     * 如果有孩子显示右侧的下拉箭头
     */
    isHasLeaf(data){
      if(!data.hasChild){
        return true;
      }else{
        return false;
      }
    },
    onCancel(){
      this.$emit("update:visible", false);
    },
    async onOk(){
      let that=this;
      let data={};
      data.roles=[]
      if(this.isBatch){
        data.roles=this.roleIds;
      }else{
        data.roles.push(this.roleId);
      }
      
      this.pcCanCheck.forEach(elm=>{
        let data={};
        data.id=elm;
        data.checked=that.$refs.pcTree.getNode(elm).checked;
        this.resources.push(data)
      })
      this.mobileCanCheck.forEach(elm=>{
        let data={};
        data.id=elm;
        data.checked=that.$refs.mobileTree.getNode(elm).checked;
        this.resources.push(data)
      })
      
      data.resources=this.resources;
      if(this.moduleResource && this.moduleResource.forms && this.moduleResource.views){
        this.moduleResource.forms.forEach(elm=>{
          that.forms.forEach((elem,ind)=>{
            if(elm.id==elem.id){
              that.forms.splice(ind,1);
            }
          })
          if(elm.permissionType=="private"){
            let change={
              "id": elm.id,
              "activities": []
            };
            elm.activities.forEach(el=>{
              let data={}
              data.id=el.id;
              data.checked=el.checked;
              change.activities.push(data);
            })
            if(change.activities.length>0){
              that.forms.push(change);
            }
            
          }
        })
        this.moduleResource.views.forEach(elm=>{
          that.forms.forEach((elem,ind)=>{
            if(elm.id==elem.id){
              that.views.splice(ind,1);
            }
          })
          if(elm.permissionType=="private"){
            let change={
              "id": elm.id,
              "activities": []
            };
            elm.activities.forEach(el=>{
              let data={}
              data.id=el.id;
              data.checked=el.checked;
              change.activities.push(data);
            })
            if(change.activities.length>0){
              that.views.push(change);
            }
          }
        })
      }
      
      data.views=this.views;
      data.forms=this.forms;
      this.loading = true;
      const resp = await updatePermissions({applicationId:this.applicationId,data:data});
      if(resp.data.errcode==0){
        this.$message.success(resp.data.data);
        this.$emit("update:visible", false);
      }else{
        this.$message.error(resp.data.errmsg)
      }
      this.loading = false;
    },
    async loadNode(node, resolve) {
      let that=this;
      console.log(node);
      if (node.level === 0 ) {
        if(this.first){
          this.first=false;
          this.node=node;
          this.resolve=resolve;
        }
        this.node.childNodes = [];
        this.defaultExpandedKeys=[];
        let root =[{
          checked: true,
          id: this.params.applicationId,
          name: this.$t('label.all_menu'),
          parentId: "",
          permissionType: "private",
        }]
        resolve(root);
        this.defaultExpandedKeys.push(this.params.applicationId)
      }
      if (node.level >= 1 ) {
        this.params.parentId = node.key;
        this.params.roleId = this.roleId

        const resp = await getPcResource(this.params);
        if (resp.data.data) {
          let subdepts = resp.data.data;
          subdepts.forEach(elm=>{
            if(elm.checked == true){
              this.defaultChecked.push(elm.id)
            }
            if(elm.hasChild && that.pcExpandAll){
              this.defaultExpandedKeys.push(elm.id)
            }
            if(elm.permissionType=="private"){
              this.pcCanCheck.push(elm.id);
            }
          })
          resolve(subdepts);
        } else {
          resolve([])
        }
      }
    },
   async loadMobileNode(node, resolve){
      
      let that=this;
      if (node.level === 0 ) {
        if(this.mobilefirst){
          this.mobilefirst=false;
          this.mobilenode=node;
          this.mobileresolve=resolve;
        }
        this.mobilenode.childNodes = [];
        this.defaultMobileExpandedKeys=[];

        let root =[{
          checked: true,
          id: this.params.applicationId,
          name: this.$t('label.all_menu'),
          parentId: "",
          permissionType: "private",
        }]
        resolve(root);
        this.defaultMobileExpandedKeys.push(this.params.applicationId)
      }
      if (node.level >= 1 ) { 
        
        this.mobileParams.parentId = node.key;
        this.mobileParams.roleId = this.roleId;
        const resp = await getMobileResource(this.mobileParams);
         if (resp.data.data) {
               
              let subdepts = resp.data.data;
              subdepts.forEach(elm=>{
                if(elm.checked == true){
                  this.defaultMobileChecked.push(elm.id)
                }
                if(elm.hasChild && that.mobileExpandAll){
                  this.defaultMobileExpandedKeys.push(elm.id)
                }
                if(elm.permissionType=="private"){
                  this.mobileCanCheck.push(elm.id);
                }
              })
              resolve(subdepts);
            } else {
              resolve([])
            }
       
       
      //  getMobileResource(this.mobileParams, {
      //     onSucess: resp => {
      //       if (resp.data.data) {
               
      //         let subdepts = resp.data.data;
      //         subdepts.forEach(elm=>{
      //           if(elm.checked == true){
      //             this.defaultMobileChecked.push(elm.id)
      //           }
      //           if(elm.hasChild && that.mobileExpandAll){
      //             this.defaultMobileExpandedKeys.push(elm.id)
      //           }
      //           if(elm.permissionType=="private"){
      //             this.mobileCanCheck.push(elm.id);
      //           }
      //         })
      //         resolve(subdepts);
      //       } else {
      //       alert("resp.data.data")
      //         resolve([])
      //       }

      //     }
      //   });
        
      }
    },
    async loadModuleNode(node, resolve){
      let that=this;

      if (node.level === 0 ) {
        if(this.modulefirst){
          this.modulefirst=false;
          this.modulenode=node;
          this.moduleresolve=resolve;
        }
        this.modulenode.childNodes = [];
        this.defaultModuleExpandedKeys=[];
        let root =[{
          checked: true,
          id: this.params.applicationId,
          name: this.$t('label.all_module'),
          parentId: "",
          permissionType: "public",
        }]
        
        this.defaultModuleExpandedKeys.push(this.params.applicationId)
        resolve(root);
      }
      if (node.level >= 1) {
        const response = await getModulesTree(this.params.applicationId, node.key);
        if (response.data.errcode == 0) {
          let subdepts = response.data.data;
          subdepts.forEach(elm=>{
            if(!elm.hasChild && that.moduleExpandAll){
              this.defaultModuleExpandedKeys.push(elm.id)
            }
          })
          resolve(subdepts);
        }
        
      }
    },
    //模块资源树节点点击事件
    async moduleTreeClick(data){
      let that=this;
      
      //this.forms维护的是确定的时候要传给后台的数据
      if(this.moduleResource && this.moduleResource.forms && this.moduleResource.views){
        this.moduleResource.forms.forEach(elm=>{
          that.forms.forEach((elem,ind)=>{
            if(elm.id==elem.id){
              that.forms.splice(ind,1);
            }
          })
          if(elm.permissionType=="private"){
            let change={
              "id": elm.id,
              "activities": []
            };
            elm.activities.forEach(el=>{
              let data={}
              data.id=el.id;
              data.checked=el.checked;
              change.activities.push(data);
            })
            if(change.activities.length>0){
              
              that.forms.push(change);
            }
            
          }
        })
        this.moduleResource.views.forEach(elm=>{
          that.views.forEach((elem,ind)=>{
            if(elm.id==elem.id){
              that.views.splice(ind,1);
            }
          })
          if(elm.permissionType=="private"){
            let change={
              "id": elm.id,
              "activities": []
            };
            elm.activities.forEach(el=>{
              let data={}
              data.id=el.id;
              data.checked=el.checked;
              change.activities.push(data);
            })
            if(change.activities.length>0){
              that.views.push(change);
            }
          }
        })
      }

      this.moduleResource=[];
      const resp = await getModuleResource({applicationId:this.params.applicationId,roleId:this.roleId,moduleId:data.id});
      this.moduleResource=resp.data.data;
      if(this.moduleResource.forms||this.moduleResource.views){
        if(this.moduleResource.forms.length>0||this.moduleResource.views.length>0){
          this.haveData=true;
          that.forms.forEach(elm=>{
            for(let i=0;i<that.moduleResource.forms.length;i++){
              if(elm.id==that.moduleResource.forms[i].id){
                elm.activities.forEach(el=>{
                  for(let j=0;j<that.moduleResource.forms[i].activities.length;j++){
                    if(el.id==that.moduleResource.forms[i].activities[j].id){
                      that.moduleResource.forms[i].activities[j].checked=el.checked;
                      break;
                    }
                  }
                })
                break;
              }
            }
          })
          that.views.forEach(elm=>{
            for(let i=0;i<that.moduleResource.views.length;i++){
              if(elm.id==that.moduleResource.views[i].id){
                elm.activities.forEach(el=>{
                  for(let j=0;j<that.moduleResource.views[i].activities.length;j++){
                    if(el.id==that.moduleResource.views[i].activities[j].id){
                      that.moduleResource.views[i].activities[j].checked=el.checked;
                      break;
                    }
                  }
                })
                break;
              }
            }
          })
        }
      }
    },
    /**
     * 获取角色列表
     */
    async getRoles(){
      
      let params = {
        appId: sessionStorage.getItem("appId"),
        name: "",
        pageNo: 1,
        linesPerPage: 100000
      }
      const response = await getRoles(params);
      if (response.data.errcode == 0) {
        this.rolesList = response.data.data.datas
        
      }
    },
  }
};
</script>

<style>
</style>