package cn.iocoder.yudao.module.system.controller.admin.project;

import cn.hutool.core.collection.CollectionUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.datapermission.core.annotation.DataPermission;
import cn.iocoder.yudao.module.system.controller.admin.project.vo.ProjectPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.project.vo.ProjectRespVO;
import cn.iocoder.yudao.module.system.controller.admin.project.vo.ProjectSaveReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.dept.DeptDO;
import cn.iocoder.yudao.module.system.dal.dataobject.project.ProjectDO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.service.dept.DeptService;
import cn.iocoder.yudao.module.system.service.project.ProjectService;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertMap;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

@Tag(name = "管理后台 - 项目管理")
@RestController
@RequestMapping("/system/project")
@Validated
public class ProjectController {

    @Resource
    private ProjectService projectService;

    @Resource
    private AdminUserService userService;

    @Resource
    private DeptService deptService;

    @PostMapping("/create")
    @Operation(summary = "创建项目管理")
    @PreAuthorize("@ss.hasPermission('system:project:create')")
    public CommonResult<Long> createProject(@Valid @RequestBody ProjectSaveReqVO createReqVO) {
        return success(projectService.createProject(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新项目管理")
    @PreAuthorize("@ss.hasPermission('system:project:update')")
    public CommonResult<Boolean> updateProject(@Valid @RequestBody ProjectSaveReqVO updateReqVO) {
        projectService.updateProject(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除项目管理")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('system:project:delete')")
    public CommonResult<Boolean> deleteProject(@RequestParam("id") Long id) {
        projectService.deleteProject(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得项目管理")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('system:project:query')")
    public CommonResult<ProjectRespVO> getProject(@RequestParam("id") Long id) {
        ProjectDO project = projectService.getProject(id);
        ProjectRespVO respVO = BeanUtils.toBean(project, ProjectRespVO.class);
//        if (respVO != null) {
//            // 获取项目中所有人员的用户编号列表
//            Set<Long> userIds = respVO.getStaff() == null ? new HashSet<>() : respVO.getStaff();
//            userIds.add(respVO.getDirectorUserId());
//
//            // 获取项目中所有部门编号列表
//            Set<Long> deptIds = respVO.getParticipationDept() == null ? new HashSet<>() : respVO.getParticipationDept();
//            deptIds.add(respVO.getResponsibleDept());
//
//            // 获取所有用户信息
//            Map<Long, AdminUserDO> userMap = userService.getUserMap(userIds);
//            // 获取所有部门信息
//            Map<Long, DeptDO> deptMap = deptService.getDeptMap(deptIds);
//
//            // 设置责任人名称
//            respVO.setDirectorUserName(userMap.get(respVO.getDirectorUserId()).getNickname());
//            // 拼接项目人员名称
//            userMap.remove(respVO.getDirectorUserId());
//            respVO.setStaffName(userMap.values().stream().map(AdminUserDO::getNickname).collect(Collectors.joining("、")));
//
//            // 设置责任部门名称
//            respVO.setResponsibleDeptName(deptMap.get(respVO.getResponsibleDept()).getName());
//            // 拼接参与部门名称
//            deptMap.remove(respVO.getResponsibleDept());
//            respVO.setParticipationDeptName(deptMap.values().stream().map(DeptDO::getName).collect(Collectors.joining("、")));
//        }

        return success(respVO);
    }

    @GetMapping("/page")
    @Operation(summary = "获得项目管理分页")
    @PreAuthorize("@ss.hasPermission('system:project:query')")
    @DataPermission(enable = false)
    public CommonResult<PageResult<ProjectRespVO>> getProjectPage(@Valid ProjectPageReqVO pageReqVO) {
        PageResult<ProjectDO> pageResult = projectService.getProjectPage(pageReqVO);
        PageResult<ProjectRespVO> respVOs = BeanUtils.toBean(pageResult, ProjectRespVO.class);

        if (CollectionUtil.isNotEmpty(respVOs.getList())) {
            // 获取项目中所有人员的用户编号列表
            List<Long> userIds = respVOs.getList().stream()
                    .filter(item -> Objects.nonNull(item.getStaff()))
                    .flatMap(item -> item.getStaff().stream())
                    .collect(Collectors.toList());
            userIds.addAll(convertList(respVOs.getList(), ProjectRespVO::getDirectorUserId));

            // 获取项目中所有部门编号列表
            List<Long> deptIds = respVOs.getList().stream()
                    .filter(item -> Objects.nonNull(item.getParticipationDept()))
                    .flatMap(item -> item.getParticipationDept().stream())
                    .collect(Collectors.toList());
            deptIds.addAll(convertList(respVOs.getList(), ProjectRespVO::getResponsibleDept));

            // 获取所有用户信息
            List<AdminUserDO> userDOS = userService.getUserList(userIds);
            Map<Long, AdminUserDO> userMap = convertMap(userDOS, AdminUserDO::getId);
            // 获取所有部门信息
            List<DeptDO> deptDOS = deptService.getDeptList(deptIds);
            Map<Long, DeptDO> deptMap = convertMap(deptDOS, DeptDO::getId);
            respVOs.getList().forEach(item -> {
                // 筛选出不是责任人的用户信息
                List<AdminUserDO> userVOs = userDOS.stream()
                        .filter(user -> !user.getId().equals(item.getDirectorUserId()))
                        .distinct()
                        .collect(Collectors.toList());

                // 设置责任人名称
                item.setDirectorUserName(userMap.get(item.getDirectorUserId()).getNickname());
                // 拼接项目人员名称
                if (item.getStaff() != null) {
                    item.setStaffName(userVOs.stream()
                        .filter(user -> item.getStaff().contains(user.getId()))
                        .map(AdminUserDO::getNickname)
                        .collect(Collectors.joining("、")));

                }

                // 筛选出不是责任人部门的部门信息
                List<DeptDO> deptVOs = deptDOS.stream()
                        .filter(dept -> !dept.getId().equals(item.getResponsibleDept()))
                        .distinct()
                        .collect(Collectors.toList());

                // 设置责任部门名称
                item.setResponsibleDeptName(deptMap.get(item.getResponsibleDept()).getName());
                // 拼接参与部门名称
                item.setParticipationDeptName(deptVOs.stream().map(DeptDO::getName).collect(Collectors.joining("、")));
            });
        }

        return success(respVOs);
    }

    @GetMapping("/get-my-project")
    @Operation(summary = "获得我参与的项目")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
//    @PreAuthorize("@ss.hasPermission('system:project:query')")
    public CommonResult<List<ProjectRespVO>> getMyProject() {
        List<ProjectDO> projectList = projectService.getMyProject(getLoginUserId());
        return success(BeanUtils.toBean(projectList, ProjectRespVO.class));
    }
}