package com.yeejoin.amos.boot.module.ugp.biz.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.module.ugp.api.Enum.*;
import com.yeejoin.amos.boot.module.ugp.api.dto.TaskDto;
import com.yeejoin.amos.boot.module.ugp.api.entity.*;
import com.yeejoin.amos.boot.module.ugp.api.mapper.TaskMapper;
import com.yeejoin.amos.boot.module.ugp.api.service.TaskService;
import com.yeejoin.amos.boot.module.ugp.biz.framework.BusinessIdentify;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.querydsl.QPageRequest;
import org.springframework.stereotype.Service;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.rdbms.service.BaseService;

import javax.xml.crypto.Data;
import java.util.*;

/**
 * 监检任务表 服务实现类
 *
 * @author duanwei
 * @date 2022-10-19
 */
@Service
public class TaskServiceImpl extends BaseService<TaskDto, Task, TaskMapper> implements TaskService {

    @Autowired
    OrgServiceImpl orgService;

    @Autowired
    ProjectResourceServiceImpl projectResourceService;

    @Autowired
    QualityProblemServiceImpl qualityProblemService;

    @Autowired
    SuperviseRuleServiceImpl superviseRuleService;

    @Autowired
    CompanyServiceImpl companyService;

    @Autowired
    ProjectInitiationServiceImpl projectInitiationService;

    /**
     * 获取当前登录人的所有待办事项
     * @return
     */
    @BusinessIdentify
    public List<TaskDto> unDoneTask(){
        List<TaskDto> taskDtoList = new ArrayList<>();
        TaskDto task = new TaskDto();
        JSONObject jsonObject = new JSONObject();
        ReginParams ReginParams = orgService.getReginParams();
        String companyType = ReginParams.getBusinessInfo().getCompanyType();
        Long companyId = ReginParams.getBusinessInfo().getCompanySequenceNbr();
        List<Project> projectList = projectResourceService.getProjectList();
        if(!ValidationUtil.isEmpty(projectList)) {

            //项目流程任务
            if (OrgEnum.安装单位.getKey().equals(companyType)) {
                for (Project project : projectList) {
                    if (ProjectInitiationEnum.提交资料.getName().equals(project.getStatus()) || ProjectInitiationEnum.告知申请.getName().equals(project.getStatus())) {
                        taskDtoList.add(setTask(project.getStatus(), false, TaskTypeEnum.填报.getKey(), project.getRecDate(), project.getSequenceNbr()));
                    }
                    if (ProjectInitiationEnum.审核人审核.getName().equals(project.getStatus()) || ProjectInitiationEnum.审批人审批.getName().equals(project.getStatus())) {
                        taskDtoList.add(setTask(project.getStatus(), false, TaskTypeEnum.流程.getKey(), project.getRecDate(), project.getSequenceNbr()));
                    }
                }
            } else if (OrgEnum.建设单位.getKey().equals(companyType)) {
                for (Project project : projectList) {
                    if (ProjectInitiationEnum.项目立项.getName().equals(project.getStatus())) {
                        taskDtoList.add(setTask(project.getStatus(), false, TaskTypeEnum.填报.getKey(), project.getRecDate(), project.getSequenceNbr()));
                    }
                }
            } else if (OrgEnum.设计单位.getKey().equals(companyType)) {
                for (Project project : projectList) {
                    if (ProjectInitiationEnum.提交资料.getName().equals(project.getStatus())) {
                        taskDtoList.add(setTask(project.getStatus(), false, TaskTypeEnum.填报.getKey(), project.getRecDate(), project.getSequenceNbr()));
                    }
                    if (ProjectInitiationEnum.审批人审批.getName().equals(project.getStatus()) || ProjectInitiationEnum.审核人审核.getName().equals(project.getStatus())) {
                        taskDtoList.add(setTask(project.getStatus(), false, TaskTypeEnum.流程.getKey(), project.getRecDate(), project.getSequenceNbr()));
                    }
                }
            } else if (OrgEnum.监察部门.getKey().equals(companyType)) {
                for (Project project : projectList) {
                    if (ProjectInitiationEnum.平台审核.getName().equals(project.getStatus()) || ProjectInitiationEnum.接受审查意见.getName().equals(project.getStatus()) || ProjectInitiationEnum.接受告知.getName().equals(project.getStatus())) {
                        taskDtoList.add(setTask(project.getStatus(), false, TaskTypeEnum.流程.getKey(), project.getRecDate(), project.getSequenceNbr()));
                    }
                }
            } else if (OrgEnum.监检机构.getKey().equals(companyType)) {
                for (Project project : projectList) {
                    if (ProjectInitiationEnum.审查项目.getName().equals(project.getStatus()) || ProjectInitiationEnum.监检科室分配.getName().equals(project.getStatus()) || ProjectInitiationEnum.监检员分配.getName().equals(project.getStatus()) || ProjectInitiationEnum.监检员审核.getName().equals(project.getStatus())) {
                        taskDtoList.add(setTask(project.getStatus(), false, TaskTypeEnum.流程.getKey(), project.getRecDate(), project.getSequenceNbr()));
                    }
                }
            }

            //问题处置环节流程任务
            List<QualityProblem> qualityProblemList = new ArrayList<>();
            for(Project project:projectList){
                qualityProblemList.addAll(qualityProblemService.list(new LambdaQueryWrapper<QualityProblem>().eq(QualityProblem::getProjectId,project.getSequenceNbr())));
            }
            if (OrgEnum.安装单位.getKey().equals(companyType)) {
                for (QualityProblem qualityProblem : qualityProblemList) {
                    if (ProblemProcessEnum.编制处理方案.getName().equals(qualityProblem.getStatus()) || ProblemProcessEnum.提交整改书.getName().equals(qualityProblem.getStatus())) {
                        taskDtoList.add(setTask(qualityProblem.getStatus(), false, TaskTypeEnum.填报.getKey(), qualityProblem.getRecDate(), qualityProblem.getSequenceNbr()));
                    }
                }
            } else if (OrgEnum.建设单位.getKey().equals(companyType)) {
                for (QualityProblem qualityProblem : qualityProblemList) {
                    if (ProblemProcessEnum.审查处理方案.getName().equals(qualityProblem.getStatus())) {
                        taskDtoList.add(setTask(qualityProblem.getStatus(), false, TaskTypeEnum.流程.getKey(), qualityProblem.getRecDate(), qualityProblem.getSequenceNbr()));
                    }
                }
            } else if (OrgEnum.监检机构.getKey().equals(companyType)) {
                for (QualityProblem qualityProblem : qualityProblemList) {
                    if (ProblemProcessEnum.确定问题.getName().equals(qualityProblem.getStatus()) || ProblemProcessEnum.问题分类.getName().equals(qualityProblem.getStatus()) || ProblemProcessEnum.审查整改过程.getName().equals(qualityProblem.getStatus())) {
                        taskDtoList.add(setTask(qualityProblem.getStatus(), false, TaskTypeEnum.流程.getKey(), qualityProblem.getRecDate(), qualityProblem.getSequenceNbr()));
                    }
                }
            }
        }

        //企业审核任务
        Set<Integer> regionCodes = new HashSet<>();
        LambdaQueryWrapper<SuperviseRule> wrapper = new LambdaQueryWrapper<>();
        if (OrgEnum.监察部门.getKey().equals(companyType)) {
            wrapper.eq(SuperviseRule::getSuperviseDeptId,companyId);
        } else if (OrgEnum.监检机构.getKey().equals(companyType)) {
            wrapper.eq(SuperviseRule::getInspectionUnitId,companyId);
        }
        for(SuperviseRule superviseRule:superviseRuleService.list(wrapper)){
            regionCodes.add(superviseRule.getAdminRegionCode());
        }
        LambdaQueryWrapper<Company> companyWrapper = new LambdaQueryWrapper<>();
        companyWrapper.in(Company::getRegionCode,regionCodes).eq(Company :: getApproved,CompanyExamineEnum.企业审核.getNo());
        List<Company> companyList = companyService.list(companyWrapper);
        for (Company company : companyList) {
            taskDtoList.add(setTask(null, false, TaskTypeEnum.企业审核.getKey(), company.getRecDate(), company.getSequenceNbr()));
        }
        return taskDtoList;
    }

    /**
     * 项目流程创建TaskDto对象
     * @param InitiationStatus 项目/问题处置 表中的 status字段
     * @param taskType 任务类型（填报、流程）
     * @param sendTime
     * @Param sequenceNbr 项目/问题处置的sequenceNbr
     * @return
     */
    public TaskDto setTask(String InitiationStatus,boolean status, String taskType, Date sendTime,Long sequenceNbr){
        TaskDto task = new TaskDto();
        String title = "", taskStatus = "";
        task.setTaskType(taskType);
        if(!ValidationUtil.isEmpty(InitiationStatus)){
            title = ProjectInitiationEnum.getTaskNameMap.get(InitiationStatus);
            taskStatus = ProjectInitiationEnum.getTaskStatusMap.get(InitiationStatus);
            if(ValidationUtil.isEmpty(title)){
                //不是项目立项流程，是问题处置流程
                title = ProblemProcessEnum.getTaskNameMap.get(InitiationStatus);
                taskStatus = ProblemProcessEnum.getTaskStatusMap.get(InitiationStatus);
            }
        }

        if (ValidationUtil.isEmpty(title)) {
            //不是问题处置流程，企业注册任务
            title = CompanyExamineEnum.企业审核.getName();
            if(status){
                taskStatus = CompanyExamineEnum.企业审核.getYes();
            }else {
                taskStatus = CompanyExamineEnum.企业审核.getNo();
            }


        }

        task.setTitle(title);
        task.setStatus(status);
        if(status){
            task.setStatusLabel(TaskTypeEnum.已办.getName());
            taskStatus = "已完成";
        } else {
            task.setStatusLabel(TaskTypeEnum.待办.getName());
        }

        task.setSendTime(sendTime);
        task.setContent(title+", "+taskStatus);
        task.setSequenceNbr(sequenceNbr);



        if(TaskTypeEnum.填报.getKey().equals(taskType)){
            task.setTaskTypeLabel(TaskTypeEnum.填报.getName());
        } else if(TaskTypeEnum.流程.getKey().equals(taskType)){
            task.setTaskTypeLabel(TaskTypeEnum.流程.getName());
        } else{
            task.setTaskTypeLabel(TaskTypeEnum.企业审核.getName());
        }


        return task;
    }

    /**
     * 已办任务查询
     * @return
     */
    public List<TaskDto> doneTask(){
        List<Project> projectList = projectResourceService.getProjectList();
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        ReginParams ReginParams = orgService.getReginParams();
        String companyType = ReginParams.getBusinessInfo().getCompanyType();
        Long companyId = ReginParams.getBusinessInfo().getCompanySequenceNbr();
        List<TaskDto> taskDtoList = new ArrayList<>();
        if(!ValidationUtil.isEmpty(projectList)){
            for(Project project : projectList) {
                LambdaQueryWrapper<ProjectInitiation> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(ProjectInitiation::getInstanceId, project.getInstanceId());
                List<ProjectInitiation> projectInitiationList = projectInitiationService.list(wrapper);
                if (OrgEnum.安装单位.getKey().equals(companyType)) {
                    for (ProjectInitiation projectInitiation : projectInitiationList) {
                        if (ProjectInitiationEnum.提交资料.getName().equals(projectInitiation.getTaskName())) {
                            taskDtoList.add(setTask(projectInitiation.getTaskName(), true, TaskTypeEnum.填报.getKey(), projectInitiation.getRecDate(), project.getSequenceNbr()));
                        }
                    }
                } else if (OrgEnum.设计单位.getKey().equals(companyType)) {
                    for (ProjectInitiation projectInitiation : projectInitiationList) {
                        if (ProjectInitiationEnum.提交资料.getName().equals(projectInitiation.getTaskName())) {
                            taskDtoList.add(setTask(projectInitiation.getTaskName(), true, TaskTypeEnum.填报.getKey(), projectInitiation.getRecDate(), project.getSequenceNbr()));
                        }
                    }
                } else if (OrgEnum.监察部门.getKey().equals(companyType)) {
                    for (ProjectInitiation projectInitiation : projectInitiationList) {
                        if (ProjectInitiationEnum.接受告知.getName().equals(projectInitiation.getTaskName())) {
                            taskDtoList.add(setTask(projectInitiation.getTaskName(), true, TaskTypeEnum.流程.getKey(), projectInitiation.getRecDate(), project.getSequenceNbr()));
                        }
                    }
                } else if (OrgEnum.监检机构.getKey().equals(companyType)) {
                    for (ProjectInitiation projectInitiation : projectInitiationList) {
                        if (ProjectInitiationEnum.审查项目.getName().equals(projectInitiation.getTaskName()) || ProjectInitiationEnum.监检科室分配.getName().equals(projectInitiation.getTaskName()) || ProjectInitiationEnum.监检员分配.getName().equals(projectInitiation.getTaskName()) || ProjectInitiationEnum.监检员审核.getName().equals(projectInitiation.getTaskName())) {
                            taskDtoList.add(setTask(projectInitiation.getTaskName(), true, TaskTypeEnum.流程.getKey(), projectInitiation.getRecDate(), project.getSequenceNbr()));
                        }
                    }
                }

                //质量问题
                List<ProjectInitiation> projectInitiations = new ArrayList<>();
                for (Project project1 : projectList) {
                    LambdaQueryWrapper<QualityProblem> queryWrapper = new LambdaQueryWrapper();
                    queryWrapper.eq(QualityProblem::getProjectId, project1.getSequenceNbr());
                    List<QualityProblem> qualityProblems = qualityProblemService.list(queryWrapper);
                    for (QualityProblem qualityProblem : qualityProblems) {
                        LambdaQueryWrapper<ProjectInitiation> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                        lambdaQueryWrapper.eq(ProjectInitiation::getInstanceId, qualityProblem.getInstanceId());
                        List<ProjectInitiation> projectInitiation = projectInitiationService.list(lambdaQueryWrapper);
                        projectInitiations.addAll(projectInitiation);
                    }

                }
                if (OrgEnum.安装单位.getKey().equals(companyType)) {
                    for (ProjectInitiation projectInitiation : projectInitiations) {
                        if (ProblemProcessEnum.编制处理方案.getName().equals(projectInitiation.getTaskName()) || ProblemProcessEnum.提交整改书.getName().equals(projectInitiation.getTaskName())) {
                            taskDtoList.add(setTask(projectInitiation.getTaskName(), true, TaskTypeEnum.填报.getKey(), projectInitiation.getRecDate(), project.getSequenceNbr()));
                        }
                    }
                } else if (OrgEnum.建设单位.getKey().equals(companyType)) {
                    for (ProjectInitiation projectInitiation : projectInitiations) {
                        if (ProblemProcessEnum.审查处理方案.getName().equals(projectInitiation.getTaskName())) {
                            taskDtoList.add(setTask(projectInitiation.getTaskName(), true, TaskTypeEnum.流程.getKey(), projectInitiation.getRecDate(), project.getSequenceNbr()));
                        }
                    }
                } else if (OrgEnum.监检机构.getKey().equals(companyType)) {
                    for (ProjectInitiation projectInitiation : projectInitiations) {
                        if (ProblemProcessEnum.确定问题.getName().equals(projectInitiation.getTaskName()) || ProblemProcessEnum.问题分类.getName().equals(projectInitiation.getTaskName()) || ProblemProcessEnum.审查整改过程.getName().equals(projectInitiation.getTaskName())) {
                            taskDtoList.add(setTask(projectInitiation.getTaskName(), true, TaskTypeEnum.流程.getKey(), projectInitiation.getRecDate(), project.getSequenceNbr()));
                        }
                    }
                }
            }
            //企业审核任务
            Set<Integer> regionCodes = new HashSet<>();
            LambdaQueryWrapper<SuperviseRule> wrapper1 = new LambdaQueryWrapper<>();
            if (OrgEnum.监察部门.getKey().equals(companyType)) {
                wrapper1.eq(SuperviseRule::getSuperviseDeptId,companyId);
            } else if (OrgEnum.监检机构.getKey().equals(companyType)) {
                wrapper1.eq(SuperviseRule::getInspectionUnitId,companyId);
            }
            for(SuperviseRule superviseRule:superviseRuleService.list(wrapper1)){
                regionCodes.add(superviseRule.getAdminRegionCode());
            }
            LambdaQueryWrapper<Company> companyWrapper = new LambdaQueryWrapper<>();
            companyWrapper.in(Company::getRegionCode,regionCodes).eq(Company :: getApproved,CompanyExamineEnum.企业审核.getYes());
            List<Company> companyList = companyService.list(companyWrapper);
            for (Company company : companyList) {
                taskDtoList.add(setTask(null, true, TaskTypeEnum.企业审核.getKey(), company.getRecDate(), company.getSequenceNbr()));
            }
        }
        return taskDtoList;
    }
}
