<template>
  <div class="role-manage render-container">
    <section>
      <div class="filter-container">
        <div class="flex align-items-c justify-content-b">
          <el-form
            :model="queryParams"
            label-width="100px"
            label-position="top"
            ref="queryParams"
            inline
          >
            <el-form-item label="角色名称">
              <el-input
                v-model="queryParams.roleNameLike"
                placeholder="请输入角色名称"
                clearable
                size="small"
              />
            </el-form-item>
            <el-form-item label="角色编码">
              <el-input
                v-model="queryParams.roleCodeLike"
                placeholder="请输入角色编码"
                clearable
                size="small"
              />
            </el-form-item>
          </el-form>
          <div class="mt15 flex align-items-c justify-content-b">
            <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
            >
          </div>
        </div>
      </div>

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

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

    <!-- 角色权限 抽屉 -->
    <el-drawer
      :visible.sync="permissionDrawer.visible"
      :title="permissionDrawer.title"
      :wrapperClosable="false"
      size="60%"
    >
      <el-tree
        ref="menuTreeRef"
        :data="menuTree"
        show-checkbox
        node-key="id"
        default-expand-all
        :props="defaultProps"
        @check="handleCheckChange"
      >
      </el-tree>
      <el-row>
        <el-col :span="6">
          <el-button type="primary" size="medium" @click="handleOnSave"
            >确定</el-button
          >
          <el-button type="primary" plain size="medium" @click="handleOnClose"
            >取消</el-button
          >
        </el-col>
      </el-row>
    </el-drawer>
  </div>
</template>

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

export default {
  name: 'RoleManage',
  components: {
    RoleDialog
  },
  data() {
    return {
      permissionDrawer: {
        visible: false,
        title: '设置权限'
      },
      loading: false,
      dialogVisible: false,
      resetPasswordVisible: false,
      dialogTitle: '添加角色',
      isEdit: false,
      isView: false,
      currentRoleData: {},
      total: 0,
      roleList: [],
      menuTree: [],
      defaultProps: {
        children: 'children',
        label: 'menuName'
      },
      defaultCheckedKeys: [],
      checkedKeys: [], // 存储当前选中的节点key
      menuTreeRef: null,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        roleCodeLike: '',
        roleNameLike: ''
      },
      roleMenuForm: {
        id: '',
        sysMenuRoleDTOs: [{ menuId: '' }],
        roleCode: ''
      },
      // 表格配置项
      tableConfig: {
        total: 0,
        currentPage: 1,
        pageSize: 10,
        columns: [
          { prop: 'roleCode', key: '角色编码' },
          { prop: 'roleName', key: '角色名称' },
          { prop: 'remark', key: '角色描述' },
          {
            key: '操作',
            isRedraw: true,
            render: (h, params) => {
              return h('div', [
                h('el-button', {
                  props: {
                    type: 'primary',
                    size: 'mini',
                    icon: 'el-icon-edit-outline',
                    title: '编辑'
                  },
                  class: 'normal-button',
                  on: { click: () => this.handleEdit(params.row) }
                }),
                h(
                  'el-button',
                  {
                    props: {
                      type: 'danger',
                      size: 'mini',
                      icon: 'el-icon-delete',
                      title: '删除'
                    },
                    class: 'normal-button',
                    on: { click: () => this.handleDelete(params.row) }
                  },
                  '删除'
                ),
                h(
                  'el-button',
                  {
                    props: {
                      type: 'primary',
                      size: 'mini',
                      icon: 'el-icon-tickets',
                      title: '设置权限'
                    },
                    class: 'normal-button',
                    on: {
                      click: () => this.handlePermissionVisible(params.row)
                    }
                  },
                  '设置权限'
                )
              ])
            }
          }
        ]
      },
      tableData: []
    }
  },
  created() {
    this.getRoleList()
    this.getMenuTreeData()
  },
  methods: {
    async handlePermissionVisible(row) {
      this.roleMenuForm.id = row.id
      this.roleMenuForm.roleCode = row.roleCode
      this.permissionDrawer.visible = true
      this.defaultCheckedKeys = []
      this.checkedKeys = []
      await this.getCheckedMenuData(row.id)

      this.checkedKeys = [...this.defaultCheckedKeys]
    },
    setTreeRef(el) {
      this.menuTreeRef = el
    },
    // 获取菜单的树型结构数据
    getMenuTreeData() {
      getMenuTree({})
        .then(response => {
          this.menuTree = response.content.content
        })
        .catch(error => {
          this.$message.error('获取菜单列表出错', error)
        })
        .finally(() => {
          this.loading = false
        })
    },
    // 获取角色拥有的菜单权限
    getCheckedMenuData(roleId) {
      this.defaultCheckedKeys = []
      getRoleMenu(roleId)
        .then(response => {
          const nodes = response.content.content
          if (nodes.length === 0) {
            this.defaultCheckedKeys = []
            this.$refs.menuTreeRef.setCheckedKeys([])
            return
          }
          this.extractMenuIds(nodes)
        })
        .catch(error => {
          this.$message.error('获取角色菜单出错', error)
        })
    },
    extractMenuIds(nodes) {
      nodes.forEach(node => {
        this.defaultCheckedKeys.push(node.id)
        this.$refs.menuTreeRef.setChecked(node, true, false)
        if (node.children && node.children.length > 0) {
          this.extractMenuIds(node.children)
        }
      })
    },
    // 获取角色列表
    getRoleList() {
      this.loading = true
      const params = { ...this.queryParams }

      getRolePage(params)
        .then(response => {
          this.tableData = response.content.content.list || []
          this.tableConfig.total = response.content.content.total || 0
        })
        .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 => {
          this.currentRoleData = response.content.content || {}
          this.dialogVisible = true
        })
        .catch(() => {
          this.$message.error('获取角色详情出错')
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleSubmit() {
      this.getRoleList() // 提交后刷新列表
    },
    handlePermission() {
      // TODO: 实现权限设置逻辑
    },
    handleSizeChange(val) {
      this.queryParams.pageSize = val
      this.handleQuery()
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val
      this.handleQuery()
    },
    handleDelete(row) {
      this.$messageBox(
        () => {
          this.loading = true
          // 将id放入数组中传递
          deleteRole([row.id])
            .then(() => {
              this.$message.success('删除成功')
              this.getRoleList()
            })
            .catch(error => {
              this.$message.error('删除角色出错', error)
            })
            .finally(() => {
              this.loading = false
            })
        },
        '确认删除该角色吗？',
        'warning',
        '警告'
      )

      // this.$confirm('确认删除该角色吗？', '警告', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // })
      //   .then(() => {
      //
      //   })
      //   .catch(() => {
      //     this.$message.info('已取消删除')
      //   })
    },
    // 关闭权限抽屉
    handleOnClose() {
      this.permissionDrawer.visible = false
      this.resetPermissionForm()
      if (this.menuTreeRef) {
        this.menuTreeRef.setCheckedKeys([])
      }
    },
    // 选中状态变化时的处理
    handleCheckChange(data, { checkedKeys }) {
      this.checkedKeys = checkedKeys
    },
    // 修改权限
    handleOnSave() {
      const menuRoles = this.checkedKeys
        .filter(menuId => menuId !== '' && menuId !== null)
        .map(menuId => ({ menuId }))
      const requestData = {
        id: this.roleMenuForm.id,
        sysMenuRoleDTOs: menuRoles,
        roleCode: this.roleMenuForm.roleCode
      }

      updateRole(requestData).then(() => {
        this.$message.success(this.isEdit ? '修改成功' : '添加成功')
        this.permissionDrawer.visible = false
        this.resetPermissionForm()
      })
    },
    resetPermissionForm() {
      this.roleMenuForm = {
        id: '',
        sysMenuRoleDTOs: []
      }
      this.defaultCheckedKeys = []
      this.checkedKeys = []
    }
  }
}
</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>
