<template>
  <div class="page-container">
    <div class="page-header">
      <PageTitle title="角色管理" />
      <!-- <el-button type="danger" @click="handleAdd">新增角色</el-button> -->
    </div>

    <el-table :data="paginatedRoleList" border>
      <el-table-column prop="roleName" label="角色名称" min-width="150" align="center" />
      <el-table-column prop="roleSort" label="显示顺序" width="100" align="center" />
      <el-table-column prop="status" label="状态" width="100" align="center">
        <template #default="{ row }">
          <span :style="{ color: row.status === '0' ? '#67c23a' : '#999' }">
            {{ row.status === '0' ? '正常' : '停用' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" align="center" />
      <el-table-column prop="remark" label="备注" min-width="150" align="center" show-overflow-tooltip />
      <el-table-column label="操作" width="150" align="center" fixed="right">
        <template #default="{ row }">
          <!-- <el-button type="primary" link size="small" @click="handleEdit(row)">编辑</el-button> -->
          <el-button disabled type="danger" link size="small" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[10, 20, 50, 100]"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      style="margin-top: 20px; justify-content: flex-end"
    />

    <!-- 新增/编辑角色弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px" destroy-on-close>
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="formData.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="显示顺序" prop="roleSort">
          <el-input-number v-model="formData.roleSort" :min="0" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="formData.status">
            <el-radio label="0">正常</el-radio>
            <el-radio label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="formData.remark" type="textarea" :rows="3" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="danger" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { PageTitle } from '@/components';
import { getRoleList, addRole, updateRole, deleteRole } from '@/api/pc/organization';
import { create } from 'domain';

const roleList = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const dialogVisible = ref(false);
const formRef = ref();
const editingRow = ref<any>(null);

const formData = reactive({
  roleId: undefined,
  roleName: '',
  roleKey: '',
  roleSort: 0,
  status: '0',
  remark: ''
});

const formRules = {
  roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }]
};

const total = computed(() => roleList.value.length);
const dialogTitle = computed(() => (editingRow.value ? '编辑角色' : '新增角色'));

const paginatedRoleList = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return roleList.value.slice(start, end);
});

const loadRoleList = async () => {
  try {
    // const res = await getRoleList();
    // if (res.code === 200 && res.data) {
    //   roleList.value = res.data;
    // }
    roleList.value = [
      { roleId: 1, roleName: '管理角色', roleSort: 1, status: '0', createTime: '2026-01-27 09:36:27' },
      { roleId: 2, roleName: '采购角色', roleSort: 2, status: '0', createTime: '2026-01-27 09:36:38' },
      { roleId: 3, roleName: '查询角色', roleSort: 3, status: '0', createTime: '2026-01-27 09:37:33' },
      { roleId: 4, roleName: '审核角色', roleSort: 4, status: '0', createTime: '2026-01-27 09:37:50' }
    ];
  } catch (error) {
    console.error('获取角色列表失败:', error);
    ElMessage.error('获取角色列表失败');
  }
};

const handleSizeChange = (val: number) => {
  pageSize.value = val;
  currentPage.value = 1;
};

const handleCurrentChange = (val: number) => {
  currentPage.value = val;
};

const handleAdd = () => {
  editingRow.value = null;
  Object.assign(formData, {
    roleId: undefined,
    roleName: '',
    roleKey: '',
    roleSort: 0,
    status: '0',
    remark: ''
  });
  dialogVisible.value = true;
};

const handleEdit = (row: any) => {
  editingRow.value = row;
  Object.assign(formData, {
    roleId: row.roleId,
    roleName: row.roleName,
    roleKey: row.roleKey,
    roleSort: row.roleSort,
    status: row.status,
    remark: row.remark
  });
  dialogVisible.value = true;
};

const handleSubmit = async () => {
  const valid = await formRef.value?.validate();
  if (!valid) return;

  try {
    if (editingRow.value) {
      await updateRole(formData);
      ElMessage.success('编辑成功');
    } else {
      await addRole(formData);
      ElMessage.success('新增成功');
    }
    dialogVisible.value = false;
    await loadRoleList();
  } catch (error) {
    console.error('操作失败:', error);
    ElMessage.error('操作失败');
  }
};

const handleDelete = (row: any) => {
  ElMessageBox.confirm(`确定要删除角色"${row.roleName}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteRole([row.roleId]);
      ElMessage.success('删除成功');
      await loadRoleList();
    } catch (error) {
      console.error('删除失败:', error);
      ElMessage.error('删除失败');
    }
  });
};

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

<style scoped lang="scss">
.page-container {
  padding: 20px;
  background: #fff;
  min-height: 100%;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

  :deep(.page-title) {
    margin-bottom: 0;
  }
}

:deep(.el-table) {
  th.el-table__cell {
    background: #fafafa;
    font-weight: 500;
    color: #333;
  }
}
</style>
