package com.zcloud.domain.command.query;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.cola.dto.PageResponse;
import com.jjb.saas.framework.auth.utils.AuthContext;
import com.zcloud.domain.command.convertor.ProjectTaskCoConvertor;
import com.zcloud.domain.command.convertor.ProjectTaskGroupUserCoConvertor;
import com.zcloud.domain.command.convertor.ProjectTaskInfoCoConvertor;
import com.zcloud.domain.command.convertor.ProjectTaskScoreInfoCoConvertor;
import com.zcloud.domain.domain.model.CorpInfoE;
import com.zcloud.domain.dto.ProjectTaskPageQry;
import com.zcloud.domain.dto.clientobject.*;
import com.zcloud.domain.persistence.dataobject.ProjectTaskDO;
import com.zcloud.domain.persistence.dataobject.ProjectTaskGroupUserDO;
import com.zcloud.domain.persistence.dataobject.ProjectTaskInfoDO;
import com.zcloud.domain.persistence.dataobject.ProjectTaskScoreInfoDO;
import com.zcloud.domain.persistence.repository.*;
import com.zcloud.gbscommon.utils.PageQueryHelper;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;

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


/**
 * web-app
 *
 * @Author zhaokai
 * @Date 2026-01-29 11:28:41
 */
@Component
@AllArgsConstructor
public class ProjectTaskQueryExe {
    private final ProjectTaskRepository projectTaskRepository;
    private final ProjectTaskCoConvertor projectTaskCoConvertor;
    private final ProjectTaskInfoRepository projectTaskInfoRepository;
    private final ProjectTaskInfoCoConvertor projectTaskInfoCoConvertor;
    private final ProjectTaskScoreInfoRepository projectTaskScoreInfoRepository;
    private final ProjectTaskScoreInfoCoConvertor projectTaskScoreInfoCoConvertor;
    private final ProjectTaskGroupUserRepository projectTaskGroupUserRepository;
    private final ProjectTaskGroupUserCoConvertor projectTaskGroupUserCoConvertor;
    private final CorpInfoRepository corpInfoRepository;

    /**
     * 分页
     *
     * @param projectTaskPageQry
     * @return
     */
    public PageResponse<ProjectTaskCO> execute(ProjectTaskPageQry projectTaskPageQry) {
        Map<String, Object> params = PageQueryHelper.toHashMap(projectTaskPageQry);
        PageResponse<ProjectTaskDO> pageResponse = projectTaskRepository.listPage(params);
        List<ProjectTaskCO> examCenterCOS = projectTaskCoConvertor.converDOsToCOs(pageResponse.getData());


        /**
         *权限控制
         * 1. 股份端看所有数据，企业端只能执行单位是自己的数据
         * 2. 主账号可以修改企业下创建的所有数据，个人账号，只能修改自己创建的数据
         */
        examCenterCOS.forEach(info -> {
            //如果是企业，可以看本企业下所有的，如果是个人，只能看个人的，判断登录的账号是企业主账号还是个人
            Boolean isCorpAccount = corpInfoRepository.checkCorp();
            // 企业账户：检查租户ID匹配
            if ((isCorpAccount||(AuthContext.getRoleIds()!=null && AuthContext.getRoleIds().contains(2008483105201106946L)))&& AuthContext.getTenantId().equals(info.getTenantId())) {
                info.setIsUserCreate(true);
                return;
            }
            // 个人账户：检查创建者ID匹配
            if (!isCorpAccount && info.getCreateId().equals(AuthContext.getUserId())) {
                info.setIsUserCreate(true);
            }

            //只有组长和企业主账号可以看到 指定课题组人员按钮
            if (isCorpAccount || AuthContext.getUserId().equals(info.getTeamUserId())){
                info.setIsDomainGroupUser(true);
            }
        });
        return PageResponse.of(examCenterCOS, pageResponse.getTotalCount(), pageResponse.getPageSize(), pageResponse.getPageIndex());
    }

    public ProjectTaskDetailsCO getInfoById(Long id) {

        ProjectTaskDO projectTaskDO = projectTaskRepository.getInfoById(id);
         if (projectTaskDO == null){
             return null;
         }
        ProjectTaskDetailsCO projectTaskDetailsCO = projectTaskCoConvertor.converDOToDetailsCO(projectTaskDO);
        //查询课题信息
        List<ProjectTaskInfoDO> projectTaskInfoDOList =projectTaskInfoRepository.getListByTaskId(projectTaskDetailsCO.getProjectTaskId());
        if(CollUtil.isNotEmpty(projectTaskInfoDOList)){
            List<ProjectTaskInfoCO> projectTaskInfoCOS = projectTaskInfoCoConvertor.converDOsToCOs(projectTaskInfoDOList);
            projectTaskDetailsCO.setProjectTaskInfoCOList(projectTaskInfoCOS);
        }

        //课题领域组人员信息
        List<ProjectTaskGroupUserDO> projectTaskGroupUserDOList =projectTaskGroupUserRepository.getListByTaskId(projectTaskDetailsCO.getProjectTaskId());
        if(CollUtil.isNotEmpty(projectTaskGroupUserDOList)){
            List<ProjectTaskGroupUserCO> projectTaskGroupUserCOS = projectTaskGroupUserCoConvertor.converDOsToCOs(projectTaskGroupUserDOList);
            projectTaskDetailsCO.setProjectTaskGroupUserCOList(projectTaskGroupUserCOS);
        }
        //查询课题评审人员信息
        List<ProjectTaskScoreInfoDO> projectTaskScoreInfoDOList =projectTaskScoreInfoRepository.getListByTaskId(projectTaskDetailsCO.getProjectTaskId());
        if(CollUtil.isNotEmpty(projectTaskScoreInfoDOList)){
            List<ProjectTaskScoreInfoCO> projectTaskScoreInfoCOS = projectTaskScoreInfoCoConvertor.converDOsToCOs(projectTaskScoreInfoDOList);
            projectTaskScoreInfoCOS.forEach(projectTaskScoreInfoCO -> {
                if(projectTaskScoreInfoCO.getScore()!=null){
                    projectTaskScoreInfoCO.setIsScore(true);
                }else{
                    projectTaskScoreInfoCO.setIsScore(false);
                }

                // 判断是否可以查看/设置评分
                boolean canViewScore = checkScorePermission(projectTaskScoreInfoCO);
                if(canViewScore){
                    projectTaskScoreInfoCO.setScoreFlag(true);
                }else{
                    boolean canViewByRole = (corpInfoRepository.isSupper()&&corpInfoRepository.checkCorp()) ||
                            (AuthContext.getRoleIds() != null &&
                                    AuthContext.getRoleIds().contains(2008483105201106946L));
                    //只有监管端或有特殊管理角色的用户可以查看评分
                    if (!canViewByRole) {
                        projectTaskScoreInfoCO.setScore(null);
                    }
                    projectTaskScoreInfoCO.setScoreFlag(false);
                }
            });
            projectTaskDetailsCO.setProjectTaskScoreInfoCOList(projectTaskScoreInfoCOS);
        }
         return projectTaskDetailsCO;
    }
    private boolean checkScorePermission(ProjectTaskScoreInfoCO scoreInfo) {
        // 1. 企业账号且数据属于本企业
        if (CorpInfoE.isCorp() && AuthContext.getTenantId().equals(scoreInfo.getCorpinfoId())) {
            return true;
        }
        // 2. 评分人员本人
        if (AuthContext.getUserId().equals(scoreInfo.getUserId())) {
            return true;
        }
        // 3. 拥有特殊管理角色
        if (AuthContext.getRoleIds() != null &&
                AuthContext.getRoleIds().contains(2008483105201106946L)) {
            return true;
        }
        return false;
    }
}

