﻿<template>
  <div class="user-manage" style="width: 100%; height: 100%;">
    <div class="search-wrapper">
      <a-form layout="inline" ref="form">
        <a-form-item label="角色名称" style="min-width: 19%;">
          <a-input v-model:value="searchObj.roleName" allow-clear />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="getRoleList()">查询</a-button>
        </a-form-item>
        <a-form-item v-if="readOnlyRole == 'display' && isJdcjbr">
          <a-button type="primary" @click="toaddRole()">添加</a-button>
        </a-form-item>
      </a-form>
    </div>
    <a-table
      :data-source="rolesList"
      :columns="columns"
      :pagination="false"
      row-key="id"
      style="width: 100%;"
      :style="{ height: tableHeight + 'px' }"
      :scroll="{ x: true, y: tableHeight - 60 }"
      bordered>
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'ownerSystem'">
          {{ record.ownerSystem ? systemFilter(record.ownerSystem) : '' }}
        </template>
        <template v-else-if="column.dataIndex === 'action'">
          <a-button v-if="readOnlyRole == 'display' && isJdcjbr" size="small" @click="handleEdit(record)">编辑</a-button>
          <a-button v-if="readOnlyRole == 'display' && isJdcjbr" size="small" type="danger" @click="handleDelete(record)">删除</a-button>
        </template>
      </template>
    </a-table>
    <a-pagination
      show-size-changer
      v-model:pageSize="searchObj.pageSize"
      :total="total"
      :page-size-options="['10', '20', '30', '40']"
      :show-total="total => `共${total}条`"
      @showSizeChange="handleSizeChange"
      @change="handleCurrentChange"
      style="margin-top: 10px;" />
    <a-modal :title="dialogTitle" :open="dialogFormVisible" @cancel="dialogFormVisible = false" width="70%">
      <a-form :model="editRole" :label-col="{span: 6}" style="max-width: 100%;">
        <a-form-item label="角色名称">
          <a-input v-model:value="editRole.roleName" />
        </a-form-item>
        <a-form-item label="归属系统">
          <a-select v-model:value="editRole.ownerSystem" placeholder="请选择" style="min-width: 200px;">
            <a-select-option v-for="(system,index) in privDict.systemFlag" :key="index" :value="system.value">{{ system.name
            }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="责任处室">
          <a-select v-model:value="editRole.dutyIds" placeholder="请选择" mode="multiple" style="min-width: 200px;">
            <a-select-option v-for="(item,index) in privDict.roleDutyList" :key="index" :value="item.id">{{ item.dutyName
            }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="有效标识">
          <a-select v-model:value="editRole.flagValid" placeholder="请选择" style="min-width: 200px;">
            <a-select-option value="1">有效</a-select-option>
            <a-select-option value="0">无效</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="关联权限">
          <tree-x
            :isChecked="'treeCheck'"
            :treeInfos="provList"
            :curIds="editRole.privIds"
            :defaultProps="defaultProps"
            @sendCheckedInfo="sendCheckedInfo"></tree-x>
          <a-select v-model:value="editRole.privIds" placeholder="请选择活动区域" mode="tags" :max-tag-count="1" v-show="false" style="min-width: 200px;">
            <a-select-option v-for="(prov,index) in provList" :key="index" :value="prov.id">{{ prov.privName }}</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
      <template #footer>
        <a-button @click="dialogFormVisible = false">取 消</a-button>
        <a-button type="primary" @click="updateRoleInfo">确 定</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script>
import request from '../../utils/gw_ajax_request.js';
import { getTrees } from '../../utils/gw_treeDataTransfer.js';
import treeX from '../../widgets/treeX.vue';
import { requestUserRole } from '../PblmRectify/Common/rectify_api';
export default {
  data() {
    return {
      tableHeight: window.innerHeight - 240,
      menuData: 'user',
      rolesList: [],
      total: 0,
      searchObj: {
        roleName: '',
        pageSize: 10,
        pageNum: 1,
      },
      editRole: {
        roleName: '',
        roleId: '',
        ownerSystem: '',
        flagValid: 1,
        privIds: [],
        dutyIds: [],
      },
      provList: [],
      saveUrl: '',
      privDict: {
        systemFlag: [],
        roleDutyList: [],
      },
      defaultProps: {
        children: 'children',
        title: 'privName',
        key: 'id',
      },
      dialogFormVisible: false,
      dialogTitle: '修改',
      columns: [
        {
          title: '角色名称',
          dataIndex: 'roleName',
          width: 100,
        },
        {
          title: '所属系统',
          dataIndex: 'ownerSystem',
          width: 100,
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: 100,
        },
      ],
      readOnlyRole: localStorage.getItem('readOnlyRole'),
      isJdcjbr: false,
    };
  },
  components: {
    'tree-x': treeX,
  },
  computed: {
    persId() {
      return localStorage.getItem('persId')
        ? localStorage.getItem('persId')
        : '';
    },
  },
  created() {
    this.getAuthenticatedTabs(this.persId);
  },
  mounted() {
    this.getDict();
    this.getRoleList();
    this.getRoleDutyList();
  },
  methods: {
    getAuthenticatedTabs(userId, tabs) {
      this.isJdcjbr = false;
      const currentUser = { userId: userId };
      let userRoles = [];
      requestUserRole(currentUser).then((res) => {
        if (res.data != null) {
          userRoles = res.data; // 当前用户的所有角色列表
          userRoles.forEach((userRole) => {
            if (userRole.roleId == '48fb7e333a1b44129bebfe6aff9ff34c') {
              // 判断是否是监督处经办人
              this.isJdcjbr = true;
            }
          });
        }
        console.log(this.isJdcjbr);
      });
    },
    getRoleList() {
      // request.post('/sys/roles/pageInfo',this.searchObj).then((res)=>{
      //     if(res.success){
      //       this.rolesList = res.data.list
      //       this.total = res.data.total
      //     }else{
      //       this.$message.warning(res.message)
      //     }
      // }).catch(error=>{
      //   this.$message.error(error)
      // })
      this.searchObj['id'] = this.persId;
      this.searchObj.operateType = '1';
      request.post(`/sys/roles/list-by-user`, this.searchObj).then((res) => {
        if (res.success) {
          this.rolesList = res.data.list;
          this.total = res.data.total;
        } else {
          this.$message.warning(res.message);
        }
      });
    },
    getCurPriv(roleId) {
      request
        .post(`/sys/privs/tree-by-role`, {
          roleId: roleId,
          userId: this.persId,
          pageSize: 500,
        })
        .then((res) => {
          if (res.success) {
            this.provList = res.data.list;
            this.provList.forEach((ele) => {
              if (!ele.parentId) {
                ele.parentId = '0';
              }
            });
            this.provList = getTrees(this.provList, '0');

            const curPrivList = res.data.list;
            curPrivList.forEach((ele) => {
              if (ele.checked) {
                this.editRole.privIds.push(ele.id);
              }
            });
          }
        });
    },
    getPrivList() {
      request
        .post(`/sys/privs/tree-by-role`, { userId: this.persId, pageSize: 500 })
        .then((res) => {
          if (res.success) {
            this.provList = res.data.list;
            this.provList.forEach((ele) => {
              if (!ele.parentId) {
                ele.parentId = '0';
              }
            });
            this.provList = getTrees(this.provList, '0');
          }
        });
    },
    handleEdit(rowData) {
      this.dialogTitle = '修改';
      const row = {};
      Object.assign(row, rowData);
      this.editRole = row;
      this.editRole.dutyIds = row.dutyIds == null ? [] : row.dutyIds;
      this.saveUrl = `/sys/roles/updateRole`;
      this.editRole.privIds = [];
      this.getCurPriv(rowData.id);
      this.dialogFormVisible = true;
    },
    toaddRole() {
      this.dialogTitle = '添加';
      this.editRole = {
        roleName: '',
        flagValid: '1',
      };
      this.saveUrl = `/sys/roles/insertRole`;
      this.editRole.privIds = [];
      this.getPrivList();
      delete this.editRole.roleId;
      this.dialogFormVisible = true;
    },
    updateRoleInfo() {
      const paramsObj = {
        id: this.editRole.roleId,
        privIds: this.editRole.privIds,
      };
      request
        .post(this.saveUrl, this.editRole)
        .then((res) => {
          if (res.success) {
            this.$message.success('保存成功');
            this.getRoleList();
            this.editRole.privIds = [];
            this.dialogFormVisible = false;
          } else {
            this.$message.warning(res.message);
          }
        })
        .catch((error) => {
          this.$message.error(error);
        });
    },
    handleDelete(rowData) {
      this.$confirm({
        title: '提示',
        content: '确认删除当前角色?',
        okType: 'warning',
        onOk: () => {
          request.post(`/sys/roles/${rowData.id}`).then((res) => {
            if (res.success) {
              this.getRoleList();
              this.$message.success('删除成功!');
            }
          });
        },
      });
    },
    sendCheckedInfo(checkIds) {
      this.editRole.privIds = checkIds;
    },
    handleSizeChange(size, val) {
      this.searchObj.pageSize = val;
      this.getRoleList();
    },
    handleCurrentChange(val) {
      this.searchObj.pageNum = val;
      this.getRoleList();
    },
    getDict() {
      // request.post('dc/insp/grw/getGrwDic').then(res=>{
      //   if(res.success){
      //     this.privDict['systemFlag'] = res.data.systemFlag
      //   }else{
      //     this.$message.warning(res.message)
      //   }
      // }).catch(error=>{
      //     this.$message.warning(res.message)
      // })

      request
        .get(`/sys/privs/getSysFlagByUserId?userId=${this.persId}`)
        .then((res) => {
          if (res.success) {
            this.privDict.systemFlag = res.data;
          } else {
            this.$message.warning(res.message);
          }
        })
        .catch((error) => {
          this.$message.warning(error.message);
        });
    },
    getRoleDutyList() {
      request
        .post('/sys/duty/findList', {})
        .then((res) => {
          if (res.success) {
            this.privDict.roleDutyList = res.data;
          } else {
            this.$message.warning(res.message);
          }
        })
        .catch((error) => {
          this.$message.warning(error.message);
        });
    },
    systemFilter(item) {
      if (!item) {
        return '';
      }
      let system;
      this.privDict.systemFlag.forEach((ele) => {
        if (item == ele.value) {
          system = ele.name;
        }
      });
      return system;
    },
  },
};
</script>

<style lang='less' scoped>

</style>
