<template>
  <div class="table-box">
    <ProTable ref="proTable" :config="config" :api="getRolePage">
      <template #left_buttons>
        <el-button type="primary" :icon="Plus" @click="roleModalRef?.openModal()">新增</el-button>
        <el-button type="danger" :icon="Delete" @click="onDelete">删除</el-button>
      </template>
    </ProTable>

    <RoleFormModal ref="roleModalRef" @success="query" />
  </div>
</template>

<script setup lang="jsx" name="roleManage">
  import { ref, reactive, onMounted } from 'vue';
  import { Plus, Delete, Edit, Setting } from '@element-plus/icons-vue';
  import { getRolePage, deleteRoles } from '@/api/role';
  import RoleFormModal from './components/RoleFormModal.vue';
  import { ElMessageBox, ElMessage, ElButton } from 'element-plus';

  const proTable = ref(null);
  const roleModalRef = ref(null);
  const config = reactive({
    columns: [
      { type: 'checkbox', width: 50 },
      { field: 'roleName', title: '角色名称', search: { el: 'input' } },
      { field: 'roleCode', title: '角色编码', search: { el: 'input' } },
      { field: 'roleDesc', title: '角色描述', search: { el: 'input' } },
      {
        width: 280,
        title: '操作',
        slots: {
          default: ({ row }) => (
            <>
              <ElButton type="primary" link icon={Edit} onClick={() => handleEdit(row)}>
                编辑
              </ElButton>
              <ElButton type="primary" link icon={Setting}>
                设置权限
              </ElButton>
              <ElButton type="primary" link icon={Setting}>
                设置成员
              </ElButton>
            </>
          ),
        },
      },
    ],
  });

  const query = () => proTable.value?.search();
  const handleEdit = (row) => roleModalRef.value.openModal(JSON.parse(JSON.stringify(row)));
  const onDelete = async () => {
    const list = proTable.value.element.getCheckboxRecords();
    if (list.length > 0) {
      await ElMessageBox.confirm('是否确认删除选中的数据？', '删除提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      });

      const ids = list.map((v) => v.id).join(',');
      await deleteRoles(ids);

      ElMessage.success({
        message: '删除成功',
        plain: true,
      });

      query();
    }
  };

  onMounted(() => {
    query();
  });
</script>
