<template>
  <div class="page-container">
    <a-card class="box-card" :bordered="false">
      <!-- Search Form -->
      <div class="search-form">
        <a-form :model="queryParams" layout="inline">
          <a-form-item field="name" label="角色名称">
            <a-input v-model="queryParams.name" placeholder="输入角色名称" allow-clear />
          </a-form-item>
          <a-form-item field="status" label="状态">
            <a-select v-model="queryParams.status" placeholder="全部" allow-clear style="width: 120px">
              <a-option value="0">正常</a-option>
              <a-option value="1">禁用</a-option>
            </a-select>
          </a-form-item>
          <a-form-item>
            <a-button type="primary" @click="handleQuery">
              <template #icon><icon-search /></template>
              搜索
            </a-button>
            <a-button @click="resetQuery" style="margin-left: 10px">
              <template #icon><icon-refresh /></template>
              重置
            </a-button>
            <a-button type="primary" @click="handleAddRole" v-hasPermi="['system:role:add']" style="margin-left: 10px">
              <template #icon><icon-plus /></template>
              新增角色
            </a-button>
          </a-form-item>
        </a-form>
      </div>
      
      <!-- Table -->
      <a-table 
        :data="roles" 
        style="margin-top: 15px" 
        :pagination="pagination" 
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
        :loading="loading"
      >
        <template #columns>
          <a-table-column title="角色名称" data-index="Name" :width="150" />
          <a-table-column title="菜单权限" data-index="MenuNames" ellipsis tooltip />
          <a-table-column title="状态" data-index="Status" :width="100">
             <template #cell="{ record }">
               <a-tag :color="record.Status === '0' ? 'green' : 'red'">
                 {{ record.Status === '0' ? '正常' : '禁用' }}
               </a-tag>
             </template>
          </a-table-column>
          <a-table-column title="操作" :width="200" align="center">
            <template #cell="{ record }">
              <a-space>
                <a-button size="small" type="text" @click="handleEditRole(record)" v-hasPermi="['system:role:edit']">
                   <template #icon><icon-edit /></template> 编辑
                </a-button>
                <a-button size="small" type="text" status="danger" @click="handleDeleteRole(record)" v-hasPermi="['system:role:remove']">
                   <template #icon><icon-delete /></template> 删除
                </a-button>
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>

    <!-- Dialog: Role -->
    <a-modal v-model:visible="roleDialog.visible" :title="roleDialog.isEdit ? '编辑角色' : '新增角色'" @ok="submitRole" @cancel="roleDialog.visible = false">
      <a-form :model="roleForm" layout="vertical">
        <a-form-item field="Name" label="角色名称" required>
          <a-input v-model="roleForm.Name" allow-clear />
        </a-form-item>
         <a-form-item field="Status" label="状态">
          <a-radio-group v-model="roleForm.Status">
            <a-radio value="0">正常</a-radio>
            <a-radio value="1">禁用</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item field="MenuIds" label="菜单权限">
             <a-tree
                ref="menuTreeRef"
                :data="menuOptions"
                checkable
                v-model:checked-keys="checkedKeys"
                v-model:half-checked-keys="halfCheckedKeys"
                :field-names="{ key: 'id', title: 'name', children: 'children' }"
            />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { IconSearch, IconRefresh, IconPlus, IconEdit, IconDelete } from '@arco-design/web-vue/es/icon';
import { Message, Modal } from '@arco-design/web-vue';
import * as sysApi from '../../api/system';

// --- State ---
const loading = ref(false);
const roles = ref<any[]>([]);
const menuOptions = ref<any[]>([]);
const checkedKeys = ref<string[]>([]);
const halfCheckedKeys = ref<string[]>([]);

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: '',
  roleKey: '',
  status: ''
});

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showTotal: true,
  showPageSize: true
});

const roleDialog = reactive({ visible: false, isEdit: false });
const roleForm = reactive<any>({ Name: '', RoleKey: '', DataScope: '1', Status: '0' });

// --- Lifecycle ---
onMounted(() => {
  loadRoles();
  loadMenuTree();
});

// --- Methods ---
const filterMenuTree = (menus: any[]) => {
  return menus.filter(node => {
     // If type is 'F' (Button), remove it
     if (node.type === 'F') return false;
     
     // Recursively filter children
     if (node.children && node.children.length > 0) {
       node.children = filterMenuTree(node.children);
     }
     return true;
  });
};

const loadRoles = async () => {
  loading.value = true;
  try {
    // Call API with query params
    const params = {
      pageNum: queryParams.pageNum,
      pageSize: queryParams.pageSize,
      name: queryParams.name,
      roleKey: queryParams.roleKey,
      status: queryParams.status
    };
    
    const res: any = await sysApi.getRoles(params);
    
    // Check if res has rows/total (New API format) or is array (Old API format fallback)
    if (res.rows) {
      roles.value = res.rows;
      pagination.total = res.total;
      pagination.current = queryParams.pageNum;
    } else if (Array.isArray(res)) {
      roles.value = res;
      pagination.total = res.length; // Fake total if no pagination
    }
  } catch (error) {
    console.error(error);
  } finally {
    loading.value = false;
  }
};

const loadMenuTree = async () => {
    const res: any = await sysApi.getMenuTree();
    // Filter out buttons (Type 'F')
    menuOptions.value = filterMenuTree(res); 
};

const handleQuery = () => {
  queryParams.pageNum = 1;
  loadRoles();
};

const resetQuery = () => {
  queryParams.name = '';
  queryParams.roleKey = '';
  queryParams.status = '';
  handleQuery();
};

const onPageChange = (current: number) => {
  queryParams.pageNum = current;
  loadRoles();
};

const onPageSizeChange = (pageSize: number) => {
  queryParams.pageSize = pageSize;
  queryParams.pageNum = 1;
  loadRoles();
};


// --- Role Actions ---
const handleAddRole = () => {
  roleDialog.isEdit = false;
  Object.assign(roleForm, { Name: '', RoleKey: '', DataScope: '1', Status: '0' });
  checkedKeys.value = [];
  halfCheckedKeys.value = [];
  roleDialog.visible = true;
};

const handleEditRole = async (row: any) => {
  roleDialog.isEdit = true;
  Object.assign(roleForm, row);
  roleDialog.visible = true;
  
  // Load role menus
  const res: any = await sysApi.getRoleMenuIds(row.ID);
  const menuIds = res || [];
  checkedKeys.value = menuIds;
};

const handleDeleteRole = (row: any) => {
   Modal.confirm({
    title: '提示',
    content: '确定删除该角色吗?',
    onOk: async () => {
      await sysApi.deleteRole(row.ID);
      Message.success('删除成功');
      loadRoles();
    }
  });
};

const submitRole = async () => {
  const data = { ...roleForm };
  data.MenuIds = [...checkedKeys.value, ...halfCheckedKeys.value];
  
  // Auto-generate RoleKey if empty (since we hid the input)
  // Simple unique key: 'role_' + timestamp
  if (!data.RoleKey) {
     data.RoleKey = 'role_' + new Date().getTime();
  }

  if (roleDialog.isEdit) {
    await sysApi.updateRole(roleForm.ID, data);
    Message.success('更新成功');
  } else {
    await sysApi.createRole(data);
    Message.success('创建成功');
  }
  roleDialog.visible = false;
  loadRoles();
};
</script>

<style scoped>
.page-container {
  padding: 20px;
}
.search-form {
  margin-bottom: 20px;
}
</style>

