<!--角色管理-->
<template>
  <div class="app-container role">
    <div class="page-container rolePage" v-if="pageType==1">
      <div class="page-form-title-box">
        <el-form :model="queryParams" ref="queryForm" v-show="showSearch" :inline="true" >
          <el-form-item label="" prop="roleName">
            <el-input
              v-model="queryParams.roleName"
              placeholder="请输入角色名称"
              clearable
              size="small"
            />
          </el-form-item>
          <el-form-item label="" prop="state">
            <el-select
              v-model="queryParams.state"
              placeholder="请选择状态"
              clearable
              size="small"
            >
              <el-option
                v-for="dict in statusOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
          <p class="page-inquire-common-style-button" @click="handleQuery">查询</p>
          <p class="page-reset-common-style-button" @click="resetQuery">重置</p>
          <p class="page-submit-common-style-button"
             style="float: right;"
             @click="dialogOpen"
             v-hasPermiRouter="['system:role:add']"
          >新增</p>
        </el-form>
      </div>
      <div class="page-content-box">
        <el-table class="table-box" v-loading="loading" border :data="roleList" v-if="pageType==1">
          <el-table-column label="序号" width="80" align="center"  type="index"/>
          <el-table-column label="名称" prop="roleName" align="center" :show-overflow-tooltip="true" width="200"/>
          <el-table-column label="权限字符" prop="roleKey" align="center" :show-overflow-tooltip="true" width="200">
            <template slot-scope="scope">
              <span>{{scope.row.roleKey?scope.row.roleKey:'--'}}</span>
            </template>
          </el-table-column>
          <!--<el-table-column label="权限类型" prop="onlyIdentify" align="center" :show-overflow-tooltip="true" width="100">-->
            <!--<template slot-scope="scope">-->
              <!--<span>{{scope.row.onlyIdentify?'功能权限':'数据权限'}}</span>-->
            <!--</template>-->
          <!--</el-table-column>-->
          <el-table-column label="数据范围" prop="dataScope" align="center" :show-overflow-tooltip="true" width="296">
            <template slot-scope="scope">
              <p v-for="(item,index) in optionsDataList" :key="index" v-if="scope.row.dataScope == item.type">{{item.value}}</p>
            </template>
          </el-table-column>
          <el-table-column label="描述" prop="roleDesc" align="center" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{scope.row.roleDesc?scope.row.roleDesc:'--'}}</span>
            </template>
          </el-table-column>
          <el-table-column label="状态" prop="dataScope" align="state" :show-overflow-tooltip="true" width="100">
            <template slot-scope="scope">{{scope.row.state?'启用':'停用'}}</template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="340" v-if="tableButtonType">
            <template slot-scope="scope">
              <div class="table-button-box">
                <p class="table-button-null"></p>
                <p class="table-button-p"
                   @click="handleUpdate(scope.row)"
                   v-hasPermiRouter="['system:role:edit']"
                >编辑</p>
                <p class="table-button-p"
                   @click="copyButton(2,scope.row)"
                   v-hasPermiRouter="['system:role:perms']"
                >PC权限配置</p>
                <p class="table-button-p"
                   @click="copyButton(3,scope.row)"
                   v-hasPermiRouter="['applet:role:perms']"
                >小程序权限配置</p>
                <p class="table-button-p"
                   @click="handleDelete(scope.row)"
                   v-hasPermiRouter="['system:role:del']"
                >删除</p>
                <p class="table-button-null"></p>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <pagination :page-sizes="[20, 30, 40, 50]"
                    v-if="pageType==1"
                    v-show="total>0"
                    :total="total"
                    layout="total, prev, pager, next, sizes, jumper"
                    :page.sync="queryParams.page"
                    :limit.sync="queryParams.pageSize"
                    @pagination="getList"
        />
      </div>
    </div>
    <!--新增弹窗-->
    <el-dialog class="classConfig-dialog" :title='dialogTitle' width="540px" append-to-body
               :visible.sync="dialogType" v-if="dialogType" @close="dialogOff()"
               :close-on-click-modal="false" :close-on-press-escape="false">
      <el-form :model="dialogForm" ref="dialogForm" :inline="true" :rules="dialogRules" class="addCheckPage-min" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="dialogForm.roleName" placeholder="请输入角色名称" maxLength="10" style="width:320px;"/>
        </el-form-item>
        <el-form-item label="权限类型" prop="onlyIdentify">
          <el-radio-group v-model="dialogForm.onlyIdentify" :disabled="!!dialogForm.roleId">
            <el-radio :label="false">数据权限</el-radio>
            <el-radio :label="true">功能权限</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="权限字符" prop="roleKey" v-if="dialogForm.onlyIdentify">
          <el-input v-model="dialogForm.roleKey" :disabled="!!dialogForm.roleId" placeholder="请输入权限字符" maxLength="20" style="width:320px;"/>
        </el-form-item>
        <el-form-item label="数据范围" prop="dataScope">
          <el-select v-model="dialogForm.dataScope"
                     placeholder="请选择数据范围"
                     clearable style="width:320px;">
            <el-option
              v-for="dict in optionsDataList"
              :key="dict.type"
              :label="dict.value"
              :value="dict.type"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="指定部门" prop="customDept" v-if="dialogForm.dataScope == 5&&!dialogForm.onlyIdentify">
          <el-cascader
            style="width:320px;"
            ref="cascader"
            :options="treeselectList"
            :props="{multiple: true,value: 'deptId', label: 'deptName',children:'child',emitPath:false}"
            collapse-tags
            v-model="dialogForm.customDept"
            clearable>
          </el-cascader>
        </el-form-item>
        <el-form-item label="排序" prop="roleSort">
          <el-input-number v-model="dialogForm.roleSort" controls-position="right" :min="1" :max="9999" style="width:320px;"></el-input-number>
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-radio-group v-model="dialogForm.state" style="width:320px;">
            <el-radio :label="true">启用</el-radio>
            <el-radio :label="false">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="描述" prop="roleDesc">
          <el-input v-model="dialogForm.roleDesc" placeholder="请输入描述" maxLength="20" style="width:320px;"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer dialog-footer-box">
        <p class="dialog-footer-button-null"></p>
        <p class="dialog-footer-button-info" @click="dialogOff()">取消</p>
        <p class="dialog-footer-button-primary" @click="dialogSubmit">提交</p>
        <p class="dialog-footer-button-null"></p>
      </div>
    </el-dialog>
    <!--PC端权限-->
    <add-page v-if="pageType == 2" :propsData="propsData"></add-page>
    <!--小程序权限-->
    <small-program-limits v-if="pageType == 3" :propsData="propsData"></small-program-limits>
  </div>
</template>

<script>
import { systemRoleList,systemRoleDetail,systemRoleDelete,systemRoleAdd,systemRoleUpdate,systemRoleGetRoleMenu } from "@/api/systemManagement/index";
import { getDeptDropList } from "@/api/commonality/permission";
import { listRole, getRole, delRole, addRole, updateRole, dataScope, changeRoleStatus } from "@/apiDemo/system/role";
import addPage from "./addPage.vue"
import smallProgramLimits from "./smallProgramLimits.vue"

export default {
  components: {
    addPage,
    smallProgramLimits
  },
  name: "Role",
  data() {
    return {
      tableButtonType:this.hasPermiDom(['system:role:edit','system:role:detail','system:role:del']),
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 状态数据字典
      statusOptions: [{dictValue:true,dictLabel:"启用"}, {dictValue:false,dictLabel:"禁用"}],
      //部门列表
      treeselectList:[],
      // 查询参数
      queryParams: {
        page: 1,
        pageSize:20,
        roleName: null,
        state: null
      },
      roleList:[],
      pageType:1,
      //组件传参数据
      propsData:{},
      //数据范围（1：全部, 2：部门及下级, 3：本部门, 4：仅本人，5：自定义）
      optionsDataList:[
        {type: 1, value: "所有数据",},
        {type: 2, value: "本部门及下级部门数据",},
        {type: 3, value: "本部门",},
        {type: 4, value: "当前账号数据",},
        {type: 5, value: "自定义",},
      ],
      //新增编辑数据
      dialogTitle:null,
      dialogType:false,
      dialogForm:{},
      dialogRules:{
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          { required: true, message: "请输入角色名称", validator: this.spaceJudgment, trigger: "blur" }
        ],
        roleKey: [
          { required: true, message: "请输入权限字符", trigger: "blur" },
          { required: true, message: "请输入权限字符", validator: this.spaceJudgment, trigger: "blur" }
        ],
        roleSort: [
          { required: true, message: "请输入排序", trigger: "blur" },
          { required: true, message: "请输入排序", validator: this.spaceJudgment, trigger: "blur" }
        ],
        dataScope: [
          { required: true, message: "请选择数据范围", trigger: "blur" },
        ],
        state: [
          { required: true, message: "请选择状态", trigger: "blur" },
        ],
        onlyIdentify: [
          { required: true, message: "请选择权限类型", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getDeptDropList();
  },
  methods: {
    goPage(type){
      if(this.pageType != type){
        if(type == 1){
          this.$set(this,'pageType',type);
        }else if(type == 4){
          this.$set(this,'pageType',1);
          this.resetQuery();
        }
      }
    },
    /** 查询角色列表 */
    getList() {
      this.$set(this,'loading',true);
      systemRoleList(this.queryParams).then(response => {
        this.$set(this,'loading',false);
        this.$set(this,'roleList',response.data.records);
        this.$set(this,'total',response.data.total);
      });
    },
    //部门列表
    getDeptDropList(){
      getDeptDropList(this.queryParams).then(response => {
        this.$set(this,'treeselectList',response.data);
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$set(this,"queryParams", {
        page: 1,
        pageSize:20,
        roleName: null,
        state: null
      });
      this.handleQuery();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      systemRoleDetail({roleId:row.roleId}).then(response => {
        this.dialogFormReset();
        let obj = JSON.parse(JSON.stringify(response.data));
        if (obj.dataScope == 5 && obj.customDept[0]){
          obj.customDept = obj.customDept.split(',');
        }else{
          obj.customDept = [];
        }
        this.$set(this,'dialogForm',obj);
        this.$set(this,'dialogTitle','编辑');
        this.$set(this,'dialogType',true);
      });
    },
    /** 权限配置按钮 */
    copyButton(type,row){
        this.$set(this,'propsData',row);
        if(type == 2){
          this.$set(this,'pageType',2);
        }else if (type == 3){
          this.$set(this,'pageType',3);
        }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除角色?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return systemRoleDelete({roleId:row.roleId});
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    //弹层关闭
    dialogOff(){
      this.$set(this,'dialogType',false);
    },
    /** 新增按钮操作-弹层开启 */
    dialogOpen(){
      this.dialogFormReset();
      this.$set(this,'dialogTitle','新增');
      this.$set(this,'dialogType',true);
    },
    //弹层确定
    dialogSubmit(){
      this.$refs["dialogForm"].validate(valid => {
        if (valid) {
          let obj = {
            roleName:this.dialogForm.roleName,
            onlyIdentify:this.dialogForm.onlyIdentify,
            roleDesc:this.dialogForm.roleDesc,
            roleSort:this.dialogForm.roleSort,
            state:this.dialogForm.state,
          }
          if(!this.dialogForm.onlyIdentify){
            obj.roleKey = '';
          }else{
            obj.roleKey = this.dialogForm.roleKey;
          }
          obj.dataScope = this.dialogForm.dataScope;
          if(this.dialogForm.dataScope == 5){
            let list = this.$refs['cascader'].getCheckedNodes()
            let valueList = [];
            list.forEach((item)=>{
              valueList.push(item.value)
            })
            obj.customDept = valueList+'';
          }else{
            obj.customDept = '';
          }
          if(this.dialogForm.roleId){
            //编辑
            obj.roleId = this.dialogForm.roleId;
            systemRoleUpdate(obj).then(response => {
              this.msgSuccess(response.message);
              this.getList();
              this.$set(this,'dialogType',false);
            });
          }else{
            //新增
            systemRoleAdd(obj).then(response => {
              this.msgSuccess(response.message);
              this.getList();
              this.$set(this,'dialogType',false);
            });
          }
        }
      })
    },
    dialogFormReset(){
      this.$set(this,'dialogForm',{
        roleName:'',
        roleKey:'',
        roleDesc:'',
        roleSort:1,
        onlyIdentify:false,
        customDept:'',
        dataScope:'',
        state:true,
      });
    },
  }
};
</script>

<style scoped lang="scss">
  .role {
    .rolePage{

    }
  }
</style>
