<template>
  <div>
      <!-- 表头 -->
      <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
          <el-form :inline="true" style="width: 87%">
              <el-form-item label="角色权限">
              </el-form-item>
              <el-form-item >
                  <div>
                  <el-input style="float:left;" v-model="keyword" class="input-with-select" placeholder="请输入关键字查询" clearable="true">
                      <el-button slot="append"  @click="mohu" @clear="mohus" icon="el-icon-search"></el-button>
                  </el-input>
                  </div>
              </el-form-item>
              <el-form-item style="float: right">
                  <el-link type="primary" :underline="false" @click="handleAdd('添加角色', '立即添加')">添加角色</el-link>
                  <el-link type="primary" :underline="false" @click="modify()" style="margin-left: 20px;">修改默认角色</el-link>
                  <!-- <el-link type="primary" :underline="false" @click="exportAuthority()" style="margin-left:20px">导出所有权限</el-link> -->
              </el-form-item>
          </el-form>
      </el-col>
      <!-- 表格 -->
      <el-table :data="tableData" style="width: 100%" height="615">
        <el-table-column prop="rolename" label="角色" align="center">
            <template slot-scope="scope">
              {{scope.row.rolename}} <span v-if="scope.row.isDefault == 1" style="color: #909399;"> - (默认角色)</span>
            </template>
        </el-table-column>
        <el-table-column prop="roleDescribe" label="描述"></el-table-column>
        <el-table-column prop="date" label="操作">
            <template slot-scope="scope">
                <div>
                    <el-button size="small" @click="handleAdd('编辑角色', '立即修改', scope.row)" :style="scope.row.rolename != '超级管理员' ? '' : 'visibility:hidden;'">编辑角色</el-button>
                    <el-button type="primary" size="small" @click="shisha(scope.row.id), roleName = scope.row.rolename" v-if="scope.row.rolename !='超级管理员' || (scope.row.rolename =='超级管理员' && user.roleName == '超级管理员')">分配权限</el-button>
                    <el-button size="small" @click="exportAuthority(scope.row)" >导出权限</el-button>
                    <el-button type="danger" size="small" @click="deteHand(scope.row)" v-if="scope.row.rolename != '超级管理员'">删除</el-button>
                </div>
            </template>
        </el-table-column>
      </el-table>
      <!--工具条-->
        <!-- <el-col :span="24" class="toolbar">
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :page-sizes="[20 , 50 , 80 , 100]"
                :page-size="20"
                layout="total, sizes, prev, pager, next"
                :total="total"
                style="float:right;"
            ></el-pagination>
        </el-col> -->
        <!-- 分配权限弹窗 -->
        <el-dialog :title="'分配权限 - '+roleName" :visible.sync="dialogVisible" width="764px" :before-close="handleClose">
            <div class="quanxians">
                <!-- <el-input placeholder="输入关键字进行过滤" v-model="filterText"></el-input> -->
                <!-- <el-tree :data="data" show-checkbox node-key="id" :filter-node-method="filterNode" ref="tree" :default-expanded-keys="[2, 3]" :default-checked-keys="[5]" :props="defaultProps"> </el-tree> -->
                <el-form ref="form" :model="form" label-width="0px">
                <!-- 分模块展示功能项 -->
                <el-form-item>
                  <ul>
                    <!-- <li v-for="mainMenu in moduleList" :key="mainMenu.id" style="display: flex;"> -->
                    <li v-for="mainMenu in moduleList" :key="mainMenu.id">
                      <!-- <div style="width: 20px; display: inline-block;height: 10px"> -->
                      <div style="display: inline-block; float: left;width: 20px;height: 10px">
                        <span v-if="mainMenu.children.length > 0" @click="dianji(mainMenu)" style="cursor:pointer;"><i :class="mainMenu.useState ? 'el-icon-caret-bottom' : 'el-icon-caret-right'"></i></span>
                      </div>
                      <span style="display: flex;">
                        <el-checkbox :label="mainMenu.name" name="type" v-model="mainMenu.checked" style="font-weight:bold;width: 160px" @change="mainChange(mainMenu)"></el-checkbox>
                        <span v-if="mainMenu.functionList && mainMenu.functionList.length > 0" style="margin-right:10px;margin-left:10px;">
                          <!-- <div></div>(功能:  <el-checkbox v-for="fun in mainMenu.functionList" :key="fun.id" :label="fun.name" name="type" v-model="fun.checked" @change="subChanges(fun, mainMenu.id)"></el-checkbox>) -->
                          <span class="gongn"><el-checkbox v-for="fun in mainMenu.functionList" :key="fun.id" :label="fun.name" name="type" v-model="fun.checked" style="width: 130px" @change="subChanges(fun, mainMenu.id)"></el-checkbox></span>
                        </span>
                      </span>
                      <ul v-if="mainMenu.children && mainMenu.useState">
                        <li v-for="subMenu in mainMenu.children" :key="subMenu.id">
                        <el-checkbox :label="subMenu.name" name="type" v-model="subMenu.checked" style="font-weight:bold;" @change="subChange(subMenu)"></el-checkbox>
                            <span v-if="subMenu.functionList && subMenu.functionList.length > 0" style="margin-right:10px;margin-left:10px;">(功能:  
                              <el-checkbox v-for="fun in subMenu.functionList" :key="fun.id" :label="fun.name" name="type" v-model="fun.checked" @change="funChange(fun)"></el-checkbox>)</span>
                        </li>
                      </ul>
                    </li>
                  </ul>
                </el-form-item>
                </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
              <el-button type="primary" @click="saveList()">保存</el-button>
            </span>
        </el-dialog>
        <!-- 添加角色弹窗 -->
        <el-dialog :title="titles" :visible.sync="addDialogVisible" width="600px" :before-close="handleClose">
            <div>
                <el-form ref="form" :rules="rules" :model="form" label-width="80px">
                    <el-form-item label="角色名称" prop="rolename">
                        <el-input v-model="form.rolename" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="描述">
                        <el-input type="textarea" v-model="form.roleDescribe" maxlength="25" show-word-limit clearable></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button style="float: right" type="primary" @click="onSubmit('form')">确定</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </el-dialog>
        <!-- 修改默认角色弹窗 -->
        <el-dialog title="默认角色" :visible.sync="defaultRole" width="400px" :before-close="handleClose">
            <div>
              <el-form label-width="80px">
                <el-form-item label="默认角色">
                  <el-select v-model="roleId" placeholder="请选择默认角色">
                      <el-option v-for="item in auseList" :key="item.id" :label="item.rolename" :value="item.id"></el-option>
                  </el-select>
                </el-form-item>
                <div class="daoru"><span type="info" style="color:#999">*设置导入人员时的默认角色</span></div>
              </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
              <el-button type="primary" @click="determine()">确 定</el-button>
            </span>
        </el-dialog>
  </div>
</template>

<script>
export default {
  props: {},
  components: {},
  watch: {
      filterText(val) {
        this.$refs.tree.filter(val);
      }
  },
  data() {
    return {
        user: JSON.parse(sessionStorage.getItem("user")),
        tableData: [],
        total: 0,
        dialogVisible: false,
        filterText: '',
        addDialogVisible: false,
        form: {
            rolename: '',
            roleDescribe: '',
            id: ''
        },
        moduleList: [],
        roles: '',
        titles: '',
        addTil: '立即添加',
        keyword: '',
        auseList: [],
        defaultRole: false,
        roleId: '',
        roleName: '',
        rules: {
          rolename: [{
            required: true, message: '请输入角色名称', trigger: 'blur'
          }]
        }
    };
  },
  computed: {},
  watch: {
      filterText(val) {
        this.$refs.tree.filter(val);
      },
      keyword(val) {
        if(val == '') {
          this.mohu()
        }
      }
  },
  created() {},
  mounted() {
    this.getRole()
    // this.shisha()
  },
  methods: {
      // 默认角色点击确定
      determine() {
        this.http.post('/permission/setDefaultRole', {
          companyId: this.user.companyId,
          id: this.roleId
        },
        res => {
            if (res.code == "ok") {
                this.$message({
                    message: '操作成功',
                    type: "success"
                });
                this.defaultRole = false
                this.getRole()
            } else {
                this.$message({
                    message: res.msg,
                    type: "error"
                });
            }
        },
        error => {
            this.$message({
                message: error,
                type: "error"
            });
        });
      },
      // 默认角色
      modify() {
        for(var i in this.auseList) {
          if(this.auseList[i].isDefault == '1') {
            this.roleId = this.auseList[i].id
          }
        }
        this.defaultRole = true
      },
      // 模糊匹配
      mohu() {
        console.log(this.keyword)
        if(this.keyword == '') {
          this.tableData = this.auseList
          return
        }
        var len = this.auseList.length;
        var arr = []
        for(var i = 0; i < len; i++){
            if(this.auseList[i].rolename.indexOf(this.keyword)>=0){
                arr.push(this.auseList[i]);
            }
        }
        this.tableData = arr
      },
      // 还不知道是啥
      shisha(id) {
        this.roles = id
        this.http.post('/permission/getAuthority', {
          companyId: this.user.companyId,
          role: id
        },
        res => {
            if (res.code == "ok") {
              console.log(res.data, '数据来源(990)')
              this.moduleList = res.data
              this.dialogVisible = true
            } else {
                this.$message({
                    message: res.msg,
                    type: "error"
                });
            }
        },
        error => {
            this.$message({
                message: error,
                type: "error"
            });
        });
      },
      // 获取权限列表
      getRole() {
        this.http.post('/permission/getRoleList', {
          companyId: this.user.companyId
        },
        res => {
            if (res.code == "ok") {
              console.log(res.data, '数据来源')
              this.tableData = res.data
              this.auseList = res.data
            } else {
                this.$message({
                    message: res.msg,
                    type: "error"
                });
            }
        },
        error => {
            this.$message({
                message: error,
                type: "error"
            });
        });
      },
      handleSizeChange() {},
      handleCurrentChange() {},
      filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
      },
        handleAdd(tex, tel, id) {
          if(id && id.rolename == '超级管理员'){
            this.$message('超级管理员为固定的默认角色无法编辑');
            return
          }
          this.titles = tex
          this.addTil = tel
          this.addDialogVisible = true
          // var ss = {rolename: '', roleDescribe: '',id: ''}
          var ss = {}
          id ? ss.id = id.id : ss.id = ''
          id ? ss.rolename = id.rolename : ss.rolename = ''
          id ? ss.roleDescribe = id.roleDescribe : ss.roleDescribe = ''
          this.form = ss
      },
      // 添加角色
      onSubmit(formName) {
          // var ss = this.form
          this.$refs[formName].validate((valid) => {
          if (valid) {
             this.http.post('/permission/editRole', {
                id: this.form.id,
                name: this.form.rolename,
                description: this.form.roleDescribe,
                companyId: this.user.companyId
              },
              res => {
                  if (res.code == "ok") {
                    console.log(res.data, '数据来源(123)')
                    this.addDialogVisible = false
                    this.getRole()
                  } else {
                      this.$message({
                          message: res.msg,
                          type: "error"
                      });
                  }
              },
              error => {
                  this.$message({
                      message: error,
                      type: "error"
                  });
              });
          } else {
            console.log('error submit!!');
            return false;
          }
        });
         
      },
      deteHand(item) {
        this.$confirm('此操作将删除('+item.rolename+')角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.http.post('/permission/deleteRole', {
            id: item.id,
          },
          res => {
              if (res.code == "ok") {
                this.$message({
                      message: '删除成功',
                      type: "success"
                  });
                this.getRole()
              } else {
                  this.$message({
                      message: res.msg,
                      type: "error"
                  });
              }
          },
          error => {
              this.$message({
                  message: error,
                  type: "error"
              });
          });
        }).catch(() => {});
      },
      mainChange(mainMenu) {
        //一级选中，全部选中,一级取消全部取消
        console.log(mainMenu);
        mainMenu.children.forEach(c=>{
            c.checked = mainMenu.checked;
            c.functionList.forEach(f=>{
                f.checked = mainMenu.checked;
            });
        });
        if(mainMenu.functionList) {
          mainMenu.functionList.forEach(c=>{
            c.checked = mainMenu.checked;
          })
        }
      },
      subChange(subMenu) {
        //二级选中，自动勾选对应的一级
        console.log(subMenu);
        let mainMenuList = this.moduleList;
        mainMenuList.forEach(m=>{
          //检测子菜单
          if (m.id == subMenu.parentId) {
            //找到父菜单了
            var hasChecked = false;
            m.children.forEach(c=>{
                if (c.checked) {
                    hasChecked = true;
                }
            })
            //当前点击的子菜单所有同级菜单是否有点中的，如果没有需要把父级取消勾选
            m.checked = hasChecked;
          }
        });
      },
      subChanges(subMenu, id) {
        let mainMenuList = this.moduleList
        mainMenuList.forEach(m=>{
          if(m.id == id) {
            //找到父菜单了
            var hasChecked = false;
            m.functionList.forEach(c=>{
                if (c.checked) {
                    hasChecked = true;
                }
            })
            console.log(hasChecked, '事件')
            // m.checked = hasChecked;
            if(hasChecked) {
              console.log('执行')
              m.checked = hasChecked;
            }
          }
        });
      },
      dianji(item) {
        console.log(item)
        let mainMenuList = this.moduleList
        mainMenuList.forEach(m=>{
          if(m.id == item.id) {
            m.useState = !m.useState
          }
        });
      },
      saveList() {
        this.dialogVisible = false
        console.log(this.moduleList)
        this.http.post('/permission/savePermission', {
            role: this.roles,
            moduleList: JSON.stringify(this.moduleList),
          },
          res => {
              if (res.code == "ok") {
                this.$message({
                      message: '操作成功',
                      type: "success"
                  });
                this.getRole()
              } else {
                  this.$message({
                      message: res.msg,
                      type: "error"
                  });
              }
          },
          error => {
              this.$message({
                  message: error,
                  type: "error"
              });
          });
      },
      exportAuthority(row){ // 导出权限
        this.http.post('/permission/exportData',{
          role: row.id,
          companyId: this.user.companyId
        },res => {
          if(res.code == 'ok'){
            var a = document.createElement('a');
            a.download = "权限数据表.xls";
            a.href = res.data;
            a.click();
          }else{
            this.$message({
              message: res.msg,
              type: 'error'
            })
          }
        },err => {
          this.$message({
            message: err,
            type: 'error'
          })
        })
      }
  },
};
</script>

<style scoped>
  ul {
    padding: 0 0 0 30px;
    margin: 0;
  }
  li {
    list-style: none;
  }
  .quanxians {
    height: 400px;
    width: 100%;
    overflow: auto;
  }
  .gongn {
    display: inline-block;
    width: 500px;
  }
  .daoru {
    margin-left: 10px;
  }
</style>
