package com.yeejoin.precontrol.common.task;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yeejoin.precontrol.common.entity.Company;
import com.yeejoin.precontrol.common.entity.PersonAscription;
import com.yeejoin.precontrol.common.entity.PersonClock;
import com.yeejoin.precontrol.common.entity.Project;
import com.yeejoin.precontrol.common.entity.Task;
import com.yeejoin.precontrol.common.enums.ClockInOutEum;
import com.yeejoin.precontrol.common.enums.TypeKeyEnum;
import com.yeejoin.precontrol.common.service.ICompanyService;
import com.yeejoin.precontrol.common.service.IPersonAscriptionService;
import com.yeejoin.precontrol.common.service.IPersonClockService;
import com.yeejoin.precontrol.common.service.IProjectScoreService;
import com.yeejoin.precontrol.common.service.IProjectService;
import com.yeejoin.precontrol.common.service.ITaskService;
import com.yeejoin.precontrol.common.utils.DateTools;
import com.yeejoin.precontrol.common.utils.StringUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * @description: 计算所有工程是否有交底
 * @author: duanwei
 * @date: 2020-08-07 14:06
 **/

@Component
@EnableScheduling
@Slf4j
public class ProjectJobNumTask {

    @Autowired
    IProjectService iProjectService;


    @Autowired
    IProjectScoreService iProjectScoreService;


    @Autowired
    IPersonAscriptionService iPersonAscriptionService;


    @Autowired
    ITaskService iTaskService;
    
    @Autowired
    IPersonClockService iPersonClockService;
    
    @Autowired
    ICompanyService iCompanyService;

    /**
     * 每天凌晨2点 计算昨天的交底次数
     */
    @Scheduled(cron = "0 0 2 * * ?")
    public void scan() {
        log.info("定时任务计算昨天的交底次数开始--------------->");
        String day = DateTools.getPastDate(1);
        String start = day + " 00:00:00";
        String end = day + " 23:59:59";
        List<Project> projects = iProjectService.list(new LambdaQueryWrapper<Project>().in(Project::getStatus, "开发",
                "策划", "在建"));
        if (StringUtil.isNotEmpty(projects)) {
            projects.forEach(p -> {
                //昨日未交底数量
                int jobTotal = 0;
                long projectId = p.getId();
                List<PersonClock> clockList = iPersonClockService.list(new LambdaQueryWrapper<PersonClock>()
        				.eq(PersonClock::getClockProjectId, projectId).between(PersonClock::getCreateDate, start, end)
        				.eq(PersonClock::getInOrOut, ClockInOutEum.in.getValue()));
        		Set<Long> clockPersonIdList = clockList.stream().map(clock -> clock.getPersonId()).collect(Collectors.toSet());
        		List<PersonAscription> companyList = null;
        		if (StringUtil.isNotEmpty(clockPersonIdList))

        		{
        			companyList = iPersonAscriptionService.list(new LambdaQueryWrapper<PersonAscription>()
        					.select(PersonAscription::getCompanyId).eq(PersonAscription::getProjectId, projectId)
        					.in(PersonAscription::getPersonId, clockPersonIdList).isNotNull(PersonAscription::getCompanyId)
        					.groupBy(PersonAscription::getCompanyId));
        		}
                Set<Long> companyIdList = null;
                if (StringUtil.isNotEmpty(companyList)) {
                	companyIdList = companyList.stream().map(company -> company.getCompanyId()).collect(Collectors.toSet());
                	// 过滤出分包商
        			List<Company> list = iCompanyService.list(new LambdaQueryWrapper<Company>()
        					.eq(Company::getTypeKey, TypeKeyEnum.COMPANY).in(Company::getId, companyIdList));
        			companyIdList = list.stream().map(company -> company.getId()).collect(Collectors.toSet());
                    //获取项目昨天的三交三查情况
                    Set<Long> taskPersonIdList = null;
                    List<Task> taskList = iTaskService.list(new LambdaQueryWrapper<Task>().eq(Task::getProjectId,
                            p.getId()).eq(Task::getType, 1).eq(Task::getStatus, 1).between(Task::getCreateDate, start, end));
                    //发起任务的人的id
                    if (StringUtil.isNotEmpty(taskList)) {
                        taskPersonIdList = taskList.stream().map(task -> task.getCreatePersonId()).collect(Collectors.toSet());
                    }
                    //发起任务的人得分包商id
                    Set<Long> taskCompanyIds = null;
                    //根据发起任务的人 获取对应的分包商id
                    List<PersonAscription> taskCompanyIdList = iPersonAscriptionService.list(new LambdaQueryWrapper<PersonAscription>().select(PersonAscription::getCompanyId).in(PersonAscription::getPersonId, taskPersonIdList));
                    if (StringUtil.isNotEmpty(taskCompanyIdList)) {
                        taskCompanyIds = taskCompanyIdList.stream().map(task -> task.getCompanyId()).collect(Collectors.toSet());
                         // 过滤出分包商
    					List<Company> list2 = iCompanyService.list(new LambdaQueryWrapper<Company>()
    							.eq(Company::getTypeKey, TypeKeyEnum.COMPANY).in(Company::getId, taskCompanyIds));
    					taskCompanyIds = list2.stream().map(company -> company.getId()).collect(Collectors.toSet());
    					
                        //得到未交底得数量 根据没提交的数量做增减
                        jobTotal = companyIdList.size() - taskCompanyIds.size();
						if (jobTotal < 0) {
							jobTotal = 0;
						}
                        p.setJobNum(p.getJobNum() + jobTotal);

                        //只要分包商没提交 只算一次未交底
//                    if (companyIdList.size() > taskCompanyIds.size()) {
//                        p.setJobNum(p.getJobNum() + 1);
//                    }
                        //更新数量
                        iProjectService.updateById(p);
                    }
                }
            });
        }
        log.info("定时任务计算昨天的交底次数结束--------------->");
    }


}
