package com.yeejoin.precontrol.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.precontrol.common.entity.*;
import com.yeejoin.precontrol.common.enums.TaskPersonTypeEnum;
import com.yeejoin.precontrol.common.service.*;
import com.yeejoin.precontrol.common.utils.*;
import com.yeejoin.precontrol.common.vo.*;
import com.yeejoin.precontrol.common.ws.WebSocketStatistics;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.util.SystemOutLogger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.precontrol.common.config.GlobalUtils;
import com.yeejoin.precontrol.common.constant.Constant;
import com.yeejoin.precontrol.common.dto.BadPersonDto;
import com.yeejoin.precontrol.common.dto.CommonPageableDto;
import com.yeejoin.precontrol.common.dto.CompanyPersonAdmissionDto;
import com.yeejoin.precontrol.common.dto.CompanyPersonDto;
import com.yeejoin.precontrol.common.dto.NoJobCompanyDto;
import com.yeejoin.precontrol.common.dto.NoJobDto;
import com.yeejoin.precontrol.common.dto.NoJobPersonDto;
import com.yeejoin.precontrol.common.dto.SafeConstructionDto;
import com.yeejoin.precontrol.common.dto.SafeOperationStatisticsDto;
import com.yeejoin.precontrol.common.dto.StatisticsDto;
import com.yeejoin.precontrol.common.enums.TaskTypeEnum;
import com.yeejoin.precontrol.common.enums.TypeKeyEnum;
import com.yeejoin.precontrol.common.exception.BaseException;
import com.yeejoin.precontrol.common.mapper.StatisticsMapper;
import com.yeejoin.precontrol.common.mapper.TaskMapper;
import com.yeejoin.precontrol.common.param.PersonStatisticParam;
import com.yeejoin.precontrol.common.vo.taskStatistical.BadStatisticalVo;
import com.yeejoin.precontrol.common.vo.taskStatistical.JobStatisticalVo;
import com.yeejoin.precontrol.common.vo.taskStatistical.RiskStatisticalVo;
import com.yeejoin.precontrol.common.vo.taskStatistical.TaskPayStatisticalVo;
import com.yeejoin.precontrol.common.vo.taskStatistical.WorkTicketStatisticalVo;
import com.yeejoin.precontrol.controller.publics.BaseController;

import lombok.extern.slf4j.Slf4j;

/**
 * 统计
 *
 * @author sqy
 */
@RestController
@Api(tags = "统计api")
@RequestMapping(value = "/statistical", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Slf4j
public class StatisticalController extends BaseController {

	/**
	 * 人员服务
	 */
	@Autowired
	IPersonService personService;
	/**
	 * 项目分数服务
	 */
	@Autowired
	IProjectScoreService projectScoreService;
	/**
	 * 项目服务
	 */
	@Autowired
	IProjectService projectService;
	/**
	 * 任务服务
	 */
	@Autowired
	ITaskService taskService;

	@Autowired
	ITaskRiskControlService taskRiskControlService;
	/**
	 * 企业服务
	 */
	@Autowired
	ICompanyService companyService;
	/**
	 * 人员关系表服务
	 */
	@Autowired
	IPersonAscriptionService personAscriptionService;
	/**
	 * 人员打卡服务
	 */
	@Autowired
	IPersonClockService personClockService;
	/**
	 * 违章管理服务
	 */
	@Autowired
	IBadManagementService badManagementService;
	/**
	 * 任务与人关系服务
	 */
	@Autowired
	ITaskPersonService taskPersonService;
	/**
	 * 地区服务
	 */
	@Autowired
	IDistrictsService districtsService;
	/**
	 * 任务服务
	 */
	@Autowired
	TaskMapper taskMapper;

	@Autowired
	PlatformUtils platformUtils;

	@Autowired
	IStatisticsService statistisService;

	/**
	 * 文件服务器地址
	 */
	@Value("${fileserver.domain}")
	String fileServerUrl;

	/**
	 * 人员信息统计根据项目id
	 *
	 * @return
	 */
	@RequestMapping(value = "/person", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "人员信息统计根据项目id", notes = "人员信息统计根据项目id")
	public Object personByProjectId(Long projectId) {
		return personService.personByProjectId(projectId);
	}

	/**
	 * 人员态势（红黄绿)
	 *
	 * @return
	 */
	@RequestMapping(value = "/personSituational", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "人员态势统计", notes = "人员态势统计")
	public Map<String, Object> personSituational(Long projectId) {
		getUserInfo();
		Long companyId = null;
		ReginParams reginInfo = getReginInfo();
		if (isFbsRole(reginInfo)) {
			Company company = reginInfo.getCompany();
			if (company != null) {
				companyId = company.getId();
			}
		}
		String orgCode = platformUtils.getOrgCode();
		return personService.personSituational(projectId, companyId, orgCode);
	}

	/**
	 * 人员统计详情列表(点击人员的列表) 业务屏
	 */
	@RequestMapping(value = "/personlist", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "人员统计详情列表", notes = "人员统计详情列表")
	public Object listPage(@ApiParam(value = "分页") CommonPageableDto pageable,
			@ApiParam(value = "查询参数") PersonStatisticParam personStatisticParam,
			@ApiParam(value = "类型 0查询列表 1 导出列表") @RequestParam Long operType, HttpServletResponse response) {
		String fileName = UUID.randomUUID().toString() + ".xls";
		String orgCode = platformUtils.getOrgCode();
		personStatisticParam.setOrgCode(orgCode);
		IPage<PersonStatisticVo> page = personService.statisticPageInfo(personStatisticParam, pageable);
		if (operType == 1) {
			List<PersonStatisticVo> excelList = page.getRecords();
			FileHelper.exportExcel(excelList, "人员安全态势", "人员安全态势", PersonStatisticVo.class, fileName, response);
			return null;
		} else {
			return page;
		}
	}

	/**
	 * 人员入场统计列表 大屏统计接口
	 *
	 * @param pageable
	 * @param personStatisticParam
	 * @return
	 */
	@RequestMapping(value = "/in/person", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "人员入场统计列表", notes = "人员入场统计列表")
	public Object inPersonlistPage(@ApiParam(value = "分页") CommonPageableDto pageable,
			@ApiParam(value = "查询参数") PersonStatisticParam personStatisticParam) {
		String orgCode = platformUtils.getOrgCode();
		personStatisticParam.setOrgCode(orgCode);
		IPage<PersonStatisticVo> page = null;
		// 1-红绿黄码接口 2-入场人员接口
		if ("1".equals(personStatisticParam.getTypeFlag())) {
			personStatisticParam.setTypeKey(0L);
			page = personService.statisticPageInfo(personStatisticParam, pageable);
		} else if ("2".equals(personStatisticParam.getTypeFlag())) {
			page = personService.statisticInPersonlistPage(personStatisticParam, pageable);
		}
		return page;
	}

	/**
	 * 项目安全态势-监控屏
	 *
	 * @return
	 */
	@RequestMapping(value = "/securityPostureMonitor", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "项目安全态势-监控屏", notes = "项目安全态势-监控屏")
	public Object securityPostureMonitor(Long projectId) {
		Person me = getPerson();
		Person person = personService.getById(me.getId());
		if (person != null && person.getIsJxdj() != TypeKeyEnum.JXDJ.getLongType()) {
			PersonAscription personAscription = personAscriptionService
					.getOne(new LambdaQueryWrapper<PersonAscription>().eq(PersonAscription::getPersonId, me.getId()));
			if (personAscription.getProjectId() == null) {
				return 0;
			}
		}
		if (projectId == null) {
			String orgCode = platformUtils.getOrgCode();
			Integer score = projectScoreService.allProjectAvgScore(orgCode);
			return score;
		} else {
//            return projectService.securityScore(projectId);;
			return projectScoreService.getNowDateScore(projectId);
		}

	}

	/**
	 * 项目安全态势-业务屏
	 *
	 * @return
	 */
	@RequestMapping(value = "/securityPostureBusiness", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "项目安全态势-业务屏", notes = "项目安全态势-业务屏")
	public Object securityPostureBusiness(Long projectId) {
//        Integer score = projectService.securityScore(projectId);
		return projectScoreService.getNowDateScore(projectId);
	}

	/**
	 * 项目安全态势按最近七天统计
	 *
	 * @return
	 */
	@RequestMapping(value = "/projectSecurityList", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "项目安全态势按最近七天统计", notes = "项目安全态势按最近七天统计")
	public Object clockExcetionList(Long projectId) {
		List<String> days = DateTools.getDays(7);
		LinkedHashMap<String, Object> maps = new LinkedHashMap<>();
		days.forEach(day -> {
			// 查询每天的数据情况
			String start = day + " 00:00:00";
			String end = day + " 23:59:59";
			List<ProjectScore> projectScore = projectScoreService.list(new LambdaQueryWrapper<ProjectScore>()
					.eq(ProjectScore::getProjectId, projectId).between(ProjectScore::getCreateDate, start, end));
			if (StringUtil.isNotEmpty(projectScore)) {
				maps.put(day.substring(5), projectScore.get(0).getScore());
			} else {
				maps.put(day.substring(5), 0);
			}
		});
		return maps;
	}

	/**
	 * 安全施工任务数量 0进行中[距离目前2小时以内] 1超时[超出目前2小时] 2未完成[今天没完成的就算未完成])
	 *
	 * @return
	 */
	@RequestMapping(value = "/safeConstructionStatusNum", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "安全施工任务数量", notes = "安全施工任务数量")
	public Object safeConstructionStatusNum(Long projectId) {
		String orgCode = platformUtils.getOrgCode();
		CommonPageableDto pageable = new CommonPageableDto(1);
		SafeConstructionDto safeConstructionDto = new SafeConstructionDto();
		safeConstructionDto.setOrgCode(orgCode);
		safeConstructionDto.setProjectId(projectId);
		safeConstructionDto.setCurrentStatus(0L);
		long processing = taskService.safeConstructionTaskStatusList(pageable, safeConstructionDto).getTotal();
		safeConstructionDto.setCurrentStatus(1L);
		long risk = taskService.safeConstructionTaskStatusList(pageable, safeConstructionDto).getTotal();
		safeConstructionDto.setCurrentStatus(2L);
		long undone = taskService.safeConstructionTaskStatusList(pageable, safeConstructionDto).getTotal();
		Map<String, Object> resultMap = new HashMap<>();
		resultMap.put("processing", processing);
		resultMap.put("risk", risk);
		resultMap.put("undone", undone);
		return resultMap;
	}

	/**
	 * 安全施工任务查询
	 *
	 * @return
	 */
	@RequestMapping(value = "/safeConstructionTaskStatusList", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "安全施工任务列表查询", notes = "安全施工任务列表查询")
	public Object safeConstructionTaskStatusList(@ApiParam(value = "分页条件 isAll=0 具体分页必传") CommonPageableDto pageable,
			@ApiParam(value = "查询参数") SafeConstructionDto safeConstructionDto) {
		IPage<TaskPageVo> taskPageVo = taskService.safeConstructionTaskStatusList(pageable, safeConstructionDto);
		return taskPageVo;
	}

	/**
	 * 统计屏-安全作业统计
	 *
	 * @return
	 */
	@RequestMapping(value = "/safeOperationStatistics", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "安全作业统计", notes = "安全作业统计")
	public Object safeOperationStatistics(String date,
			@DateTimeFormat(pattern = "yyyy-MM-dd 00:00:00") String startDate,
			@DateTimeFormat(pattern = "yyyy-MM-dd 23:59:59") String endDate) throws ParseException {
		Map<String, Object> map = new HashMap<>();
		map.put("jobDisclosure", Constant.ZERO);
		map.put("taskPayCheck", Constant.ZERO);
		map.put("badManagement", Constant.ZERO);
		map.put("riskTypeNum", Constant.ZERO);
		map.put("salaryConfirm", Constant.ZERO);
		if (StringUtils.isNotEmpty(date)) {
			Calendar calendar = new GregorianCalendar();
			Date e = new Date();
			calendar.setTime(e);
			calendar.add(Calendar.DAY_OF_MONTH, -Integer.parseInt(date));
			Date s = calendar.getTime();
			String start = DateUtils.dateFormat(s, "yyyy-MM-dd 00:00:00");
			String end = DateUtils.dateFormat(e, "yyyy-MM-dd 23:59:59");
			getTaskStatisticalNum(map, start, end);
			return map;
		} else {
			if (StringUtils.isNotEmpty(startDate)) {
				getTaskStatisticalNum(map, startDate, endDate);
			} else {
				throw new BaseException("请选择开始时间！");
			}
			return map;
		}

	}

	/**
	 * 统计屏-安全作业统计列表 0 技术交底 1三交三查 2违规行为 3风险作业 4安全施工作业票
	 *
	 * @return
	 */
	@RequestMapping(value = "/safeOperationStatisticsList", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "安全作业统计列表", notes = "安全作业统计列表")
	public Object safeOperationStatisticsList(String date, String type, Long operType,
			SafeOperationStatisticsDto safeOperationStatisticsDto, CommonPageableDto commonPageableDto,
			@DateTimeFormat(pattern = "yyyy-MM-dd 00:00:00") String startTime,
			@DateTimeFormat(pattern = "yyyy-MM-dd 23:59:59") String endTime, HttpServletResponse response)
			throws ParseException, IllegalAccessException {
		String fileName = UUID.randomUUID().toString() + ".xls";
		IPage<TaskPageVo> taskListByType;
		if (StringUtils.isNotEmpty(date)) {
			Calendar calendar = new GregorianCalendar();
			Date e = new Date();
			calendar.setTime(e);
			calendar.add(Calendar.DAY_OF_MONTH, -Integer.parseInt(date));
			Date s = calendar.getTime();
			String startDate = DateUtils.dateFormat(s, "yyyy-MM-dd 00:00:00");
			String endDate = DateUtils.dateFormat(e, "yyyy-MM-dd 23:59:59");
			taskListByType = getTaskListByType(commonPageableDto, type, startDate, endDate, safeOperationStatisticsDto);
		} else {
			taskListByType = getTaskListByType(commonPageableDto, type, startTime, endTime, safeOperationStatisticsDto);
		}
		if (operType == 1) {
			List<TaskPageVo> excelList = taskListByType.getRecords();
			switch (type) {
			case "0":
				// 技术交底
				List<JobStatisticalVo> jobStatisticalList = new ArrayList<>();
				if (StringUtil.isNotEmpty(excelList)) {
					for (TaskPageVo taskPageVo : excelList) {
						JobStatisticalVo jobStatisticalVo = new JobStatisticalVo();
						BeanUtils.copyProperties(taskPageVo, jobStatisticalVo);
						GlobalUtils.setFormateByOne(jobStatisticalVo);
						jobStatisticalList.add(jobStatisticalVo);
					}
				}
				FileHelper.exportExcel(jobStatisticalList, "技术交底列表", "技术交底列表", JobStatisticalVo.class, fileName,
						response);
				break;
			case "1":
				// 三交三查
				List<TaskPayStatisticalVo> taskPayStatisticalList = new ArrayList<>();
				if (StringUtil.isNotEmpty(excelList)) {
					for (TaskPageVo taskPageVo : excelList) {
						TaskPayStatisticalVo taskPayStatisticalVo = new TaskPayStatisticalVo();
						BeanUtils.copyProperties(taskPageVo, taskPayStatisticalVo);
						GlobalUtils.setFormateByOne(taskPayStatisticalVo);
						taskPayStatisticalList.add(taskPayStatisticalVo);
					}
				}
				FileHelper.exportExcel(taskPayStatisticalList, "安全作业统计列表", "安全作业统计列表", TaskPayStatisticalVo.class,
						fileName, response);
				break;
			case "2":
				// 违规作业
				List<BadStatisticalVo> badStatisticalList = new ArrayList<>();
				if (StringUtil.isNotEmpty(excelList)) {
					for (TaskPageVo taskPageVo : excelList) {
						BadStatisticalVo badStatisticalVo = new BadStatisticalVo();
						BeanUtils.copyProperties(taskPageVo, badStatisticalVo);
						GlobalUtils.setFormateByOne(badStatisticalVo);
						badStatisticalList.add(badStatisticalVo);
					}
				}
				FileHelper.exportExcel(badStatisticalList, "安全作业统计列表", "安全作业统计列表", BadStatisticalVo.class, fileName,
						response);
				break;
			case "3":
				// 风险作业
				List<RiskStatisticalVo> riskStatisticalVoList = new ArrayList<>();
				if (StringUtil.isNotEmpty(excelList)) {
					for (TaskPageVo taskPageVo : excelList) {
						RiskStatisticalVo riskStatisticalVo = new RiskStatisticalVo();
						BeanUtils.copyProperties(taskPageVo, riskStatisticalVo);
						GlobalUtils.setFormateByOne(riskStatisticalVo);
						riskStatisticalVoList.add(riskStatisticalVo);
					}
				}
				FileHelper.exportExcel(riskStatisticalVoList, "安全作业统计列表", "安全作业统计列表", RiskStatisticalVo.class, fileName,
						response);
				break;
			case "4":
				// 安全施工作业票
				List<WorkTicketStatisticalVo> workTicketStatisticalVoList = new ArrayList<>();
				if (StringUtil.isNotEmpty(excelList)) {
					for (TaskPageVo taskPageVo : excelList) {
						WorkTicketStatisticalVo workTicketStatisticalVo = new WorkTicketStatisticalVo();
						BeanUtils.copyProperties(taskPageVo, workTicketStatisticalVo);
						GlobalUtils.setFormateByOne(workTicketStatisticalVo);
						workTicketStatisticalVoList.add(workTicketStatisticalVo);
					}
				}
				FileHelper.exportExcel(workTicketStatisticalVoList, "作业票统计列表", "作业票统计列表", WorkTicketStatisticalVo.class,
						fileName, response);
				break;
			case "5":
				// 薪资确认
				List<TaskSalaryConfirmVo> taskSalaryConfirmVoList = new ArrayList<>();
				if (StringUtil.isNotEmpty(excelList)) {
					for (TaskPageVo taskPageVo : excelList) {
						TaskSalaryConfirmVo taskSalaryConfirmVo = new TaskSalaryConfirmVo();
						BeanUtils.copyProperties(taskPageVo, taskSalaryConfirmVo);
						GlobalUtils.setFormateByOne(taskSalaryConfirmVo);
						taskSalaryConfirmVoList.add(taskSalaryConfirmVo);
					}
				}
				FileHelper.exportExcel(taskSalaryConfirmVoList, "薪资确认列表", "薪资确认列表", WorkTicketStatisticalVo.class,
						fileName, response);
				break;
			default:
			}
			return null;
		} else {
			return taskListByType;
		}
	}

	/**
	 * 今日未交底项目
	 *
	 * @return
	 */
	@RequestMapping(value = "/noJobProject", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "今日未交底项目", notes = "今日未交底项目")
	public Object noJobProject(@ApiParam(value = "分页条件 isAll=0 具体分页必传") CommonPageableDto pageable,
			@ApiParam(value = "查询参数") NoJobDto noJobDto,
			@ApiParam(value = "类型 0查询列表 1 导出列表") @RequestParam Long operType,
			@ApiParam(value = "查询Ids") @RequestParam(required = false) List<Long> ids, HttpServletResponse response) {
		String fileName = UUID.randomUUID().toString() + ".xls";
		if (pageable.getIsAll() == 1) {
			pageable.setPageNumber(0);
			pageable.setPageSize(Integer.MAX_VALUE);
		}
		Page<?> page = new Page<>(pageable.getPageNumber(), pageable.getPageSize());

		// 获取今日发起的三交三查任务
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date());
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		List<Task> list = taskService.list(new LambdaQueryWrapper<Task>().eq(Task::getType, TaskTypeEnum.TASKPAYCHECK)
				.ge(Task::getCreateDate, calendar.getTime()));
	    Set<Long> taskIds = list.stream().map(i->i.getId()).collect(Collectors.toSet());
	    
	    
	    //查询一直入场没出场且没有参与今日三交三查的分包商施工人员
	    List<Long> personIds = taskMapper.noJobPersonIdList(taskIds);
	    
	    IPage<NoJobProjectVo> pageData = taskMapper.noJobProjectNew(page, personIds,noJobDto);
	    
		//IPage<NoJobProjectVo> pageData = taskMapper.noJobProject(page, noJobDto);

		if (StringUtil.isNotEmpty(pageData.getRecords())) {
			pageData.getRecords().forEach(p -> {
				Long projectId = p.getId();
				QueryWrapper<PersonAscription> personAscriptionQueryWrapper1 = new QueryWrapper<>();
				personAscriptionQueryWrapper1.eq("project_id", projectId);
				personAscriptionQueryWrapper1.groupBy("company_id");

				List<PersonAscription> list1 = personAscriptionService.list(new LambdaQueryWrapper<PersonAscription>()
						.select(PersonAscription::getCompanyId).eq(PersonAscription::getProjectId, projectId)
						.isNotNull(PersonAscription::getCompanyId).groupBy(PersonAscription::getCompanyId));
				Integer companyNum = list1.size();
				if (companyNum == null) {
					p.setCompanyNum(0);
				} else {
					p.setCompanyNum(companyNum);
				}
				List<PersonAscription> list2 = personAscriptionService
						.list(new LambdaQueryWrapper<PersonAscription>().select(PersonAscription::getPersonId)
								.eq(PersonAscription::getProjectId, projectId).groupBy(PersonAscription::getPersonId));
				Integer personNum = list2.size();
				if (personNum == null) {
					p.setPersonNum(0);
				} else {
					p.setPersonNum(personNum);
				}
				// 转换地区
				if (StringUtils.isNotBlank(p.getRegion())) {
					String[] split = p.getRegion().split(",");
					LinkedList<Long> collect = Arrays.stream(split).map(Long::parseLong)
							.collect(Collectors.toCollection(LinkedList::new));
					Collection<Districts> districts = districtsService.listByIds(collect);
					StringBuffer districtsName = new StringBuffer();
					districts.forEach(districts1 -> districtsName.append(districts1.getExtName()).append(","));
					districtsName.deleteCharAt(districtsName.length() - 1);
					p.setRegionName(districtsName.toString());
				}
//                p.setSecurityScore(projectService.securityScore(projectId));
				p.setSecurityScore(projectScoreService.getNowDateScore(projectId));
				p.setTaskType("三交三查");
			});

		}
		if (operType == 1) {
			List<NoJobProjectVo> excelList = pageData.getRecords();
			FileHelper.exportExcel(excelList, "今日未交底项目", "今日未交底项目", NoJobProjectVo.class, fileName, response);
			return null;
		} else {
			return page;
		}
	}

	/**
	 * 今日未交底分包商
	 *
	 * @return
	 */
	@RequestMapping(value = "/noJobCompany", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "今日未交底分包商", notes = "今日未交底分包商")
	public Object noJobCompany(@ApiParam(value = "分页条件 isAll=0 具体分页必传") CommonPageableDto pageable,
			@ApiParam(value = "查询参数") NoJobCompanyDto noJobCompanyDto,
			@ApiParam(value = "类型 0查询列表 1 导出列表") @RequestParam Long operType,
			@ApiParam(value = "查询Ids") @RequestParam(required = false) List<Long> ids, HttpServletResponse response) {
		String fileName = UUID.randomUUID().toString() + ".xls";
		if (pageable.getIsAll() == 1) {
			pageable.setPageNumber(0);
			pageable.setPageSize(Integer.MAX_VALUE);
		}
		Page<?> page = new Page<>(pageable.getPageNumber(), pageable.getPageSize());
		//System.out.println("==========noJobCompany 1" + new Date());
		//IPage<NoCompanyVo> pageData = taskMapper.noJobCompany(page, noJobCompanyDto);
		//System.out.println("==========noJobCompany 2" + new Date());
					
		// 获取今日发起的三交三查任务
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date());
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		List<Task> list = taskService.list(new LambdaQueryWrapper<Task>().eq(Task::getType, TaskTypeEnum.TASKPAYCHECK)
				.ge(Task::getCreateDate, calendar.getTime()));
	    Set<Long> taskIds = list.stream().map(i->i.getId()).collect(Collectors.toSet());
	    
	    
	    //查询一直入场没出场且没有参与今日三交三查的分包商施工人员
	    List<Long> personIds = taskMapper.noJobPersonIdList(taskIds);
	    
	    IPage<NoCompanyVo> pageData = taskMapper.noJobCompanyNew(page, personIds,noJobCompanyDto);
		if (StringUtil.isNotEmpty(pageData.getRecords())) {
			pageData.getRecords().forEach(p -> {
				LambdaQueryWrapper<PersonAscription> personAscriptionLambdaQueryWrapper = new LambdaQueryWrapper<>();
				personAscriptionLambdaQueryWrapper.eq(PersonAscription::getCompanyId, p.getId())
						.eq(PersonAscription::getProjectId, p.getProjectId());
				if (StringUtils.isNotEmpty(noJobCompanyDto.getOrgCode())) {
					personAscriptionLambdaQueryWrapper.likeRight(PersonAscription::getOrgCode,
							noJobCompanyDto.getOrgCode());
				}
				int count = personAscriptionService.count(personAscriptionLambdaQueryWrapper);
				p.setPersonTotal(count);
				p.setTaskType("三交三查");
			});
		}
		System.out.println("==========noJobCompany 3" + new Date());
		if (operType == 1) {
			List<NoCompanyVo> excelList = pageData.getRecords();
			FileHelper.exportExcel(excelList, "今日未交底分包商", "今日未交底分包商", NoCompanyVo.class, fileName, response);
			return null;
		} else {
			return page;
		}
	}

	/**
	 * 今日统计
	 *
	 * @return
	 */
	@RequestMapping(value = "/statisticsToday", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "今日统计", notes = "今日统计")
	public Object statisticsToday() {

		String orgCode = platformUtils.getOrgCode();
		StatisticsDto statisticsDto = new StatisticsDto(orgCode, null);
		return statistisService.statisticsToday(statisticsDto);
	}

	/**
	 * 今日分包商人员
	 *
	 * @return
	 */
	@RequestMapping(value = "/companyPerson", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "今日分包商人员", notes = "今日分包商人员")
	public Object noJobCompanyPerson(@ApiParam(value = "分页条件 isAll=0 具体分页必传") CommonPageableDto pageable,
			@ApiParam(value = "查询参数") CompanyPersonDto companyPersonDto,
			@ApiParam(value = "类型 0查询列表 1 导出列表") @RequestParam Long operType,
			@ApiParam(value = "查询Ids") @RequestParam(required = false) List<Long> ids, HttpServletResponse response) {
		String fileName = UUID.randomUUID().toString() + ".xls";
		if (pageable.getIsAll() == 1) {
			pageable.setPageNumber(0);
			pageable.setPageSize(Integer.MAX_VALUE);
		}
		Page<?> page = new Page<>(pageable.getPageNumber(), pageable.getPageSize());
		IPage<CompanyPersonVo> pageData = taskMapper.companyPerson(page, companyPersonDto);
		if (operType == 1) {
			List<CompanyPersonVo> excelList = pageData.getRecords();
			FileHelper.exportExcel(excelList, "今日分包商人员", "今日分包商人员", CompanyPersonVo.class, fileName, response);
			return null;
		} else {
			return page;
		}
	}

	/**
	 * 今日入场分包商人员
	 *
	 * @return
	 */
	@RequestMapping(value = "/companyPersonAdmission", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "今日入场分包商人员", notes = "今日入场分包商人员")
	public Object companyPersonAdmission(@ApiParam(value = "分页条件 isAll=0 具体分页必传") CommonPageableDto pageable,
			@ApiParam(value = "查询参数") CompanyPersonAdmissionDto companyPersonDto,
			@ApiParam(value = "类型 0查询列表 1 导出列表") @RequestParam Long operType,
			@ApiParam(value = "查询Ids") @RequestParam(required = false) List<Long> ids, HttpServletResponse response) {
		String fileName = UUID.randomUUID().toString() + ".xls";
		if (pageable.getIsAll() == 1) {
			pageable.setPageNumber(0);
			pageable.setPageSize(Integer.MAX_VALUE);
		}
		Page<?> page = new Page<>(pageable.getPageNumber(), pageable.getPageSize());
		String orgCode = platformUtils.getOrgCode();
		companyPersonDto.setOrgCode(orgCode);

		IPage<CompanyPersonAdmissionVo> pageData = taskMapper.companyPersonAdmission(page, companyPersonDto);
		if (operType == 1) {
			List<CompanyPersonAdmissionVo> excelList = pageData.getRecords();
			FileHelper.exportExcel(excelList, "今日入场分包商人员", "今日入场分包商人员", CompanyPersonAdmissionVo.class, fileName,
					response);
			return null;
		} else {
			return page;
		}
	}

	/**
	 * 今日未交底人员
	 *
	 * @return
	 */
	@RequestMapping(value = "/noJobPersonList", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "今日未交底人员列表", notes = "今日未交底人员列表")
	public Object noJobPerson(@ApiParam(value = "分页条件 isAll=0 具体分页必传") CommonPageableDto pageable,
			@ApiParam(value = "查询参数") NoJobPersonDto noJobPersonDto,
			@ApiParam(value = "类型 0查询列表 1 导出列表") @RequestParam Long operType,
			@ApiParam(value = "查询Ids") @RequestParam(required = false) List<Long> ids, HttpServletResponse response) {
		String fileName = UUID.randomUUID().toString() + ".xls";
		if (pageable.getIsAll() == 1) {
			pageable.setPageNumber(0);
			pageable.setPageSize(Integer.MAX_VALUE);
		}
		String orgCode = platformUtils.getOrgCode();
		noJobPersonDto.setOrgCode(orgCode);
		Page<?> page = new Page<>(pageable.getPageNumber(), pageable.getPageSize());
		IPage<NoJobPersonVo> noJobPersonList = taskMapper.noJobPerson(page, noJobPersonDto);

		List<NoJobPersonVo> records = noJobPersonList.getRecords();
		if (StringUtil.isNotEmpty(records)) {
			for (NoJobPersonVo record : records) {
				record.setJobName("三交三查");
			}
		}

		if (operType == 1) {
			List<NoJobPersonVo> excelList = noJobPersonList.getRecords();
			FileHelper.exportExcel(excelList, "今日未交底人员列表", "今日未交底人员列表", NoJobPersonVo.class, fileName, response);
			return null;
		} else {
			return page;
		}
	}

	/**
	 * 今日违章员项列表
	 *
	 * @return
	 */
	@RequestMapping(value = "/badPersonList", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "今日违章员项列表", notes = "今日违章员项列表")
	public Object badPersonList(@ApiParam(value = "分页条件 isAll=0 具体分页必传") CommonPageableDto pageable,
			@ApiParam(value = "查询参数") BadPersonDto badPersonDto,
			@ApiParam(value = "类型 0查询列表 1 导出列表") @RequestParam Long operType,
			@ApiParam(value = "查询Ids") @RequestParam(required = false) List<Long> ids, HttpServletResponse response) {
		String fileName = UUID.randomUUID().toString() + ".xls";
		if (pageable.getIsAll() == 1) {
			pageable.setPageNumber(0);
			pageable.setPageSize(Integer.MAX_VALUE);
		}
		Page<BadPersonVo> page = new Page<>(0, Integer.MAX_VALUE);
		IPage<BadPersonVo> badPersonList = taskMapper.badPersonList(page, new BadPersonDto());

		if (operType == 1) {
			List<BadPersonVo> records = badPersonList.getRecords();
			FileHelper.exportExcel(records, "今日违章员项列表", "今日违章员项列表", BadPersonVo.class, fileName, response);
			return null;
		} else {
			return page;
		}
	}

	/**
	 * 违章统计
	 *
	 * @return
	 */
	@RequestMapping(value = "/badStatistics", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "违章统计", notes = "违章统计")
	public Object badStatistics() {
		String orgCode = platformUtils.getOrgCode();
		Map<String, Object> map = new HashMap<>();
		map.put("projectNum", Constant.ZERO);
		map.put("companyNum", Constant.ZERO);
		map.put("noBadProject", Constant.ZERO);
		map.put("noBadCompany", Constant.ZERO);
		LambdaQueryWrapper<Project> projectWrapper = new LambdaQueryWrapper<Project>().in(Project::getStatus, "在建",
				"开发", "策划");
		if (StringUtils.isNotEmpty(orgCode)) {
			projectWrapper = projectWrapper.likeRight(Project::getOrgCode, orgCode);
		}
		int projectCount = projectService.count(projectWrapper);
		map.put("projectNum", projectCount);
		BadProjectVo badProjectVo = new BadProjectVo();
		badProjectVo.setOrgCode(orgCode);
		IPage<BadProjectVo> badProjectVoIpage = projectService.pageBadProject(false, false, new CommonPageableDto(1),
				badProjectVo);
		List<BadProjectVo> badProject = badProjectVoIpage.getRecords();
		if (StringUtil.isNotEmpty(badProject)) {
			map.put("noBadProject", badProject.size());
		}
		BadCompanyVo badCompanyVo = new BadCompanyVo();
		badCompanyVo.setOrgCode(orgCode);
		IPage<BadCompanyVo> page = companyService.pageBadCompany(false, false, new CommonPageableDto(1), badCompanyVo);
		IPage<BadCompanyVo> badPage = companyService.pageBadCompany(true, true, new CommonPageableDto(1), badCompanyVo);
		List<BadCompanyVo> noBadCompany = page.getRecords();
		List<BadCompanyVo> badCompany = badPage.getRecords();
		if (StringUtil.isNotEmpty(noBadCompany)) {
			map.put("noBadCompany", noBadCompany.size());
		}
		if (StringUtil.isNotEmpty(badCompany)) {
			map.put("companyNum", badCompany.size());
		}
		return map;
	}

	/**
	 * 获取任务统计数量
	 *
	 * @param map
	 * @param startDate
	 * @param endDate
	 */
	private void getTaskStatisticalNum(Map<String, Object> map, String startDate, String endDate) {
		String orgCode = platformUtils.getOrgCode();

		LambdaQueryWrapper<Task> taskLambdaQueryWrapper = new LambdaQueryWrapper<>();
		LambdaQueryWrapper<Task> taskLambdaQueryWrapper1 = new LambdaQueryWrapper<>();
		LambdaQueryWrapper<Task> taskLambdaQueryWrapper2 = new LambdaQueryWrapper<>();
		LambdaQueryWrapper<Task> taskLambdaQueryWrapper3 = new LambdaQueryWrapper<>();
		taskLambdaQueryWrapper.eq(Task::getType, TaskTypeEnum.JOBDISCLOSURE.getValue()).between(Task::getCreateDate,
				startDate, endDate);
		taskLambdaQueryWrapper1.eq(Task::getType, TaskTypeEnum.TASKPAYCHECK.getValue()).between(Task::getCreateDate,
				startDate, endDate);
		taskLambdaQueryWrapper2.eq(Task::getType, TaskTypeEnum.BAD.getValue()).between(Task::getCreateDate, startDate,
				endDate);
		taskLambdaQueryWrapper3.eq(Task::getType, TaskTypeEnum.SALARY_CONFIRM.getValue()).between(Task::getCreateDate,
				startDate, endDate);
		if (StringUtils.isNotEmpty(orgCode)) {
			taskLambdaQueryWrapper.likeRight(Task::getOrgCode, orgCode);
			taskLambdaQueryWrapper1.likeRight(Task::getOrgCode, orgCode);
			taskLambdaQueryWrapper2.likeRight(Task::getOrgCode, orgCode);
			taskLambdaQueryWrapper3.likeRight(Task::getOrgCode, orgCode);
		}

		int jobDisclosure = taskService.count(taskLambdaQueryWrapper);
		int taskPayCheck = taskService.count(taskLambdaQueryWrapper1);
		int badManagement = taskService.count(taskLambdaQueryWrapper2);
		int salaryConfirm = taskService.count(taskLambdaQueryWrapper3);
		map.put("jobDisclosure", jobDisclosure);
		map.put("taskPayCheck", taskPayCheck);
		map.put("badManagement", badManagement);
		map.put("salaryConfirm", salaryConfirm);
		map.put("riskTypeNum", Constant.ZERO);
		map.put("jobTicket", Constant.ZERO);

		SafeOperationStatisticsDto safeOperationStatisticsDto = new SafeOperationStatisticsDto();
		safeOperationStatisticsDto.setOrgCode(orgCode);
		IPage<TaskPageVo> riskType = taskService.riskWork(new CommonPageableDto(1), startDate, endDate,
				safeOperationStatisticsDto);
		if (StringUtil.isNotEmpty(riskType.getRecords())) {
			map.put("riskTypeNum", riskType.getRecords().size());
		}
		IPage<TaskPageVo> jobTicket = taskService.jobTicket(new CommonPageableDto(1), startDate, endDate,
				safeOperationStatisticsDto);
		if (StringUtil.isNotEmpty(jobTicket.getRecords())) {
			map.put("jobTicket", jobTicket.getRecords().size());
		}
	}

	/**
	 * 根据类型返回任务数据
	 *
	 * @param type
	 * @param startTime
	 * @param endTime
	 * @return
	 */
	private IPage<TaskPageVo> getTaskListByType(CommonPageableDto commonPageableDto, String type, String startTime,
			String endTime, SafeOperationStatisticsDto safeOperationStatisticsDto) {
		IPage<TaskPageVo> taskPageVoIpage = null;

		switch (type) {
		case "0":
			// 技术交底
			taskPageVoIpage = taskService.taskList(commonPageableDto, type, startTime, endTime,
					safeOperationStatisticsDto);
			break;
		case "1":
			// 三交三查
			taskPageVoIpage = taskService.taskPay(commonPageableDto, startTime, endTime, safeOperationStatisticsDto);
			break;
		case "2":
			// 违规任务
			taskPageVoIpage = taskService.bad(commonPageableDto, startTime, endTime, safeOperationStatisticsDto);
			break;
		case "3":
			// 风险作业
			taskPageVoIpage = taskService.riskWork(commonPageableDto, startTime, endTime, safeOperationStatisticsDto);
			break;
		case "4":
			// 安全施工作业票
			taskPageVoIpage = taskService.jobTicket(commonPageableDto, startTime, endTime, safeOperationStatisticsDto);
			break;
		case "5":
			// 薪资确认
			taskPageVoIpage = taskService.salaryConfirm(commonPageableDto, startTime, endTime,
					safeOperationStatisticsDto);
			break;
		default:
			taskPageVoIpage = taskService.taskList(commonPageableDto, type, startTime, endTime,
					safeOperationStatisticsDto);
		}
		List<TaskPageVo> records = taskPageVoIpage.getRecords();
		if (StringUtil.isNotEmpty(records)) {
			for (TaskPageVo record : records) {
				// 转换地区
				if (StringUtils.isNotBlank(record.getRegion())) {
					String[] split = record.getRegion().split(",");
					LinkedList<Long> collect = Arrays.stream(split).map(Long::parseLong)
							.collect(Collectors.toCollection(LinkedList::new));
					Collection<Districts> districts = districtsService.listByIds(collect);
					StringBuffer districtsName = new StringBuffer();
					districts.forEach(districts1 -> districtsName.append(districts1.getExtName()).append(","));
					districtsName.deleteCharAt(districtsName.length() - 1);
					record.setRegionName(districtsName.toString());
				}
			}
		}
		return taskPageVoIpage;
	}

	/**
	 * 今日监管
	 *
	 * @return
	 */
	@RequestMapping(value = "/today-regulate", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "今日监管", notes = "今日监管")
	public Object todayRegulate(Long projectId) {
		return statistisService.todayRegulate(getStatisticDto(projectId));
	}

	/**
	 * 今日监管-在建项目
	 *
	 * @return
	 */
	@RequestMapping(value = "/today-regulate/project", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "今日监管-在建项目", notes = "今日监管-在建项目")
	public Object todayRegulateProject(Long projectId) {
		return statistisService.todayRegulateProject(getStatisticDto(projectId));
	}

	/**
	 * 今日监管-风险作业
	 *
	 * @return
	 */
	@RequestMapping(value = "/today-regulate/risk", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "今日监管-风险作业", notes = "今日监管-风险作业")
	public Object todayRegulateRisk(Long projectId) {
		return statistisService.todayRegulateRisk(getStatisticDto(projectId));
	}

	/**
	 * 今日监管-今日违章
	 *
	 * @return
	 */
	@RequestMapping(value = "/today-regulate/bad", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "今日监管-今日违章", notes = "今日监管-今日违章")
	public Object todayRegulateBad(Long projectId) {
		return statistisService.todayRegulateBad(getStatisticDto(projectId));
	}

	/**
	 * 今日监管-技术交底
	 *
	 * @return
	 */
	@RequestMapping(value = "/today-regulate/tech", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "今日监管-技术交底", notes = "今日监管-技术交底")
	public Object todayRegulateTech(Long projectId) {
		return statistisService.todayRegulateTech(getStatisticDto(projectId));
	}

	/**
	 * 今日监管-入场人员
	 *
	 * @return
	 */
	@RequestMapping(value = "/today-regulate/person/in", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "今日监管-入场人员", notes = "今日监管-入场人员")
	public Object todayRegulatePersonIn(Long projectId) {
		return statistisService.todayRegulatePersonIn(getStatisticDto(projectId));
	}

	/**
	 * 今日监管-未交底人员
	 *
	 * @return
	 */
	@RequestMapping(value = "/today-regulate/person/no-tech", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "今日监管-未交底人员", notes = "今日监管-未交底人员")
	public Object todayRegulatePersonNoTech(Long projectId) {
		return statistisService.todayRegulatePersonNoTech(getStatisticDto(projectId));
	}

	/**
	 * 今日监管-作业票
	 *
	 * @return
	 */
	@RequestMapping(value = "/today-regulate/ticket", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "今日监管-作业票", notes = "今日监管-作业票")
	public Object todayRegulateTicket(Long projectId) {
		return statistisService.todayRegulateTicket(getStatisticDto(projectId));
	}

	/**
	 * 综合统计
	 *
	 * @return
	 */
	@RequestMapping(value = "/comprehensive-statistical", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "统计-综合统计", notes = "统计-综合统计")
	public Object comprehensiveStatistical(Long projectId) {
		return statistisService.comprehensiveStatistical(getStatisticDto(projectId));
	}

	/**
	 * 作业活动
	 *
	 * @return
	 */
	@RequestMapping(value = "/operation-activities", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "统计-作业活动", notes = "统计-作业活动")
	public Object operationActivities(Long projectId) {
		Person person = personService.getById(getPerson().getId());
		StatisticsDto statisticsDto = new StatisticsDto();
		// 分包商只看自己的----userId;江西电建查看项目部的----orgCode
		if (person.getIsJxdj() == 0) {
			statisticsDto.setPersonId(person.getId());
//			statisticsDto.setCompanyId(person.getCompanyId());
		} else {
			statisticsDto.setOrgCode(person.getOrgCode());
		}
		statisticsDto.setProjectId(projectId);
		return statistisService.operationActivities(statisticsDto);
	}

	@ApiOperation(value = "分包商app任务统计", notes = "分包商首页使用")
	@GetMapping("/task")
	public Object getTaskStatistics() {
		Person person = personService.getById(getPerson().getId());
		StatisticsDto statisticsDto = new StatisticsDto();
		statisticsDto.setUserId(person.getUserId());
		statisticsDto.setPersonId(person.getId());
		return statistisService.taskStatistics(statisticsDto);
	}

	/**
	 * 安全分析
	 *
	 * @return
	 */
	@RequestMapping(value = "/safety-analysis", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "统计-安全分析", notes = "统计-安全分析")
	public Object safetyAnalysis(Long projectId) {
		return statistisService.safetyAnalysis(getStatisticDto(projectId));
	}

	/**
	 * 知识分享
	 *
	 * @return
	 */
	@RequestMapping(value = "/knowledge-share", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "统计- 知识分享", notes = "统计- 知识分享")
	public Object knowledgeShare(Long projectId) {
		return statistisService.knowledgeShare(getStatisticDto(projectId));
	}

	/**
	 * 生成统计dto
	 *
	 * @param projectId
	 * @return
	 */
	private StatisticsDto getStatisticDto(Long projectId) {
		Person person = personService.getById(getPerson().getId());
		PersonAscription ascription = personAscriptionService.getOne(
				new LambdaQueryWrapper<PersonAscription>().eq(PersonAscription::getPersonId, getPerson().getId()));
		StatisticsDto statisticsDto = new StatisticsDto();
		if (projectId != null) {
			statisticsDto.setProjectId(projectId);
		}
		// 分包商只看自己的----userId;江西电建查看项目部的----orgCode
		if (person.getIsJxdj() == 0) {
			statisticsDto.setPersonId(person.getId());
			statisticsDto.setCompanyId(ascription.getCompanyId());
		} else {
			statisticsDto.setOrgCode(person.getOrgCode());
		}
		return statisticsDto;
	}

	/**
	 * 获取项目部首页统计--小程序使用
	 *
	 * @return
	 */
	@RequestMapping(value = "/home/project/statistics", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "小程序-项目部首页统计", notes = "小程序-项目部首页统计")
	public Map<String, Integer> getProjectDepartmentStatistics() {
		Person person = personService.getById(getPerson().getId());
		StatisticsDto statisticsDto = new StatisticsDto();
		// statisticsDto.setPersonId(person.getId());
		statisticsDto.setOrgCode(person.getOrgCode());
		return statistisService.getProjectStatistics(statisticsDto);
	}

	@ApiOperation(value = "分包商app任务统计明细", notes = "分包商首页使用")
	@GetMapping("/task/detail")
	public List getTaskDetail() {
		AgencyUserModel userInfo = getUserInfo();
		return statistisService.getTaskDetail(userInfo.getSequenceNbr(), userInfo.getUserId());
	}

	@ApiOperation(value = "热门知识", notes = "热门知识，分包商首页使用")
	@GetMapping("/knowledge/random-list")
	public List getKnowledgeRandomList(@RequestParam Integer total) {
		buildRequestContext();
		return statistisService.getKnowledgeRandomList(total);
	}

	@ApiOperation(value = "待办任务状态", notes = "待办任务状态，首页小红点")
	@GetMapping("/myTodo/status")
	public Object getTaskDealStatus(@RequestParam(required = false) Long companyId,
			@RequestParam(required = false) Long projectId) {
		Person person = getPerson();
		return statistisService.getTaskDealStatus(person, companyId, projectId);
	}

	/**
	 * 违章排名
	 *
	 * @return
	 */
	@GetMapping(value = "violation/rank")
	@ApiOperation(value = "违章排名", notes = "违章排名")
	public Object violationRank(@ApiParam(value = "排序字段", required = false) Long projectId,
			@ApiParam(value = "排序字段", required = true, defaultValue = "num", example = "num") String key,
			@ApiParam(value = "排序方式", required = true, defaultValue = "desc", example = "desc 倒序， asc 正序") String sortType,
			@ApiParam(value = "分页") CommonPageableDto pageable) {
		try {
			String orgCode = platformUtils.getOrgCode();
			IPage<Object> page = taskService.violationRank(pageable, key, sortType, orgCode, projectId);
			return page;
		} catch (Exception e) {
			return CommonResponseUtil.failure(e.getMessage());
		}
	}

	/**
	 * 风险作业 分页列表
	 *
	 * @param pageable
	 * @param status
	 * @return
	 */
	@GetMapping(value = "risk/list")
	@ApiOperation(value = "风险作业 分页列表", notes = "风险作业 分页列表")
	@ApiImplicitParam(value = "status", defaultValue = "0", example = "查询状态 0-进行中 1-已完成")
	public Object riskList(@ApiParam(value = "分页") CommonPageableDto pageable,
			@RequestParam(value = "status", defaultValue = "0") Integer status, TaskRiskControlVo taskRiskControlVo) {
		String orgCode = platformUtils.getOrgCode();
		if (status == null) {
			status = 0;
		}
		try {
			IPage<Object> page = taskRiskControlService.riskWorkPageInfo(pageable, orgCode, status, taskRiskControlVo);
			return page;
		} catch (Exception e) {
			return CommonResponseUtil.failure(e.getMessage());
		}
	}

	/**
	 * 反违章任务 分页列表
	 *
	 * @param pageable
	 * @param status
	 * @return
	 */
	@GetMapping(value = "anti/violation/list")
	@ApiOperation(value = "反违章任务 分页列表", notes = "反违章任务 分页列表")
	@ApiImplicitParam(value = "status", defaultValue = "0", example = "查询状态 0-进行中 1-已完成")
	public Object antViolationList(@ApiParam(value = "分页") CommonPageableDto pageable,
			@RequestParam(value = "status", defaultValue = "0") Integer status,
			@RequestParam(value = "projectId", required = false) Long projectId) {
		String orgCode = platformUtils.getOrgCode();
		if (status == null) {
			status = 0;
		}
		try {
			IPage<Object> page = taskRiskControlService.antiViolationPageInfo(pageable, orgCode, status, projectId);
			return page;
		} catch (Exception e) {
			return CommonResponseUtil.failure(e.getMessage());
		}
	}

	/**
	 * 风险作业详情
	 *
	 * @param id
	 * @return
	 */
	@GetMapping(value = "risk/detail")
	@ApiOperation(value = "风险作业详情", notes = "风险作业详情")
	public Object riskDetail(@RequestParam(value = "id") Long id) {
		if (id == null) {
			return CommonResponseUtil.failure("参数 id 为空");
		}
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			// 统计累计入场 当前入场
			map = (Map<String, Object>) taskRiskControlService.personStatistics(id);
			// 专业人员
			List<TaskWorkPersonVo> listPro = taskRiskControlService.riskPersonList(id,
					TaskPersonTypeEnum.PRO_WORKER.getValue());
			listPro.forEach(i -> i.setHeadPhoto(fileServerUrl + i.getHeadPhoto()));
			map.put("listPro", listPro);
			// 辅助人员
			List<TaskWorkPersonVo> listAssist = taskRiskControlService.riskPersonList(id,
					TaskPersonTypeEnum.ASSIST_WORKER.getValue());
			listAssist.forEach(i -> i.setHeadPhoto(fileServerUrl + i.getHeadPhoto()));
			map.put("listAssist", listAssist);
			// 详细信息
			TaskRiskControlDetailVo taskRiskControlDetailVo = taskRiskControlService.taskRiskDetail(id);
			map.put("riskDetailInfo", taskRiskControlDetailVo);
			return map;
		} catch (Exception e) {
			return CommonResponseUtil.failure(e.getMessage());
		}
	}

	/**
	 * 需要办理的风险作业
	 *
	 * @return
	 */
	@GetMapping(value = "risk/need")
	@ApiOperation(value = "需要办理的风险作业", notes = "需要办理的风险作业")
	public Object riskNeedProcessList(Long projectId) {
		String orgCode = platformUtils.getOrgCode();
		try {
			// 详细信息
			List<TaskRiskControlDetailVo> list = taskRiskControlService.riskNeedProcessList(orgCode, projectId);
			return list == null ? new ArrayList<TaskRiskControlDetailVo>() : list;
		} catch (Exception e) {
			return CommonResponseUtil.failure(e.getMessage());
		}
	}

	/**
	 * 作业活动分页列表
	 *
	 * @param pageable
	 * @param workActivityVo
	 * @return
	 */
	@RequestMapping(value = "/work/activity/page", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "作业活动列表", notes = "作业活动列表")
	public Object workActivityPage(@ApiParam(value = "分页") CommonPageableDto pageable,
			@ApiParam(value = "查询参数") WorkActivityVo workActivityVo) {
		String orgCode = platformUtils.getOrgCode();
		workActivityVo.setOrgCode(orgCode);
		IPage<WorkActivityVo> page = statistisService.workActivityPageInfo(workActivityVo, pageable);
		return page;
	}

	/**
	 * 获取orgcode
	 *
	 * @return
	 */
	@GetMapping(value = "get/orgcode")
	@ApiOperation(value = "获取orgCode", notes = "获取orgCode")
	public Object getOrgCode() {
		String orgCode = platformUtils.getOrgCode();
		return orgCode == null ? "null" : orgCode;
	}

}
