<template>
  <div class="role-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <div class="search-section">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索角色名称或标识"
              clearable
              style="width: 300px"
              @clear="handleSearch"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-button
              type="primary"
              @click="handleSearch"
            >
              搜索
            </el-button>
          </div>
          <el-button
            type="primary"
            @click="handleAdd"
          >
            新增角色
          </el-button>
        </div>
      </template>
      <el-table
        v-loading="loading"
        :data="dataSource"
        style="width: 100%"
        @sort-change="handleSortChange"
      >
        <el-table-column
          prop="id"
          label="ID"
          width="80"
          sortable="custom"
        />
        <el-table-column
          prop="roleName"
          label="角色名称"
          sortable="custom"
        />
        <el-table-column
          prop="roleKey"
          label="角色标识"
          sortable="custom"
        />
        <el-table-column
          prop="roleSort"
          label="显示顺序"
          sortable="custom"
        />
        <el-table-column
          label="状态"
          width="100"
        >
          <template #default="{ row }">
            <el-tag 
              :type="row.status === RoleStatus.ACTIVE ? 'success' : 'danger'"
              effect="dark"
              style="font-weight: 500; font-size: 14px;"
            >
              {{ row.status === RoleStatus.ACTIVE ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="createdAt"
          label="创建时间"
          sortable="custom"
        >
          <template #default="{ row }">
            {{ formatDateTime(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="250"
        >
          <template #default="{ row }">
            <el-button
              type="primary"
              link
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              type="warning"
              link
              @click="handleAssignPermissions(row)"
            >
              分配权限
            </el-button>
            <el-button
              type="danger"
              link
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        style="margin-top: 16px; justify-content: flex-end"
        @current-change="handleTableChange"
        @size-change="handleSizeChange"
      />
    </el-card>

    <el-dialog
      v-model="modalVisible"
      :title="modalTitle"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="formState"
        :rules="formRules"
        label-width="80px"
      >
        <el-form-item
          label="角色名称"
          prop="roleName"
          required
        >
          <el-input v-model="formState.roleName" />
        </el-form-item>
        <el-form-item
          label="角色标识"
          prop="roleKey"
          required
        >
          <el-input
            v-model="formState.roleKey"
            :disabled="!!formState.id"
          />
        </el-form-item>
        <el-form-item
          label="显示顺序"
          prop="roleSort"
          required
        >
          <el-input-number
            v-model="formState.roleSort"
            :min="1"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="formState.status">
            <el-option
              value="ACTIVE"
              label="正常"
            />
            <el-option
              value="INACTIVE"
              label="禁用"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="modalVisible = false">
          取消
        </el-button>
        <el-button
          type="primary"
          @click="handleModalOk"
        >
          确定
        </el-button>
      </template>
    </el-dialog>

    <el-dialog
      v-model="permissionDialogVisible"
      title="分配权限"
      width="600px"
    >
      <el-tree
        ref="permissionTreeRef"
        :data="permissionTree"
        :props="{ label: 'name', children: 'children' }"
        show-checkbox
        node-key="id"
        :default-checked-keys="selectedPermissions"
        check-strictly
      />
      <template #footer>
        <el-button @click="permissionDialogVisible = false">
          取消
        </el-button>
        <el-button
          type="primary"
          @click="handleAssignPermissionsOk"
        >
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { roleApi, type Role, type CreateRoleRequest, type UpdateRoleRequest, type Permission } from '@/api/role.api'
import { handleApiError } from '@/utils/errorHandler'
import { RoleStatus } from '@/constants/status'
import { formatDateTime } from '@/utils/dateFormat'

const loading = ref(false)
const dataSource = ref<Role[]>([])
const searchKeyword = ref('')
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
})

const sortInfo = reactive({
  sortBy: 'id',
  sortOrder: 'asc' as 'asc' | 'desc'
})

const modalVisible = ref(false)
const modalTitle = ref('')
const formRef = ref()
const formState = reactive<CreateRoleRequest & { id?: number; status?: RoleStatus }>({
  roleName: '',
  roleKey: '',
  roleSort: 1,
  permissions: [],
  status: RoleStatus.ACTIVE
})

const formRules = {
  roleName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 50, message: '角色名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  roleKey: [
    { required: true, message: '请输入角色标识', trigger: 'blur' },
    { min: 2, max: 50, message: '角色标识长度在 2 到 50 个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_-]+$/, message: '角色标识只能包含字母、数字、下划线和横线', trigger: 'blur' }
  ],
  roleSort: [
    { required: true, message: '请输入显示顺序', trigger: 'blur' },
    { type: 'number', min: 1, message: '显示顺序必须大于0', trigger: 'blur' }
  ]
}

const permissionDialogVisible = ref(false)
const permissionTreeRef = ref()
const permissionTree = ref<any[]>([])
const selectedPermissions = ref<number[]>([])
const currentRoleId = ref<number | null>(null)

const fetchData = async () => {
  loading.value = true
  try {
    const res = await roleApi.getPage({
      page: pagination.current - 1,
      size: pagination.pageSize,
      sortBy: sortInfo.sortBy,
      sortOrder: sortInfo.sortOrder,
      name: searchKeyword.value || undefined
    })
    dataSource.value = res.content
    pagination.total = res.totalElements
  } catch (error) {
    handleApiError(error)
  } finally {
    loading.value = false
  }
}

const handleTableChange = () => {
  fetchData()
}

const handleSizeChange = () => {
  pagination.current = 1
  fetchData()
}

const handleSearch = () => {
  pagination.current = 1
  fetchData()
}

const handleSortChange = ({ prop, order }: any) => {
  sortInfo.sortBy = prop
  sortInfo.sortOrder = order === 'ascending' ? 'asc' : 'desc'
  fetchData()
}

const handleAdd = () => {
  modalTitle.value = '新增角色'
  Object.assign(formState, {
    id: undefined,
    roleName: '',
    roleKey: '',
    roleSort: 1,
    permissions: [],
    status: RoleStatus.ACTIVE
  })
  modalVisible.value = true
}

const handleEdit = (row: Role) => {
  modalTitle.value = '编辑角色'
  Object.assign(formState, {
    id: row.id,
    roleName: row.roleName,
    roleKey: row.roleKey,
    roleSort: row.roleSort,
    status: row.status,
    permissions: []
  })
  modalVisible.value = true
}

const handleDelete = async (row: Role) => {
  try {
    await ElMessageBox.confirm('确定要删除该角色吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await roleApi.delete(row.id)
    ElMessage.success('删除成功')
    fetchData()
  } catch (error) {
    if (error !== 'cancel') {
      handleApiError(error)
    }
  }
}

const handleModalOk = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    if (formState.id) {
      const updateData: UpdateRoleRequest = {
        roleName: formState.roleName,
        roleKey: formState.roleKey,
        roleSort: formState.roleSort,
        status: formState.status
      }
      await roleApi.update(formState.id, updateData)
      ElMessage.success('更新成功')
    } else {
      const createData: CreateRoleRequest = {
        roleName: formState.roleName,
        roleKey: formState.roleKey,
        roleSort: formState.roleSort,
        permissions: formState.permissions
      }
      await roleApi.create(createData)
      ElMessage.success('创建成功')
    }
    modalVisible.value = false
    fetchData()
  } catch (error) {
    if (error !== 'cancel') {
      handleApiError(error)
    }
  }
}

const handleAssignPermissions = async (row: Role) => {
  currentRoleId.value = row.id
  try {
    const allPermissions = await roleApi.getAllPermissions()
    permissionTree.value = buildPermissionTree(allPermissions)
    
    const rolePermissions = await roleApi.getPermissions(row.id)
    selectedPermissions.value = rolePermissions.map((p: Permission) => p.id)
    
    permissionDialogVisible.value = true
  } catch (error) {
    handleApiError(error)
  }
}

const buildPermissionTree = (permissions: Permission[]): any[] => {
  const tree: any[] = []
  const resourceMap = new Map<string, Permission[]>()
  
  permissions.forEach(p => {
    if (!resourceMap.has(p.resource)) {
      resourceMap.set(p.resource, [])
    }
    resourceMap.get(p.resource)!.push(p)
  })
  
  resourceMap.forEach((perms, resource) => {
    tree.push({
      id: `resource-${resource}`,
      name: resource,
      children: perms.map(p => ({
        id: p.id,
        name: p.name
      }))
    })
  })
  
  return tree
}

const handleAssignPermissionsOk = async () => {
  if (!currentRoleId.value) return
  
  try {
    const checkedNodes = permissionTreeRef.value.getCheckedNodes()
    const permissionIds = checkedNodes
      .filter((node: any) => typeof node.id === 'number')
      .map((node: any) => node.id)
    
    await roleApi.assignPermissions(currentRoleId.value, permissionIds)
    ElMessage.success('权限分配成功')
    permissionDialogVisible.value = false
    fetchData()
  } catch (error) {
    handleApiError(error)
  }
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped lang="css">
.role-management {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 16px;

    .search-section {
      display: flex;
      gap: 8px;
      align-items: center;
    }
  }
}
</style>
