package com.yeejoin.precontrol.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

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

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yeejoin.amos.boot.module.common.api.dto.CreatExamDto;
import com.yeejoin.amos.boot.module.common.api.feign.KnowledgebaseFeignClient;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.model.RoleModel;
import com.yeejoin.precontrol.common.dto.CommonPageableDto;
import com.yeejoin.precontrol.common.dto.SingBadManagementDto;
import com.yeejoin.precontrol.common.dto.SingJobDisclosureDto;
import com.yeejoin.precontrol.common.dto.SingTaskPayCheckDto;
import com.yeejoin.precontrol.common.dto.StudioPageableDto;
import com.yeejoin.precontrol.common.dto.TaskDto;
import com.yeejoin.precontrol.common.dto.TaskPageDto;
import com.yeejoin.precontrol.common.entity.BadManagement;
import com.yeejoin.precontrol.common.entity.Person;
import com.yeejoin.precontrol.common.entity.PersonCondition;
import com.yeejoin.precontrol.common.entity.Project;
import com.yeejoin.precontrol.common.entity.Task;
import com.yeejoin.precontrol.common.entity.TaskPaycheck;
import com.yeejoin.precontrol.common.entity.TaskPerson;
import com.yeejoin.precontrol.common.entity.TaskPersonFile;
import com.yeejoin.precontrol.common.entity.TaskRiskControl;
import com.yeejoin.precontrol.common.entity.TaskRiskControlPrePerson;
import com.yeejoin.precontrol.common.entity.TaskRiskControlTech;
import com.yeejoin.precontrol.common.entity.TaskTechDocument;
import com.yeejoin.precontrol.common.enums.MessageAttributeEnum;
import com.yeejoin.precontrol.common.enums.MessageSubTypeEnum;
import com.yeejoin.precontrol.common.enums.MessageTypeEnum;
import com.yeejoin.precontrol.common.enums.StatusEnum;
import com.yeejoin.precontrol.common.enums.TaskPersonTypeEnum;
import com.yeejoin.precontrol.common.enums.TaskStatusEnum;
import com.yeejoin.precontrol.common.enums.TaskTypeEnum;
import com.yeejoin.precontrol.common.enums.WeChatMsgTemplateTypeEum;
import com.yeejoin.precontrol.common.exception.BaseException;
import com.yeejoin.precontrol.common.exception.errorEnum.BaseExceptionEnum;
import com.yeejoin.precontrol.common.mapper.PersonMapper;
import com.yeejoin.precontrol.common.publish.MessageEventPublish;
import com.yeejoin.precontrol.common.publish.StatusEventPublish;
import com.yeejoin.precontrol.common.publish.TranslateEventPublish;
import com.yeejoin.precontrol.common.service.FileService;
import com.yeejoin.precontrol.common.service.IBadManagementService;
import com.yeejoin.precontrol.common.service.ICompanyService;
import com.yeejoin.precontrol.common.service.IHazardousWorkResultService;
import com.yeejoin.precontrol.common.service.IHazardousWorkService;
import com.yeejoin.precontrol.common.service.IPersonConditionService;
import com.yeejoin.precontrol.common.service.IPersonService;
import com.yeejoin.precontrol.common.service.IProjectService;
import com.yeejoin.precontrol.common.service.ITaskPaycheckService;
import com.yeejoin.precontrol.common.service.ITaskPersonFileService;
import com.yeejoin.precontrol.common.service.ITaskPersonService;
import com.yeejoin.precontrol.common.service.ITaskRiskControlPrePersonService;
import com.yeejoin.precontrol.common.service.ITaskRiskControlService;
import com.yeejoin.precontrol.common.service.ITaskRiskControlTechService;
import com.yeejoin.precontrol.common.service.ITaskService;
import com.yeejoin.precontrol.common.service.ITaskTechDocumentService;
import com.yeejoin.precontrol.common.service.ITechDocumentAttachmentTemplateService;
import com.yeejoin.precontrol.common.service.PdfService;
import com.yeejoin.precontrol.common.service.SmallProService;
import com.yeejoin.precontrol.common.utils.DateUtils;
import com.yeejoin.precontrol.common.utils.PersonUtils;
import com.yeejoin.precontrol.common.utils.StringUtil;
import com.yeejoin.precontrol.common.vo.ReginParams;
import com.yeejoin.precontrol.common.vo.RewardAndRetributionListVo;
import com.yeejoin.precontrol.common.vo.TaskPageVo;
import com.yeejoin.precontrol.controller.publics.BaseController;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;

/**
 * 作业活动
 *
 * @author duanwei
 * @date 2020-06-30
 */
@RestController
@Api(tags = "作业活动Api")
@RequestMapping(value = "/task", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Slf4j
public class TaskController extends BaseController {
	/**
	 * 任务服务
	 */
	@Autowired
	ITaskService iTaskService;
	/**
	 * 任务与附件关系服务
	 */
	@Autowired
	ITaskPersonFileService iTaskPersonFileService;
	/**
	 * 任务与人服务
	 */
	@Autowired
	ITaskPersonService iTaskPersonService;
	/**
	 * 三交三查服务
	 */
	@Autowired
	ITaskPaycheckService iTaskPaycheckService;
	/**
	 * 违章管理服务
	 */
	@Autowired
	IBadManagementService iBadManagementService;
	/**
	 * 人员服务
	 */
	@Autowired
	IPersonService iPersonService;
	/**
	 * 工程服务
	 */
	@Autowired
	IProjectService iProjectService;
	/**
	 * 任务与文档服务
	 */
	@Autowired
	ITaskTechDocumentService iTaskTechDocumentService;
	/**
	 * 企业服务
	 */
	@Autowired
	ICompanyService iCompanyService;
	/**
	 * pdf转换服务
	 */
	@Autowired
	PdfService pdfService;
	/**
	 * 文档与附件服务
	 */
	@Autowired
	ITechDocumentAttachmentTemplateService iTechDocumentAttachmentTemplateService;
	/**
	 * 危险作业服务
	 */
	@Autowired
	IHazardousWorkService iHazardousWorkService;
	/**
	 * 危险作业结果服务
	 */
	@Autowired
	IHazardousWorkResultService iHazardousWorkResultService;

	/**
	 * 文件服务
	 */
	@Autowired
	FileService fileService;
	/**
	 * 翻译事件服务
	 */
	@Autowired
	TranslateEventPublish translateEventPublish;
	/**
	 * 状态事件服务
	 */
	@Autowired
	StatusEventPublish statusEventPublish;
	/**
	 * 知识库服务
	 */
	@Autowired
	KnowledgebaseFeignClient knowledgeBaseFeign;

	@Autowired
	IPersonConditionService iPersonConditionService;
	@Autowired
	MessageEventPublish messageEventPublish;
	@Autowired
	IPersonService personService;
	@Autowired
	ITaskRiskControlService iTaskRiskControlService;
	@Autowired
	ITaskRiskControlTechService iTaskRiskControlTechService;
	@Autowired
	ITaskRiskControlPrePersonService iTaskRiskControlPrePersonService;
	/**
	 * 产品号
	 */
	@Value("${admin.product}")
	String product;
	/**
	 * 产品密钥
	 */
	@Value("${admin.appkey}")
	String appkey;

	/**
	 * 账户
	 */
	@Value("${admin.user}")
	String user;
	/**
	 * 密码
	 */
	@Value("${admin.password}")
	String password;

	@Autowired
	SmallProService smallProService;

	@Autowired
	PersonUtils personUtils;

	@Autowired
	PersonMapper personMapper;

	/**
	 * 新增技术交底
	 *
	 * @return
	 */
	@RequestMapping(value = "/saveJobDisclosure", method = RequestMethod.POST)
	@ApiOperation(httpMethod = "POST", value = "新增作业活动-技术交底", notes = "新增作业活动-技术交底")
	public boolean saveJobDisclosure(@RequestBody SingJobDisclosureDto singJobDisclosureDto) {
		Person person = getPerson();
		List<Long> safetyOfficerId = singJobDisclosureDto.getSafetyOfficerId();
		// 项目部技术员只需判断本项目安全员是否必选
		if ("technician".equals(person.getRoleKey())) {
			boolean security = checkTaskUser(safetyOfficerId, "security");
			if (!security) {
				throw new BaseException("必选本项目部安全员");
			}
		}
		// 分包商只需判断本分包商安全员是否必选
		if ("fbs_technician".equals(person.getRoleKey())) {
			boolean fbs_security = checkTaskUser(safetyOfficerId, "fbs_security");
			if (!fbs_security) {
				throw new BaseException("必选本分包商安全员");
			}
		}
		iTaskService.saveJobDisclosure(singJobDisclosureDto, person);
		return true;
	}

	/**
	 * 新增三交三查 业务上属于交底任务
	 *
	 * @return
	 */
	@RequestMapping(value = "/saveTaskPayCheck", method = RequestMethod.POST)
	@ApiOperation(httpMethod = "POST", value = "新增作业活动-三交三查", notes = "新增作业活动-三交三查")
	public boolean saveTaskPayCheck(@RequestBody SingTaskPayCheckDto singTaskPayCheckDto) {
		Person person = getPerson();
		setPlatFormAccess();
		// 校验

		if (StringUtil.isNotEmpty(singTaskPayCheckDto.getTechnicianId())) {
			checkTaskUser(singTaskPayCheckDto.getTechnicianId(), "项目部和分包商技术员必须各选择1个", "technician", "fbs_technician");
		}
		if (StringUtil.isNotEmpty(singTaskPayCheckDto.getEngineeringStaffId())) {
			checkTaskUser(singTaskPayCheckDto.getEngineeringStaffId(), "项目部工程员和分包商主管必须各选择1个", "project",
					"fbs_director");
		}
		iTaskService.saveTaskPayCheck(singTaskPayCheckDto, person);
		return true;
	}

	/**
	 * 更新三交三查
	 *
	 * @return
	 */
	@RequestMapping(value = "/updatePayCheck", method = RequestMethod.PUT)
	@ApiOperation(httpMethod = "PUT", value = "更新作业活动-三交三查", notes = "更新作业活动-三交三查")
	public boolean updatePayCheck(@RequestBody SingTaskPayCheckDto singTaskPayCheckDto) {
		Person person = getPerson();
		iTaskService.updatePayCheck(singTaskPayCheckDto, person);
		return true;
	}

	/**
	 * 新增违规管理
	 *
	 * @return
	 */
	@RequestMapping(value = "/saveBadManagement", method = RequestMethod.POST)
	@ApiOperation(httpMethod = "POST", value = "新增作业活动-违规管理", notes = "新增作业活动-违规管理")
	public boolean saveSingBadManagement(@RequestBody SingBadManagementDto singBadManagementDto) {
		Person curPerson = getPerson();
		iTaskService.saveBadManagement(singBadManagementDto, curPerson);
		return true;
	}

	/**
	 * 更新违规管理
	 *
	 * @return
	 */
	@RequestMapping(value = "/updateBadManagement", method = RequestMethod.PUT)
	@ApiOperation(httpMethod = "PUT", value = "更新作业活动-违规管理", notes = "更新作业活动-违规管理")
	public boolean updateBadManagement(@RequestBody SingBadManagementDto singBadManagementDto) {
		Person curPerson = getPerson();
		iTaskService.updateBadManagement(singBadManagementDto, curPerson);
		return true;
	}

	/**
	 * 根据id删除
	 *
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
	@ApiOperation(httpMethod = "DELETE", value = "根据id删除", notes = "根据id删除")
	public boolean deleteById(@PathVariable Long id) {
		if (id == null) {
			throw new BaseException(BaseExceptionEnum.DATA_NOT_EXISTS);
		}
		iTaskService.removeById(id);
		iBadManagementService.remove(
				new LambdaQueryWrapper<BadManagement>().select(BadManagement::getId).eq(BadManagement::getTaskId, id));
		iTaskPaycheckService.remove(
				new LambdaQueryWrapper<TaskPaycheck>().select(TaskPaycheck::getId).eq(TaskPaycheck::getTaskId, id));
		iTaskPersonService
				.remove(new LambdaQueryWrapper<TaskPerson>().select(TaskPerson::getId).eq(TaskPerson::getTaskId, id));
		iTaskPersonFileService.remove(new LambdaQueryWrapper<TaskPersonFile>().select(TaskPersonFile::getId)
				.eq(TaskPersonFile::getTaskId, id));
		iTaskTechDocumentService.remove(new LambdaQueryWrapper<TaskTechDocument>().select(TaskTechDocument::getId)
				.eq(TaskTechDocument::getTaskId, id));
		iTaskRiskControlService.remove(new LambdaQueryWrapper<TaskRiskControl>().eq(TaskRiskControl::getTaskId, id));
		iTaskRiskControlPrePersonService
				.remove(new LambdaQueryWrapper<TaskRiskControlPrePerson>().eq(TaskRiskControlPrePerson::getTaskId, id));
		iTaskRiskControlTechService
				.remove(new LambdaQueryWrapper<TaskRiskControlTech>().eq(TaskRiskControlTech::getTaskId, id));
		return true;
	}

	/**
	 * 根据id删除
	 *
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "ids/{ids}", method = RequestMethod.DELETE)
	@ApiOperation(httpMethod = "DELETE", value = "根据id删除", notes = "根据id删除")
	public boolean deleteById(@PathVariable String ids) {
		if (StringUtils.isNotBlank(ids)) {
			String[] idsSplit = ids.split(",");
			Set<Long> comIds = Arrays.stream(idsSplit).map(Long::parseLong).collect(Collectors.toSet());
			for (Long id : comIds) {
				iTaskService.removeById(id);
				iBadManagementService.remove(new LambdaQueryWrapper<BadManagement>().select(BadManagement::getId)
						.eq(BadManagement::getTaskId, id));
				iTaskPaycheckService.remove(new LambdaQueryWrapper<TaskPaycheck>().select(TaskPaycheck::getId)
						.eq(TaskPaycheck::getTaskId, id));
				iTaskPersonService.remove(
						new LambdaQueryWrapper<TaskPerson>().select(TaskPerson::getId).eq(TaskPerson::getTaskId, id));
				iTaskPersonFileService.remove(new LambdaQueryWrapper<TaskPersonFile>().select(TaskPersonFile::getId)
						.eq(TaskPersonFile::getTaskId, id));
				iTaskTechDocumentService.remove(new LambdaQueryWrapper<TaskTechDocument>()
						.select(TaskTechDocument::getId).eq(TaskTechDocument::getTaskId, id));
				iTaskRiskControlService
						.remove(new LambdaQueryWrapper<TaskRiskControl>().eq(TaskRiskControl::getTaskId, id));
				iTaskRiskControlPrePersonService.remove(
						new LambdaQueryWrapper<TaskRiskControlPrePerson>().eq(TaskRiskControlPrePerson::getTaskId, id));
				iTaskRiskControlTechService
						.remove(new LambdaQueryWrapper<TaskRiskControlTech>().eq(TaskRiskControlTech::getTaskId, id));
			}
		}

		return true;
	}

	/**
	 * 查看技术交底
	 *
	 * @return
	 */
	@RequestMapping(value = "/getJobDisclosure", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "获取作业活动-技术交底", notes = "获取作业活动-技术交底")
	public Object getJobDisclosure(Long taskId,Long taskPersonId) {
		return iTaskService.getJobDisclosure(taskId,taskPersonId);
	}

	/**
	 * 查看三交三查
	 *
	 * @return
	 */
	@RequestMapping(value = "/getTaskPayCheck", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "获取作业活动-三交三查", notes = "获取作业活动-三交三查")
	public Object getTaskPayCheck(Long taskId,Long taskPersonId) {
		return iTaskService.getTaskPayCheck(taskId,taskPersonId);
	}

	/**
	 * 查看违规管理
	 *
	 * @return
	 */
	@RequestMapping(value = "/getBadManagement", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "获取作业活动-违规管理", notes = "获取作业活动-违规管理")
	public Object getBadManagement(Long taskId,Long taskPersonId) {
		Person person = getPerson();
		return iTaskService.getBadManagement(taskId, person.getId(),taskPersonId);
	}

	/**
	 * 根据id查询
	 *
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "根据id查询", notes = "根据id查询")
	public Object selectById(@PathVariable Long id,Long taskPersonId) {
		return iTaskService.selectById(id,taskPersonId);
	}

	/**
	 * 列表分页查询
	 *
	 * @return
	 */
	@RequestMapping(value = "/new/{id}", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "根据id查询", notes = "根据id查询")
	public Object newSelectById(@PathVariable Long id,Long taskPersonId) {
		return iTaskService.newSelectById(id,taskPersonId);
	}

	/**
	 * 导出doc 嵌套html渲染
	 *
	 * @return
	 */
	@RequestMapping(value = "/exportDoc", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "任务导出doc", notes = "任务导出doc")
	public String exportDoc(HttpServletRequest request, HttpServletResponse response, Long id) throws IOException {
		return iTaskService.exportDoc(id, request, response);
	}

	/**
	 * 任务阅读反馈
	 *
	 * @return
	 */
	@RequestMapping(value = "/read", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "任务阅读反馈", notes = "任务阅读反馈")
	public Object read(Long taskPersonId) {
		TaskPerson taskPerson = iTaskPersonService.getById(taskPersonId);
		if (taskPerson == null) {
			throw new BaseException("taskPersonId为空");
		}
		taskPerson.setReadStatus(StatusEnum.SUCCESS.getValue());
		taskPerson.setReadTime(new Date());
		iTaskPersonService.updateById(taskPerson);
		Long taskId = taskPerson.getTaskId();
		Task task = iTaskService.getById(taskId);
		// 技术交底一个人两个角色特殊处理
		if (TaskTypeEnum.JOBDISCLOSURE.getValue().equals(task.getType())) {
			List<TaskPerson> samePersonList = iTaskPersonService.list(new LambdaQueryWrapper<TaskPerson>()
					.eq(TaskPerson::getTaskId, taskId).eq(TaskPerson::getPersonId, taskPerson.getPersonId()));
			samePersonList.forEach(i -> {
				i.setReadStatus(StatusEnum.SUCCESS.getValue());
				taskPerson.setReadTime(new Date());
			});
			iTaskPersonService.updateBatchById(samePersonList);
		}
		// 当人员的状态已经都为1的时候 则代表任务完结
		List<TaskPerson> list = iTaskPersonService.list(new LambdaQueryWrapper<TaskPerson>()
				.eq(TaskPerson::getReadStatus, 0).eq(TaskPerson::getTaskId, taskId));
		if (StringUtil.isEmpty(list)) {
			task.setStatus(TaskStatusEnum.COMPLETED.getLongType());
			task.setEndTime(new Date());
			iTaskService.updateById(task);
			// 完成消息通知：违章检查任务执行完成之后、知识推送任务执行完成之后、技术交底任务执行完成之后、风险作业任务执行完成之后
			JSONArray jsonArray = new JSONArray();
			JSONObject msg = new JSONObject();
			MessageSubTypeEnum messageSubTypeEnum = this.getMessageSubTypEum(String.valueOf(task.getType()));
			if (messageSubTypeEnum != null) {
				msg.put(MessageAttributeEnum.MSG_TYPE.getName(), MessageTypeEnum.SERVICE_REMINDER.getType());
				msg.put(MessageAttributeEnum.MSG_SUB_TYPE.getName(), messageSubTypeEnum.getType());
				msg.put(MessageAttributeEnum.CONTENT.getName(), messageSubTypeEnum.getTip());
				msg.put(MessageAttributeEnum.PERSON_ID.getName(), task.getCreatePersonId());
				msg.put(MessageAttributeEnum.TASK_ID.getName(), task.getId());
				msg.put(MessageAttributeEnum.PARAM.getName(), 99); // 任务已完成 stage = 99
				jsonArray.add(msg);
				JSONObject obj = new JSONObject();
				obj.put("param", jsonArray);
				messageEventPublish.publish(obj);
			}

			Project project = iProjectService.getById(task.getProjectId());
			// 微信服务通知
			Set<Long> set = personUtils.getWXTaskBasicPerson(taskId);
			List<Person> persons = iPersonService
					.list(new LambdaQueryWrapper<Person>().in(Person::getId, set).isNotNull(Person::getOpenId));
			List<String> openIds = persons.stream().map(Person::getOpenId).collect(Collectors.toList());
			List<String> messages = new ArrayList<>();
			messages.add(project.getName());
			messages.add(TaskTypeEnum.getLabelByValue(task.getType()));
			messages.add(DateUtils.getDateNowString());
			messages.add(TaskTypeEnum.getLabelByValue(task.getType()) + "任务完成消息通知");
			smallProService.sendWeChatUpcomingMessage(openIds, WeChatMsgTemplateTypeEum.SERVICE_COMPLETE.getValue(),
					messages);
		}

		// 更新注册时的知识分享任务状态
		if (TaskTypeEnum.KNOWLEDGE_SHARE.getValue().equals(task.getType())) {
			PersonCondition personCondition = iPersonConditionService.getOne(
					new LambdaQueryWrapper<PersonCondition>().eq(PersonCondition::getPersonId, taskPerson.getPersonId())
							.eq(PersonCondition::getKnowledgeTaskId, task.getId()));
			if (personCondition != null && personCondition.getKnowledgeStatus() == 0) {
				personCondition.setKnowledgeStatus(1);
				iPersonConditionService.updateById(personCondition);
			}
		}

		// 推送状态更改消息
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("name", "read");
		jsonObject.put("taskId", taskId);
		statusEventPublish.publish(jsonObject);
		return true;
	}

	private MessageSubTypeEnum getMessageSubTypEum(String type) {
		switch (type) {
		case "2":
			return MessageSubTypeEnum.SERVICE_REMINDER_VIOLATION_FINISHED;
		case "6":
			return MessageSubTypeEnum.SERVICE_REMINDER_KNOWLEDGE_PUSH_FINISHED;
		case "0":
			return MessageSubTypeEnum.SERVICE_REMINDER_TECHNICAL_DISCLOSURE_FINISHED;
		case "3":
			return MessageSubTypeEnum.SERVICE_REMINDER_RISK_WORK_FINISHED;
		default:
			return null;
		}
	}

	/**
	 * 列表分页查询
	 *
	 * @return
	 */
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "列表分页查询", notes = "列表分页查询")
	public Object listPage(@ApiParam(value = "分页条件 isAll=0 具体分页必传") CommonPageableDto pageable,
			@ApiParam(value = "查询参数") TaskPageDto taskPageDto,
			@ApiParam(value = "类型 0查询列表 1 导出列表") @RequestParam Long operType,
			@ApiParam(value = "查询Ids") @RequestParam(required = false) List<Long> ids, HttpServletResponse response) {
		ReginParams reginInfo = getReginInfo();
		boolean fbsRole = isFbsRole(reginInfo);
		return iTaskService.list(reginInfo, fbsRole, pageable, taskPageDto, operType, ids, response);

	}

	/**
	 * 我的待办
	 *
	 * @return
	 */
	@RequestMapping(value = "/myTodoList", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "我的待办仅仅自己", notes = "我的待办仅仅自己")
	public Object myTodoList(@ApiParam(value = "分页条件 isAll=0 具体分页必传") CommonPageableDto pageable,
			@ApiParam(value = "查询参数") TaskPageDto taskPageDto, HttpServletResponse response) {
		Person person = personService.getById(getPerson().getId());
		// 分包商只看自己的----userId;江西电建查看项目部的----orgCode
		if (person.getIsJxdj() == 0) {
			taskPageDto.setUserId(person.getId());
			//taskPageDto.setOrgCode("");
		} else {
			taskPageDto.setOrgCode(person.getOrgCode());
			taskPageDto.setUserId(person.getId());
		}
		IPage<TaskPageVo> page = iTaskService.myToDoListByPage(pageable, taskPageDto, person.getId());
		return page;
	}

	/**
	 * 我的待办数量
	 *
	 * @return
	 */
	@RequestMapping(value = "/todoListNum", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "我的待办", notes = "我的待办")
	public Object todoListNum(@ApiParam(value = "查询参数") TaskPageDto taskPageDto, HttpServletResponse response) {
		// 获取用户id 创建人的
		Person person = getPerson();
		taskPageDto.setUserId(person.getId());
		IPage<TaskPageVo> page = iTaskService.listByPage(new CommonPageableDto(), taskPageDto);
		return page.getTotal();
	}

	/**
	 * 查看任务是否允许操作
	 *
	 * @return
	 */
	@RequestMapping(value = "/taskIsOperOk", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "任务是否允许操作", notes = "任务是否允许操作")
	public Object taskIsOperOk(Long executeUserId) {
		Person person = getPerson();
		Long personId = person.getId();
		if (executeUserId != null && executeUserId.equals(personId)) {
			return true;
		}
		return false;
	}

	/**
	 * 审核任务
	 *
	 * @return
	 */
	@RequestMapping(value = "/audit", method = RequestMethod.POST)
	@ApiOperation(httpMethod = "POST", value = "审核任务", notes = "审核任务")
	public Object audit(@RequestBody TaskDto taskDto) {
		Person curPerson = getPerson();
		Task task = new Task();
		task.setId(taskDto.getId());
		task.setStatus(taskDto.getStatus());
		TaskPerson taskPerson = new TaskPerson();
		taskPerson.setReadStatus(StatusEnum.SUCCESS.getValue());
		taskPerson.setReadTime(new Date());
		iTaskPersonService.update(taskPerson, new LambdaQueryWrapper<TaskPerson>()
				.eq(TaskPerson::getTaskId, taskDto.getId()).eq(TaskPerson::getPersonId, curPerson.getId()));
		if (taskDto.getStatus() == TaskStatusEnum.RETURNED.getLongType()) {
			TaskPerson createPerson = new TaskPerson();
			createPerson.setReadStatus(StatusEnum.UNFINISHED.getValue());
			iTaskPersonService.update(createPerson,
					new LambdaQueryWrapper<TaskPerson>().eq(TaskPerson::getTaskId, taskDto.getId())
							.eq(TaskPerson::getType, TaskPersonTypeEnum.SPONSORVIOLATION.getValue()));
		}
		iTaskService.updateById(task);
		translateEventPublish.publish(task);

		// 审核通过后，通知分包商负责人进行执行--违规任务
		Task newTask = iTaskService.getById(taskDto.getId());
		if (TaskStatusEnum.UNCOMPLETED.getType() == taskDto.getStatus()
				&& newTask.getType().equals(TaskTypeEnum.BAD.getValue())) {

			// 保存分包商负责人
			TaskPerson liablePerson = new TaskPerson();
			BadManagement badManagement = iBadManagementService
					.getOne(new LambdaQueryWrapper<BadManagement>().eq(BadManagement::getTaskId, newTask.getId()));
			liablePerson.setTaskId(newTask.getId());
			liablePerson.setPersonId(badManagement.getPersonLiable());
			Person person = iPersonService.getById(badManagement.getPersonLiable());
			liablePerson.setPersonName(person.getName());
			liablePerson.setType(TaskPersonTypeEnum.SUBCONTRACTOR.getValue());
			liablePerson.setReadStatus(StatusEnum.UNFINISHED.getValue());
			liablePerson.setCompanyId(badManagement.getCompanyId());
			iTaskPersonService.save(liablePerson);

			// 发起人发消息
			JSONArray jsonArray = new JSONArray();
			JSONObject msg = new JSONObject();
			msg.put(MessageAttributeEnum.MSG_TYPE.getName(), MessageTypeEnum.VIOLATION_INSPECTION.getType());
			msg.put(MessageAttributeEnum.MSG_SUB_TYPE.getName(), MessageSubTypeEnum.VIOLATION_INSPECTION_NEW.getType());
			msg.put(MessageAttributeEnum.CONTENT.getName(), MessageSubTypeEnum.VIOLATION_INSPECTION_NEW.getTip());
			msg.put(MessageAttributeEnum.TASK_ID.getName(), newTask.getId());
			msg.put(MessageAttributeEnum.PERSON_ID.getName(), newTask.getCreatePersonId());
			jsonArray.add(msg);

			// 分包商发消息
			JSONObject liableMsg = new JSONObject();
			liableMsg.put(MessageAttributeEnum.MSG_TYPE.getName(), MessageTypeEnum.VIOLATION_INSPECTION.getType());
			liableMsg.put(MessageAttributeEnum.MSG_SUB_TYPE.getName(),
					MessageSubTypeEnum.VIOLATION_INSPECTION_TODO.getType());
			liableMsg.put(MessageAttributeEnum.CONTENT.getName(),
					MessageSubTypeEnum.VIOLATION_INSPECTION_TODO.getTip());
			liableMsg.put(MessageAttributeEnum.PERSON_ID.getName(), liablePerson.getPersonId());
			liableMsg.put(MessageAttributeEnum.TASK_ID.getName(), newTask.getId());
			jsonArray.add(liableMsg);

			// 分包商违章检查:
			JSONObject obj = new JSONObject();
			obj.put("param", jsonArray);
			messageEventPublish.publish(obj);

			// 微信服务通知
			List<Person> persons = iPersonService.list(new LambdaQueryWrapper<Person>()
					.in(Person::getId, Arrays.asList(badManagement.getPersonLiable())).isNotNull(Person::getOpenId));
			List<String> openIds = persons.stream().map(Person::getOpenId).collect(Collectors.toList());
			List<String> messages = new ArrayList<>();
			messages.add(smallProService.getName());
			messages.add(badManagement.getNature());
			messages.add(badManagement.getType());
			messages.add(DateUtils.getDateNowString());
			smallProService.sendWeChatUpcomingMessage(openIds, WeChatMsgTemplateTypeEum.TODO.getValue(), messages);
		} else if (TaskStatusEnum.RETURNED.getType() == taskDto.getStatus()
				&& newTask.getType().equals(TaskTypeEnum.BAD.getValue())) {
			// 发起人发消息
//			JSONArray jsonArray = new JSONArray();
//			JSONObject msg = new JSONObject();
//			msg.put(MessageAttributeEnum.MSG_TYPE.getName(), MessageTypeEnum.VIOLATION_INSPECTION.getType());
//			msg.put(MessageAttributeEnum.MSG_SUB_TYPE.getName(),
//					MessageSubTypeEnum.VIOLATION_INSPECTION_TODO.getType());
//			msg.put(MessageAttributeEnum.CONTENT.getName(), MessageSubTypeEnum.VIOLATION_INSPECTION_TODO.getTip());
//			msg.put(MessageAttributeEnum.TASK_ID.getName(), task.getId());
//			msg.put(MessageAttributeEnum.PERSON_ID.getName(), task.getCreatePersonId());
//			jsonArray.add(msg);
//			// 分包商违章检查:
//			JSONObject obj = new JSONObject();
//			obj.put("param", jsonArray);
//			messageEventPublish.publish(obj);
		}
		return true;
	}

	/**
	 * 重新提交作业活动-违规管理
	 *
	 * @return
	 */
	@RequestMapping(value = "/recommitBadManagement", method = RequestMethod.PUT)
	@ApiOperation(httpMethod = "PUT", value = "重新提交作业活动-违规管理", notes = "重新提交作业活动-违规管理")
	public boolean recommitBadManagement(@RequestBody SingBadManagementDto singBadManagementDto) {
		Person person = getPerson();
		iTaskService.recommitBadManagement(singBadManagementDto, person);
		return true;
	}

	/**
	 * 发起人查询自己的任务列表
	 *
	 * @return
	 */
	@RequestMapping(value = "/createPersonTask", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "发起人查询自己的任务列表", notes = "发起人查询自己的任务列表")
	public Object createPersonTask() {
		Person person = getPerson();
		return iTaskService.createPersonTask(person);
	}

	/**
	 * 校验用户
	 *
	 * @param userIds   用户id
	 * @param message   校验失败弹出消息
	 * @param roleNames 角色名称
	 */
	private void checkTaskUser(List<Long> userIds, String message, String... roleNames) {
		Set<Long> technicianUserIds = iPersonService.listByIds(userIds).stream().map(p -> p.getUserId())
				.collect(Collectors.toSet());
		List<AgencyUserModel> result = new ArrayList<>();
		technicianUserIds.forEach(item -> {
			AgencyUserModel agencyUserModel = Privilege.agencyUserClient.queryByUserId(item + "").getResult();
			result.add(agencyUserModel);
		});
		AtomicInteger user1Num = new AtomicInteger();
		AtomicInteger user2Num = new AtomicInteger();
		if (StringUtil.isNotEmpty(result)) {
			result.forEach(r -> {
				if (null != r.getOrgRoles() && r.getOrgRoles().size() > 0) {
					Map<Long, List<RoleModel>> orgRoles = r.getOrgRoles();
					for (Map.Entry<Long, List<RoleModel>> entry : orgRoles.entrySet()) {
						List<RoleModel> value = entry.getValue();
						for (RoleModel roleModel : value) {
							String roleName = roleModel.getRoleName();
							if (roleName.equals(roleNames[0])) {
								user1Num.getAndIncrement();
							}
							if (roleName.equals(roleNames[1])) {
								user2Num.getAndIncrement();
							}
						}
					}
				}
			});
			// 两种角色 如果小于1 说明没有 没有传就抛出异常
			if (user1Num.get() < 1 || user2Num.get() < 1) {
				throw new BaseException(message);
			}
		}
	}

	/**
	 * 校验用户 如果传入的人角色匹配 则数量大于0
	 *
	 * @param userIds  用户id
	 * @param roleName 角色名称
	 */
	private boolean checkTaskUser(List<Long> userIds, String roleName) {
		Set<Long> ids = iPersonService.listByIds(userIds).stream().map(p -> p.getUserId()).collect(Collectors.toSet());
		if (StringUtil.isNotEmpty(ids)) {
			List<Person> list = iPersonService
					.list(new LambdaQueryWrapper<Person>().in(Person::getId, userIds).eq(Person::getRoleKey, roleName));
			if (StringUtil.isNotEmpty(list)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 获取任务列表新
	 *
	 * @return
	 */
	@RequestMapping(value = "/myList", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "发起人查询自己的任务列表", notes = "发起人查询自己的任务列表")
	public Object myList(@ApiParam(value = "分页条件 isAll=0 具体分页必传") CommonPageableDto pageable,
			@ApiParam(value = "查询参数") TaskPageDto taskPageDto, HttpServletResponse response) {
		Person person = getPerson();
		taskPageDto.setUserId(person.getId());
		IPage<TaskPageVo> page = iTaskService.myListByPage(pageable, taskPageDto);
		return page;
	}

	@RequestMapping(value = "/exam/template/test", method = RequestMethod.POST)
	@ApiOperation(httpMethod = "POST", value = "通过模板进行考试", notes = "小程序使用")
	public Object examTemplateTest(@RequestBody CreatExamDto creatExamDto) {
		return iTaskService.examTemplateTest(creatExamDto);
	}

	/**
	 * 奖励惩罚 列表
	 * 
	 * @param pageable
	 * @param rewardVo
	 * @return
	 */
	@GetMapping("/violation/list")
	@ApiOperation(httpMethod = "GET", value = "违章 列表", notes = "违章列表")
	public IPage<RewardAndRetributionListVo> violationList(StudioPageableDto pageable,
			RewardAndRetributionListVo rewardVo) {
		return iTaskService.violationList(pageable, rewardVo);
	}

}
