<!-- 角色管理 -->
<template>
  <div class="role">
    <div class="header">
      <div class="left">
        <el-button class="btn" @click="showForm(0)">+ 新增</el-button>
      </div>
      <div class="center">
        {{$x_factory.plantName}} - 角色管理
      </div>
      <div class="right">
        <i class="el-icon-close" @click="back" />
      </div>
    </div>
    <div class="main global">
      <div class="table">
        <el-table ref="table" :data="tableData" height="100%" v-loading="tableLoading" :element-loading-background="loadingColor">
          <el-table-column prop="name" label="角色名" align="center"></el-table-column>
          <el-table-column prop="permissionT" label="权限" align="center">
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template v-slot="scope">
              <span class="table-btn" @click="showForm(scope.row)">编辑</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <el-dialog class="dialog global" width="40%" :title="formTitle" :visible.sync="formShow" destroy-on-close
      v-loading="formLoading" :element-loading-background="loadingColor">
      <el-form ref="form" :model="formData" :rules="formRules" label-width="100px" size="small">
        <el-form-item label="角色名" prop="name">
          <el-input v-model.trim="formData.name" placeholder="请填写角色名" />
        </el-form-item>
        <el-form-item label="角色权限" prop="permissionPage">
          <el-checkbox class="checkbox" :indeterminate="formData.isIndeterminatePage" v-model="formData.checkAllPage" @change="allCheck($event, 1)">全选所有页面（至少选择一个）</el-checkbox>
          <el-checkbox-group class="checkgroup" v-model="formData.permissionPage" @change="checkHandler($event, 1)">
            <el-checkbox v-for="(route, key) in RouteMap" :label="key" :key="key">{{route}}</el-checkbox>
          </el-checkbox-group>
          <el-checkbox class="checkbox" :indeterminate="formData.isIndeterminateBtn" v-model="formData.checkAllBtn" @change="allCheck($event, 2)">全选所有功能</el-checkbox>
          <el-checkbox-group class="checkgroup" v-model="formData.permissionBtn" @change="checkHandler($event, 2)">
            <el-checkbox v-for="(btn, key) in ButtonMap" :label="key" :key="key">{{btn}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div class="btn-list">
        <el-button class="btn-active" type="primary" @click="onSubmit">保存</el-button>
        <el-button class="btn-default" @click="formShow = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    ChartStyle,
    RouteMap,
    ButtonMap
  } from '@/common/const.js';
  import User from '@/api/user.js';
  export default {
    components: {},
    data() {
      return {
        tableLoading: false,
        formLoading: false,
        loadingColor: ChartStyle.loadingColor,
        RouteMap: RouteMap,
        ButtonMap: ButtonMap,
        RouteMapValue: Object.keys(RouteMap),
        ButtonMapValue: Object.keys(ButtonMap),
        tableData: null,
        formShow: false,
        formTitle: '',
        formData: null,
        formRules: {
          name: [{
            required: true,
            message: '请输入角色名称',
            trigger: 'blur'
          }],
          permissionPage: [{
            required: true,
            message: '至少选择一个页面权限',
            trigger: 'blur'
          }],
        },
      };
    },
    created() {
      this.formReset();
      this.getList();
    },
    methods: {
      // 返回用户管理
      back() {
        this.$router.push('/UserManage');
      },
      // 重置表单
      formReset() {
        this.formData = {
          name: '',
          permission: '',
          permissionPage: [],
          permissionBtn: [],
          checkAllPage: false,
          checkAllBtn: false,
          isIndeterminatePage: false,
          isIndeterminateBtn: false,
        };
      },
      // 获取角色列表
      async getList() {
        this.tableLoading = true;
        try {
          let res = await User.getRoleList();
          if(!res) res = [];
          res.forEach(i => i.permissionT = i.permission?.toString().split(',').map(j => this.RouteMap[j] || this.ButtonMap[j]).join(',') || '' ); // 中文版
          this.tableData = res;
        } catch (e) {
          console.log(e);
        }
        this.tableLoading = false;
      },
      // 新增编辑
      showForm(row) {
        // 编辑
        if (row) {
          this.formTitle = '编辑角色';
          // 回显赋值
          let permissionPage = [],
            permissionBtn = [];
          if (row.permission) {
            for (let item of row.permission.split(',')) {
              if (item in RouteMap) permissionPage.push(item);
              if (item in ButtonMap) permissionBtn.push(item);
            }
          }
          this.formData = {
            roleId: row.roleId,
            name: row.name,
            permission: row.permission,
            permissionPage,
            permissionBtn,
            checkAllPage: permissionPage.length === this.RouteMapValue.length,
            checkAllBtn: permissionBtn.length === this.ButtonMapValue.length,
            isIndeterminatePage: permissionPage.length > 0 && permissionPage.length < this.RouteMapValue.length,
            isIndeterminateBtn: permissionBtn.length > 0 && permissionBtn.length < this.ButtonMapValue.length,
          };
          // 新增
        } else {
          this.formTitle = '新增角色';
          this.formReset(); // 清空表单
        }
        this.formShow = true;
      },
      // 全选，type - 1为页面，2为按钮
      allCheck(val, type) {
        if (type == 1) {
          this.formData.permissionPage = val ? this.RouteMapValue : [];
          this.formData.isIndeterminatePage = false;
        }
        if (type == 2) {
          this.formData.permissionBtn = val ? this.ButtonMapValue : [];
          this.formData.isIndeterminateBtn = false;
        }
      },
      // 单选，type - 1为页面，2为按钮
      checkHandler(val, type) {
        if (type == 1) {
          let isAllChecked = val.length === this.RouteMapValue.length;
          this.formData.checkAllPage = isAllChecked;
          this.formData.isIndeterminatePage = val.length > 0 && !isAllChecked;
        }
        if (type == 2) {
          let isAllChecked = val.length === this.ButtonMapValue.length;
          this.formData.checkAllBtn = isAllChecked;
          this.formData.isIndeterminateBtn = val.length > 0 && !isAllChecked;
        }
      },
      // 提交表单
      onSubmit() {
        this.$refs.form.validate(async valid => {
          if (!valid) return;
          if (this.formData.roleId == 1) {
            this.$message.error('超级管理员无法编辑！')
            return;
          }
          this.formData.permission = this.formData.permissionPage.concat(this.formData.permissionBtn).join(',');
          this.formLoading = true;
          try {
            await User.newOrUpdateRole(this.formData);
            this.$message.success('操作成功');
            this.formShow = false;
            this.getList();
          } catch (e) {
            console.log(e);
          }
          this.formLoading = false;
        });
      }
    }
  };
</script>

<style lang="scss" scoped>
  .role {
    height: 100%;
    padding: 1.875rem 3.125rem;
    box-sizing: border-box;

    .header {
      height: 4.25rem;
	  line-height: 4.25rem;
      background-image: linear-gradient(270deg, rgba(197, 254, 255, 0.10) 0%, rgba(147, 252, 255, 0.50) 52%, rgba(147, 252, 255, 0.10) 100%);
      padding: 0 1.875rem;
      box-sizing: border-box;
      position: relative;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .left {
        display: flex;
        z-index: 1;

        .btn {
          @extend %btn-default;
        }

        .btn:hover {
          @extend %btn-hover;
        }
      }

      .center {
        @extend %pos-center;
        font-size: 1.625rem;
        letter-spacing: 0.1625rem;
        text-shadow: 0 2px 8px rgba(78, 97, 214, 0.50);
      }

      .right {
        z-index: 1;

        i {
          font-size: 1.6rem;
        }
      }
    }

    .main {
      height: calc(100% - 4.25rem);
      background: rgba(147, 252, 255, 0.08);
      padding: 1.875rem 1.875rem 0;
      box-sizing: border-box;

      .table {
        height: calc(100% - 40px);

        .table-btn {
          color: $color-cyan;
          cursor: pointer;
        }
      }

      .page {
        margin: 0.3125rem 0;
      }
    }

    .dialog {
      /deep/ .el-dialog__body{
        text-align: left;
      }
      
      
      /deep/ .el-form-item__label {
        color: #fff;
      }
      
      .checkbox{
        width: 100%;
      }
      
      .checkgroup{
          flex-flow: wrap;
      }
      ::v-deep .el-checkbox{
        color: #bebebe;
      }
      ::v-deep .el-checkbox__label{
          line-height: 2rem;
      }
      ::v-deep .el-checkbox__input.is-checked+.el-checkbox__label{
        color: #fff;
      }

      .btn-list {
        @extend %flex-center;
        margin-top: 2rem;
      }

      .btn-active {
        @extend %btn-active;
      }

      .btn-default {
        @extend %btn-default;
      }
    }
  }
</style>
