package com.yimeng.okr.controller;

import com.yimeng.okr.dto.ApiResult;
import com.yimeng.okr.annotation.OperationLogAnnotation;
import com.yimeng.okr.dto.DepartmentTreeNode;
import com.yimeng.okr.dto.UserInfo;
import com.yimeng.okr.entity.SysDepartment;
import com.yimeng.okr.enums.UserRole;
import com.yimeng.okr.exception.BusinessException;
import com.yimeng.okr.security.SecurityUtils;
import com.yimeng.okr.service.OrganizationService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

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

@RestController
@RequestMapping("/api/org")
@RequiredArgsConstructor
public class OrganizationController {

    private final OrganizationService organizationService;

    @GetMapping("/departments/tree")
    public ApiResult<List<DepartmentTreeNode>> getTree() {
        return ApiResult.success(organizationService.getDepartmentTree());
    }

    @PostMapping("/departments")
    @OperationLogAnnotation(action = "CREATE_DEPARTMENT", entityType = "sys_department")
    public ApiResult<SysDepartment> createDepartment(@RequestBody SysDepartment dept) {
        if (!SecurityUtils.hasRole(UserRole.HR_ADMIN)) {
            throw new BusinessException(403, "无权限，需要HR管理员或以上权限");
        }
        return ApiResult.success(organizationService.createDepartment(dept));
    }

    @PutMapping("/departments/{id}")
    @OperationLogAnnotation(action = "UPDATE_DEPARTMENT", entityType = "sys_department")
    public ApiResult<Void> updateDepartment(@PathVariable Long id, @RequestBody SysDepartment dept) {
        if (!SecurityUtils.hasRole(UserRole.HR_ADMIN)) {
            throw new BusinessException(403, "无权限，需要HR管理员或以上权限");
        }
        dept.setId(id);
        organizationService.updateDepartment(dept);
        return ApiResult.success();
    }

    @DeleteMapping("/departments/{id}")
    @OperationLogAnnotation(action = "DELETE_DEPARTMENT", entityType = "sys_department")
    public ApiResult<Void> deleteDepartment(@PathVariable Long id) {
        if (!SecurityUtils.hasRole(UserRole.HR_ADMIN)) {
            throw new BusinessException(403, "无权限，需要HR管理员或以上权限");
        }
        organizationService.deleteDepartment(id);
        return ApiResult.success();
    }

    @GetMapping("/departments/{id}/members")
    public ApiResult<List<UserInfo>> getMembers(@PathVariable Long id) {
        return ApiResult.success(organizationService.getDepartmentMembers(id, SecurityUtils.getCurrentUserId()));
    }

    @GetMapping("/users")
    public ApiResult<List<UserInfo>> getAllUsers() {
        return ApiResult.success(organizationService.getAllUsers(SecurityUtils.getCurrentUserId()));
    }

    @GetMapping("/users/superiors")
    public ApiResult<List<UserInfo>> getAvailableSuperiors() {
        return ApiResult.success(organizationService.getAvailableSuperiors(SecurityUtils.getCurrentUserId()));
    }

    @PutMapping("/users/{id}/superior")
    @OperationLogAnnotation(action = "UPDATE_USER_SUPERIOR", entityType = "sys_user")
    public ApiResult<Void> updateSuperior(@PathVariable Long id, @RequestBody Map<String, Long> body) {
        if (!SecurityUtils.hasRole(UserRole.HR_ADMIN)) {
            throw new BusinessException(403, "无权限，需要HR管理员或以上权限");
        }
        organizationService.updateUserSuperior(id, body.get("superiorId"));
        return ApiResult.success();
    }

    @PutMapping("/users/{id}/department")
    @OperationLogAnnotation(action = "UPDATE_USER_DEPARTMENT", entityType = "sys_user")
    public ApiResult<Void> updateDepartment(@PathVariable Long id, @RequestBody Map<String, Long> body) {
        if (!SecurityUtils.hasRole(UserRole.HR_ADMIN)) {
            throw new BusinessException(403, "无权限，需要HR管理员或以上权限");
        }
        organizationService.updateUserDepartment(id, body.get("departmentId"));
        return ApiResult.success();
    }

    @PutMapping("/users/{id}/position")
    @OperationLogAnnotation(action = "UPDATE_USER_POSITION", entityType = "sys_user")
    public ApiResult<Void> updatePosition(@PathVariable Long id, @RequestBody Map<String, String> body) {
        if (!SecurityUtils.hasRole(UserRole.HR_ADMIN)) {
            throw new BusinessException(403, "无权限，需要HR管理员或以上权限");
        }
        organizationService.updateUserPosition(id, body.get("position"));
        return ApiResult.success();
    }

    @GetMapping("/users/my-subordinates")
    public ApiResult<List<UserInfo>> getMySubordinates() {
        Long userId = SecurityUtils.getCurrentUserId();
        return ApiResult.success(organizationService.getSubordinates(userId));
    }

    @PostMapping("/users")
    @OperationLogAnnotation(action = "CREATE_USER", entityType = "sys_user")
    public ApiResult<UserInfo> createUser(@RequestBody Map<String, Object> body) {
        if (!SecurityUtils.hasRole(UserRole.HR_ADMIN)) {
            throw new BusinessException(403, "无权限，需要HR管理员或以上权限");
        }
        return ApiResult.success(organizationService.createUser(body));
    }

    @PutMapping("/users/{id}")
    @OperationLogAnnotation(action = "UPDATE_USER", entityType = "sys_user")
    public ApiResult<Void> updateUser(@PathVariable Long id, @RequestBody Map<String, Object> body) {
        if (!SecurityUtils.hasRole(UserRole.HR_ADMIN)) {
            throw new BusinessException(403, "无权限，需要HR管理员或以上权限");
        }
        organizationService.updateUser(id, body);
        return ApiResult.success();
    }

    @DeleteMapping("/users/{id}")
    @OperationLogAnnotation(action = "DELETE_USER", entityType = "sys_user")
    public ApiResult<Void> deleteUser(@PathVariable Long id) {
        if (!SecurityUtils.hasRole(UserRole.HR_ADMIN)) {
            throw new BusinessException(403, "无权限，需要HR管理员或以上权限");
        }
        organizationService.deleteUser(id);
        return ApiResult.success();
    }

    @PutMapping("/users/{id}/disable")
    @OperationLogAnnotation(action = "DISABLE_USER", entityType = "sys_user")
    public ApiResult<Void> disableUser(@PathVariable Long id) {
        if (!SecurityUtils.hasRole(UserRole.HR_ADMIN)) {
            throw new BusinessException(403, "无权限，需要HR管理员或以上权限");
        }
        organizationService.disableUser(id);
        return ApiResult.success();
    }

    @PutMapping("/users/{id}/leave")
    @OperationLogAnnotation(action = "MARK_USER_LEFT", entityType = "sys_user")
    public ApiResult<Void> markUserLeft(@PathVariable Long id) {
        if (!SecurityUtils.hasRole(UserRole.HR_ADMIN)) {
            throw new BusinessException(403, "无权限，需要HR管理员或以上权限");
        }
        organizationService.markUserLeft(id);
        return ApiResult.success();
    }

    @PostMapping("/init-seed")
    @OperationLogAnnotation(action = "INIT_SEED_DATA", entityType = "sys_department")
    public ApiResult<Void> initSeedData() {
        if (!SecurityUtils.hasRole(UserRole.HR_ADMIN)) {
            throw new BusinessException(403, "无权限，需要HR管理员或以上权限");
        }
        organizationService.initSeedData();
        return ApiResult.success();
    }
}
