<template>
  <div class="role-manage">
    <el-card>
      <div class="filter-container">
        <el-form :model="queryParams" label-width="100px" class="demo-form-inline">
          <el-row>
            <el-col :span="6">
              <el-form-item label="角色名称">
                <el-input v-model="queryParams.roleNameLike" placeholder="请输入角色名称" clearable size="small" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="角色编码">
                <el-input v-model="queryParams.roleCodeLike" placeholder="请输入角色编码" clearable size="small" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item>
                <el-button type="primary" size="medium" @click="handleQuery">查询</el-button>
                <el-button type="primary" plain size="medium" @click="resetQuery">重置</el-button>
                <el-button type="primary" plain size="medium" @click="handleAdd">新增</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <r-table
        :columns="tableConfig.columns"
        :data="tableData"
        :deletion="false"
        :total="tableConfig.total"
        @currentChange="handleCurrentChange"
        @sizeChange="handleSizeChange"
        :currentPage="tableConfig.currentPage"
        :pageSize="tableConfig.pageSize"
      />
    </el-card>

    <!-- 角色新增弹窗 -->
    <role-dialog :visible.sync="dialogVisible" :title="dialogTitle" :is-edit="isEdit" :is-view="isView" :role-data="currentRoleData" @submit="handleSubmit" />
  </div>
</template>

<script>
import { getRolePage, deleteRole, queryRoleDetail } from '@/api/system/role'
import RoleDialog from '@/views/system/role/components/RoleDialog'

export default {
  name: 'RoleManage',
  components: {
    RoleDialog
  },
  data() {
    return {
      loading: false,
      dialogVisible: false,
      resetPasswordVisible: false,
      dialogTitle: '添加角色',
      isEdit: false,
      isView: false,
      currentRoleData: {},
      total: 0,
      roleList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        roleCodeLike: '',
        roleNameLike: ''
      },
      // 表格配置项
      tableConfig: {
        total: 0,
        currentPage: 1,
        pageSize: 10,
        columns: [
          { prop: 'roleCode', key: '角色编码' },
          { prop: 'roleName', key: '角色名称' },
          { prop: 'remark', key: '角色描述' },
          {
            key: '操作',
            render: (h, params) => {
              return h('div', [
                h(
                  'el-button',
                  {
                    props: { type: 'text', size: 'mini' },
                    on: { click: () => this.handleEdit(params.row) }
                  },
                  '编辑'
                ),
                // h(
                //   'el-button',
                //   {
                //     props: { type: 'text', size: 'mini' },
                //     on: { click: () => this.handleInfoVisible(params.row) }
                //   },
                //   '查看详情'
                // ),
                h(
                  'el-button',
                  {
                    props: { type: 'text', size: 'mini', style: 'color: #F56C6C' },
                    on: { click: () => this.handleDelete(params.row) }
                  },
                  '删除'
                )
              ])
            }
          }
        ]
      },
      tableData: []
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    // 获取角色列表
    getRoleList() {
      this.loading = true
      const params = { ...this.queryParams }

      getRolePage(params)
        .then(response => {
          if (response.code === '0') {
            this.tableData = response.content.content.list || []
            this.tableConfig.total = response.content.content.total || 0
          } else {
            this.$message.error(response.msg || '获取角色列表失败')
          }
        })
        .catch(error => {
          this.$message.error('获取用户列表出错', error)
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleQuery() {
      this.queryParams.page = 1
      this.getRoleList()
    },
    resetQuery() {
      this.queryParams.roleCodeLike = ''
      this.queryParams.roleNameLike = ''
      this.handleQuery()
    },
    handleAdd() {
      this.isEdit = false
      this.isView = false
      this.currentRoleData = {}
      this.dialogVisible = true
      this.dialogTitle = '添加角色'
    },
    handleEdit(row) {
      this.isEdit = true
      this.isView = false
      this.dialogTitle = '编辑角色'
      this.loading = true

      // 获取用户详情
      queryRoleDetail({ id: row.id })
        .then(response => {
          if (response.code === '0') {
            this.currentRoleData = response.content.content || {}
            this.dialogVisible = true
          } else {
            this.$message.error(response.msg || '获取角色详情失败')
          }
        })
        .catch(error => {
          console.error('获取角色详情出错：', error)
          this.$message.error('获取角色详情出错')
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleSubmit() {
      this.getRoleList() // 提交后刷新列表
    },
    handlePermission(row) {
      // TODO: 实现权限设置逻辑
    },
    handleSizeChange(val) {
      this.queryParams.pageSize = val
      this.handleQuery()
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val
      this.handleQuery()
    },
    handleDelete(row) {
      this.$confirm('确认删除该角色吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.loading = true
          // 将id放入数组中传递
          deleteRole([row.id])
            .then(response => {
              if (response.code === '0') {
                this.$message.success('删除成功')
                this.getRoleList()
              } else {
                this.$message.error(response.msg || '删除失败')
              }
            })
            .catch(error => {
              this.$message.error('删除角色出错', error)
            })
            .finally(() => {
              this.loading = false
            })
        })
        .catch(() => {
          this.$message.info('已取消删除')
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.role-manage {
  padding: 20px;

  .filter-container {
    margin-bottom: 20px;

    .el-form-item {
      margin-bottom: 10px;
      margin-right: 10px;

      .el-form-item__label {
        padding-right: 8px;
      }
    }
  }
}
</style>
