package com.mosquito.project.permission;

import com.mosquito.project.dto.ApiResponse;
import com.mosquito.project.service.AuditService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 角色管理Controller - 角色CRUD API
 */
@RestController
@RequestMapping("/api/v1/roles")
public class RoleController {

    private final RoleService roleService;
    private final ApprovalFlowService approvalFlowService;
    private final AuditService auditService;

    // 业务类型常量
    private static final String BIZ_TYPE_ROLE_CREATE = "ROLE_CREATE";
    private static final String BIZ_TYPE_ROLE_UPDATE = "ROLE_UPDATE";
    private static final String BIZ_TYPE_ROLE_DELETE = "ROLE_DELETE";

    public RoleController(RoleService roleService, ApprovalFlowService approvalFlowService, AuditService auditService) {
        this.roleService = roleService;
        this.approvalFlowService = approvalFlowService;
        this.auditService = auditService;
    }

    /**
     * 获取当前用户ID，优先从request attribute获取（与UserAuthInterceptor一致）
     */
    private Long getCurrentUserId(HttpServletRequest request) {
        // 优先从request attribute获取（由UserAuthInterceptor设置）
        Object userIdAttr = request.getAttribute("userId");
        if (userIdAttr != null) {
            if (userIdAttr instanceof Long) {
                return (Long) userIdAttr;
            } else if (userIdAttr instanceof Number) {
                return ((Number) userIdAttr).longValue();
            } else {
                try {
                    return Long.parseLong(userIdAttr.toString());
                } catch (NumberFormatException e) {
                    return null;
                }
            }
        }
        // 备用：从header获取
        String userIdStr = request.getHeader("X-User-Id");
        if (userIdStr != null && !userIdStr.isEmpty()) {
            try {
                return Long.parseLong(userIdStr);
            } catch (NumberFormatException e) {
                return null;
            }
        }
        return null;
    }

    /**
     * 获取角色列表
     */
    @GetMapping
    @RequirePermission("role.index.view.ALL")
    public ApiResponse<List<SysRole>> list() {
        return ApiResponse.success(roleService.findAll());
    }

    /**
     * 根据ID获取角色
     */
    @GetMapping("/{id}")
    @RequirePermission("role.index.view.ALL")
    public ApiResponse<SysRole> getById(@PathVariable Long id) {
        return roleService.findById(id)
                .map(role -> ApiResponse.success(role))
                .orElse(ApiResponse.error(404, "角色不存在"));
    }

    /**
     * 根据角色代码获取角色
     */
    @GetMapping("/code/{roleCode}")
    @RequirePermission("role.index.view.ALL")
    public ApiResponse<SysRole> getByRoleCode(@PathVariable String roleCode) {
        return roleService.findByRoleCode(roleCode)
                .map(role -> ApiResponse.success(role))
                .orElse(ApiResponse.error(404, "角色不存在"));
    }

    /**
     * 创建角色（需要审批）
     */
    @PostMapping
    @RequirePermission("role.index.manage.ALL")
    public ApiResponse<Map<String, Object>> create(@RequestBody SysRole role, HttpServletRequest request) {
        Long currentUserId = getCurrentUserId(request);

        if (currentUserId == null) {
            return ApiResponse.error(401, "无法获取当前用户信息");
        }

        try {
            // 构建完整的业务数据，包含审批回调所需的全部字段
            Map<String, Object> bizDataMap = new HashMap<>();
            bizDataMap.put("roleName", role.getRoleName());
            bizDataMap.put("roleCode", role.getRoleCode());
            bizDataMap.put("roleLevel", role.getRoleLevel());
            bizDataMap.put("dataScope", role.getDataScope());
            bizDataMap.put("description", role.getDescription());
            bizDataMap.put("status", role.getStatus());

            String bizData = new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(bizDataMap);

            Map<String, Object> approvalResult = approvalFlowService.submitApprovalByEvent(
                "ROLE_CREATE",
                BIZ_TYPE_ROLE_CREATE,
                0L,
                "角色创建审批: " + role.getRoleName(),
                currentUserId,
                "申请创建角色: " + role.getRoleName(),
                bizData
            );

            Map<String, Object> result = new HashMap<>();
            result.put("recordId", approvalResult.get("recordId"));
            result.put("status", "PENDING_APPROVAL");
            result.put("message", "创建申请已提交审批，审批通过后角色将生效");

            return ApiResponse.success(result, "创建申请已提交审批");
        } catch (Exception e) {
            return ApiResponse.error(409, "审批服务异常，无法执行敏感操作");
        }
    }

    /**
     * 更新角色（需要审批）
     */
    @PutMapping("/{id}")
    @RequirePermission("role.index.manage.ALL")
    public ApiResponse<Map<String, Object>> update(@PathVariable Long id, @RequestBody SysRole role, HttpServletRequest request) {
        Long currentUserId = getCurrentUserId(request);

        // 先检查角色是否存在
        if (roleService.findById(id).isEmpty()) {
            return ApiResponse.error(404, "角色不存在");
        }

        if (currentUserId == null) {
            return ApiResponse.error(401, "无法获取当前用户信息");
        }

        try {
            // 构建完整的业务数据，包含审批回调所需的全部字段
            Map<String, Object> bizDataMap = new HashMap<>();
            bizDataMap.put("roleId", id);
            bizDataMap.put("roleName", role.getRoleName());
            bizDataMap.put("roleCode", role.getRoleCode());
            bizDataMap.put("roleLevel", role.getRoleLevel());
            bizDataMap.put("dataScope", role.getDataScope());
            bizDataMap.put("description", role.getDescription());
            bizDataMap.put("status", role.getStatus());

            String bizData = new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(bizDataMap);

            Map<String, Object> approvalResult = approvalFlowService.submitApprovalByEvent(
                "ROLE_UPDATE",
                BIZ_TYPE_ROLE_UPDATE,
                (long) id,
                "角色更新审批: " + id,
                currentUserId,
                "申请更新角色: " + id,
                bizData
            );

            Map<String, Object> result = new HashMap<>();
            result.put("recordId", approvalResult.get("recordId"));
            result.put("status", "PENDING_APPROVAL");
            result.put("message", "更新申请已提交审批，审批通过后角色将更新");

            return ApiResponse.success(result, "更新申请已提交审批");
        } catch (Exception e) {
            return ApiResponse.error(409, "审批服务异常，无法执行敏感操作");
        }
    }

    /**
     * 删除角色（需要审批）
     */
    @DeleteMapping("/{id}")
    @RequirePermission("role.index.manage.ALL")
    public ApiResponse<Map<String, Object>> delete(@PathVariable Long id, HttpServletRequest request) {
        Long currentUserId = getCurrentUserId(request);

        // 先检查角色是否存在
        if (roleService.findById(id).isEmpty()) {
            return ApiResponse.error(404, "角色不存在");
        }

        if (currentUserId == null) {
            return ApiResponse.error(401, "无法获取当前用户信息");
        }

        try {
            String bizData = String.format("{\"roleId\":%d}", id);

            Map<String, Object> approvalResult = approvalFlowService.submitApprovalByEvent(
                "ROLE_DELETE",
                BIZ_TYPE_ROLE_DELETE,
                (long) id,
                "角色删除审批: " + id,
                currentUserId,
                "申请删除角色: " + id,
                bizData
            );

            Map<String, Object> result = new HashMap<>();
            result.put("recordId", approvalResult.get("recordId"));
            result.put("status", "PENDING_APPROVAL");
            result.put("message", "删除申请已提交审批，审批通过后角色将被删除");

            return ApiResponse.success(result, "删除申请已提交审批");
        } catch (Exception e) {
            return ApiResponse.error(409, "审批服务异常，无法执行敏感操作");
        }
    }

    /**
     * 检查角色代码是否存在
     */
    @GetMapping("/exists/{roleCode}")
    @RequirePermission("role.index.view.ALL")
    public ApiResponse<Boolean> exists(@PathVariable String roleCode) {
        return ApiResponse.success(roleService.existsByRoleCode(roleCode));
    }

    /**
     * 获取角色权限ID列表
     */
    @GetMapping("/{roleId}/permissions")
    @RequirePermission("role.index.view.ALL")
    public ApiResponse<List<Long>> getRolePermissions(@PathVariable Long roleId) {
        // 检查角色是否存在
        if (roleService.findById(roleId).isEmpty()) {
            return ApiResponse.error(404, "角色不存在");
        }
        return ApiResponse.success(roleService.getRolePermissionIds(roleId));
    }

    /**
     * 分配权限给角色
     */
    @PostMapping("/{roleId}/permissions")
    @RequirePermission("role.index.manage.ALL")
    public ApiResponse<Void> assignPermissions(@PathVariable Long roleId, @RequestBody AssignPermissionsRequest request) {
        // 检查角色是否存在
        if (roleService.findById(roleId).isEmpty()) {
            return ApiResponse.error(404, "角色不存在");
        }
        roleService.assignPermissions(roleId, request.getPermissionIds());
        return ApiResponse.success(null, "权限分配成功");
    }

    /**
     * 分配权限请求体
     */
    public static class AssignPermissionsRequest {
        private List<Long> permissionIds;

        public List<Long> getPermissionIds() {
            return permissionIds;
        }

        public void setPermissionIds(List<Long> permissionIds) {
            this.permissionIds = permissionIds;
        }
    }
}
