<template>
  <div>
    <el-card class="no-bottom">
      <el-form
        ref="searchForm"
        :model="searchForm"
        label-width="80px"
        inline
      >
        <el-form-item
          label="角色名称:"
          prop="roleName"
        >
          <el-input v-model="searchForm.roleName" />
        </el-form-item>
        <el-form-item
          label="所属租户:"
          prop="tenantId"
        >
          <el-select v-model="searchForm.tenantId" placeholder="请选择">
            <el-option label="全部" :value="null" />
            <el-option
              v-for="(tenant, index) in tenantList"
              :key="index"
              :value="tenant.id"
              :label="tenant.tenantName"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="getRoleList(1)">查询</el-button>
          <el-button icon="el-icon-refresh" @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="margin-top-20">
      <div class="buttons-group" style="margin-bottom: 20px">
        <el-button v-permission="'UserMgr_add'" type="primary" icon="el-icon-plus" @click="addRole">增加角色</el-button>
      </div>

      <el-table
        :data="tableData"
        border
      >
        <el-table-column
          type="index"
          label="序号"
          width="50px"
          align="center"
        />
        <el-table-column
          prop="roleName"
          label="角色名称"
        />
        <el-table-column
          prop="tenantName"
          label="租户名称"
        />
        <el-table-column
          prop="remark"
          label="描述"
        />
        <el-table-column
          label="操作"
          width="140px"
          align="center"
        >
          <template slot-scope="props">
            <el-button
              v-permission="'AuthMgr_Go'"
              type="text"
              :disabled="!props.row.canEdited"
              @click="goRole(props.row)"
            >权限</el-button>
            <el-button
              v-permission="'UserMgr_update'"
              type="text"
              style="margin-left: 0"
              :disabled="!props.row.canEdited"
              @click="editRole(props.row)"
            >编辑</el-button>
            <el-popconfirm
              v-permission="'UserMgr_delete'"
              title="确定要删除此条记录吗?"
              @onConfirm="deleteRole(props.row.id)"
            >
              <el-button
                slot="reference"
                v-permission="'UserMgr_delete'"
                type="text"
                :disabled="!props.row.canEdited"
              >删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        style="margin-top: 20px;text-align: right"
        :current-page="pageForm.pageNum"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageForm.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageForm.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <el-dialog
      :title="add ? '增加角色' : '编辑角色'"
      :visible.sync="roleDialogVisible"
      width="700px"
    >
      <el-form
        ref="roleForm"
        :model="roleForm"
        label-width="90px"
        :rules="roleRules"
      >
        <el-form-item
          label="角色名称:"
          prop="roleName"
        >
          <el-input v-model="roleForm.roleName" />
        </el-form-item>
        <el-form-item
          label="所属租户:"
          prop="tenantId"
        >
          <el-select
            v-model="roleForm.tenantId"
            placeholder="请选择"
            :value="roleForm.tenantId"
            :disabled="!add"
          >
            <el-option
              v-for="(tenant, index) in tenantList"
              :key="index"
              :value="tenant.id"
              :label="tenant.tenantName"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="描述:"
          prop="remark"
        >
          <el-input
            v-model="roleForm.remark"
            type="textarea"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
        <el-form-item
          label="排序:"
          prop="orderNum"
        >
          <el-input-number
            v-model="roleForm.orderNum"
            :min="1"
            :max="100"
          />
        </el-form-item>
        <!--        <el-form-item-->
        <!--          label="复制权限:"-->
        <!--          prop="d"-->
        <!--        >-->
        <!--          <el-checkbox v-model="roleForm.d">复制</el-checkbox>-->
        <!--          <el-select-->
        <!--            v-model="roleForm.e"-->
        <!--            size="small"-->
        <!--            style="margin-left: 10px;margin-right: 10px"-->
        <!--          >-->
        <!--            <el-option-->
        <!--              v-for="(category, index) in roleList"-->
        <!--              :key="index"-->
        <!--              :value="index"-->
        <!--            >-->
        <!--              {{ category.name }}-->
        <!--            </el-option>-->
        <!--          </el-select>-->
        <!--          的权限-->
        <!--        </el-form-item>-->
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="roleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getRoleList,
  addRole,
  updateRole,
  deleteRole
} from '@/api/system-management/role-management'
import { getAllTenantList } from '@/api/tenant-management/tenant-management'

export default {
  name: 'RoleManagement',
  data() {
    return {
      searchForm: {
        roleName: null,
        tenantId: null
      },
      tenantList: [],
      tableData: [],
      pageForm: {
        pageSize: 10,
        pageNum: 1,
        total: 0
      },
      activeName: 'first',
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      data: [],
      roleDialogVisible: false,
      add: true,
      roleCategory: {
        categoryName: null,
        orderNum: 1
      },
      roleForm: {
        roleName: null,
        tenantId: null,
        remark: null,
        orderNum: null
      },
      roleCategoryDialogVisible: false,
      currentCategory: null,
      currentRole: null,
      roleRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        tenantId: [
          { required: true, message: '请选择租户', trigger: 'blur' }
        ]
      },
      roleCategoryList: []
    }
  },
  created() {
    this.getRoleList(1)
    this.getAllTenantList()
  },
  methods: {
    getAllTenantList() {
      getAllTenantList({})
        .then(res => {
          const { data } = res
          this.tenantList = data
        })
        .catch(err => {
          this.$message.error('操作失败')
          console.error(err.message)
        })
    },
    getRoleList(pageNum) {
      const params = {
        current: pageNum,
        size: this.pageForm.pageSize,
        ...this.searchForm
      }
      getRoleList(params)
        .then(res => {
          const { records, total } = res.data
          this.tableData = records
          this.pageForm.total = total
        })
        .catch(err => {
          this.$message.error('操作失败')
          console.error(err.message)
        })
    },
    resetForm() {
      this.$refs.searchForm.resetFields()
    },
    addRole() {
      this.roleForm = {
        roleName: null,
        categoryId: null,
        tenantId: null,
        remark: null,
        orderNum: null
      }
      this.roleDialogVisible = true
      this.add = true
    },
    editRole(row) {
      this.currentRole = row
      const { roleName, tenantId, remark, orderNum } = row
      this.roleForm = {
        roleName,
        tenantId,
        remark,
        orderNum
      }
      this.roleDialogVisible = true
      this.add = false
    },
    goRole(row) {
      this.$router.push({ path: '/system-management/auth-management', query: { id: row.id }})
    },
    deleteRole(id) {
      deleteRole({ id: id })
        .then(res => {
          this.$message.success('操作成功')
          this.getRoleList(1)
        })
        .catch(err => {
          this.$message.error('操作失败')
          console.error(err.message)
        })
    },
    saveRole() {
      this.$refs.roleForm.validate()
        .then(_ => {
          const { roleName, tenantId, remark, orderNum } = this.roleForm
          const params = {
            roleName,
            tenantId,
            remark,
            orderNum
          }
          if (this.add) {
            addRole(params)
              .then(res => {
                this.$message.success('操作成功')
                this.roleDialogVisible = false
                this.getRoleList(this.pageForm.pageNum)
              })
              .catch(err => {
                this.$message.error(err.message)
                console.error(err.message)
              })
          } else {
            const { id } = this.currentRole
            params.id = id
            updateRole(params)
              .then(res => {
                this.$message.success('操作成功')
                this.roleDialogVisible = false
                this.getRoleList(this.pageForm.pageNum)
              })
              .catch(err => {
                this.$message.error(err.message)
                console.error(err.message)
              })
          }
        })
        .catch(_ => {})
    },
    handleSizeChange(val) {
      this.pageForm.pageSize = val
      this.getRoleList(1)
    },
    handleCurrentChange(val) {
      this.pageForm.pageNum = val
      this.getRoleList(val)
    },
    tagType(data) {
      const typeName = {
        'sys': 'danger',
        'menu': '',
        'page': 'success',
        'button': 'warning'
      }
      return typeName[data.type]
    },
    tagName(data) {
      const tagName = {
        'sys': '系统',
        'menu': '菜单',
        'page': '页面',
        'button': '按钮'
      }
      return tagName[data.type]
    }
  }
}
</script>

<style scoped lang="scss">
  .text {
    font-size: 14px;
  }
  .box-card{
    >>> .el-card__body{
      height: calc(100vh - 150px);
      overflow: scroll;
    }
  }

  .item {
    margin-bottom: 18px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 28px;
    .roleName{
      line-height: 28px;
      cursor: default;
    }
    >>> .el-button{
      padding-top: 6px;
      padding-bottom: 6px;
    }
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both
  }

</style>
