package xiaoqu.home.open.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

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

import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
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.RestController;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.DesensitizedUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import xiaoqu.home.open.aop.AvoidRepeatSubmit;
import xiaoqu.home.open.controller.export.TaskTaskScenesExport;
import xiaoqu.home.open.controller.input.task.GridAndSceneInput;
import xiaoqu.home.open.controller.input.task.TaskInfoInspectPageInput;
import xiaoqu.home.open.controller.input.task.TaskTaskScenesPageInput;
import xiaoqu.home.open.controller.output.TaskTaskScenesOutput;
import xiaoqu.home.open.controller.output.task.TaskCancelProgress;
import xiaoqu.home.open.controller.output.task.TaskInfoInspectOutput;
import xiaoqu.home.open.controller.output.task.TaskInfoInspectStatusOutput;
import xiaoqu.home.open.controller.output.task.TaskInspectDetailOutput;
import xiaoqu.home.open.controller.output.task.TaskInspectScenes;
import xiaoqu.home.open.model.db1.User;
import xiaoqu.home.open.model.db2.FieldWebpageAuthority;
import xiaoqu.home.open.model.db2.InspectPic;
import xiaoqu.home.open.model.db2.TaskInfo;
import xiaoqu.home.open.model.db2.TaskScenes;
import xiaoqu.home.open.model.db2.TaskStatusLog;
import xiaoqu.home.open.model.db2.TaskTaskScenes;
import xiaoqu.home.open.model.db2.TaskUser;
import xiaoqu.home.open.model.db2.Wage;
import xiaoqu.home.open.publicBean.BaseOutput;
import xiaoqu.home.open.publicBean.IdEntity;
import xiaoqu.home.open.publicBean.MessageNotification;
import xiaoqu.home.open.publicBean.PageOutput;
import xiaoqu.home.open.publicBean.task.TaskCancel;
import xiaoqu.home.open.publicBean.task.TaskPoint;
import xiaoqu.home.open.service.RedisService4;
import xiaoqu.home.open.service.db1.UserService;
import xiaoqu.home.open.service.db2.FieldWebpageAuthorityService;
import xiaoqu.home.open.service.db2.InspectPicService;
import xiaoqu.home.open.service.db2.PlanService;
import xiaoqu.home.open.service.db2.TaskInfoService;
import xiaoqu.home.open.service.db2.TaskPicService;
import xiaoqu.home.open.service.db2.TaskScenesService;
import xiaoqu.home.open.service.db2.TaskStatusLogService;
import xiaoqu.home.open.service.db2.TaskTaskScenesService;
import xiaoqu.home.open.service.db2.TaskUserService;
import xiaoqu.home.open.utils.ResultResponseBeanUtil;
import xiaoqu.home.open.utils.StringUtil;
import xiaoqu.home.open.utils.UserUtils;
import xiaoqu.home.open.utils.WrapperUtils;
import xiaoqu.home.open.utils.poi.ExcelUtil;

@RestController
@RequestMapping(value = "/taskInspect")
@Api(value = "巡检任务总览", description = "巡检任务总览")
public class TaskInspectController {
	@Autowired
	private TaskInfoService taskInfoService;
	@Autowired
	private UserService userService;
	@Autowired
	private TaskUserService taskUserService;
	@Autowired
	private TaskScenesService taskScenesService;
	@Autowired
	private TaskTaskScenesService taskTaskScenesService;
	@Autowired
	private TaskStatusLogService taskStatusLogService;
	@Autowired
	private FieldWebpageAuthorityService fieldWebpageAuthorityService;

	@ApiOperation(value = "分页查询")
	@RequestMapping(value = "/pageList", method = RequestMethod.POST)
	public BaseOutput<PageOutput<TaskInfoInspectOutput>> pageList(HttpServletRequest request, @RequestBody TaskInfoInspectPageInput input) {
		PageOutput<TaskInfoInspectOutput> output = new PageOutput<TaskInfoInspectOutput>();
		Long districtId = input.getDistrictId();
		if (StringUtil.isNull(districtId)) {
			return ResultResponseBeanUtil.fail("请选择站点");
		}
		QueryWrapper<TaskInfo> wrapper = WrapperUtils.getWrapper(false);
		wrapper.ge("status", 4);// 条件限定
		wrapper.eq("task_type", 5);
		if (StringUtil.isNotEmpty(input.getGridAndScenes())) {
			Set<Long> taskIds = GetQueryCiteria(input);
			if (taskIds.size() == 0) {
				return ResultResponseBeanUtil.success(output);
			} else {
				wrapper.in("id", taskIds);
			}
			input.setGridAndScenes(null);
		}
		wrapper = WrapperUtils.beanToWrapper(wrapper, input);
//		User user = UserUtils.getUser(request);
//		List<FieldWebpageAuthority> fieldList = fieldWebpageAuthorityService.getFieldList(input.getWebId(), user.getPropertyAuthorityId());
//		String[] columns = WrapperUtils.entityToColumns(fieldList);
//		wrapper.select(columns);
		Page<TaskInfo> pageList = new Page<TaskInfo>(input.getPage(), input.getRows());
		List<TaskInfo> entityList = taskInfoService.page(pageList, wrapper).getRecords();
		List<TaskInfoInspectOutput> outList = new ArrayList<TaskInfoInspectOutput>();
		if (entityList.size() > 0) {
			for (TaskInfo bean : entityList) {
				TaskInfoInspectOutput outputBean = new TaskInfoInspectOutput();
				BeanUtils.copyProperties(bean, outputBean);
				outList.add(outputBean);
			}
		}
		output.setPage(pageList.getCurrent());
		output.setRecords(pageList.getTotal());
		output.setTotal(pageList.getPages());
		output.setRows(outList);
		return ResultResponseBeanUtil.success(output);
	}
	@Autowired
	PlanService planService;

	@ApiOperation(value = "巡检明细分页查询")
	@RequestMapping(value = "/scenesPageList", method = RequestMethod.POST)
	public BaseOutput<PageOutput<TaskTaskScenesOutput>> scenesPageList(HttpServletRequest request, @RequestBody TaskTaskScenesPageInput input) {
		PageOutput<TaskTaskScenesOutput> output = new PageOutput<TaskTaskScenesOutput>();
		Long districtId = input.getDistrictId();
		if (StringUtil.isNull(districtId)) {
			return ResultResponseBeanUtil.fail("请选择站点");
		}
		QueryWrapper<TaskTaskScenes> wrapper = WrapperUtils.getWrapper(false);
		wrapper.ge("status", 4);// 条件限定
		wrapper.eq("task_type", 5);
		if (StringUtil.isNotEmpty(input.getGridAndScenes())) {
			Set<Long> scenesIds = GetQueryScenesIds(input);
			if (scenesIds.size() >= 0) {
				wrapper.in("scenes_id", scenesIds);
			}
			input.setGridAndScenes(null);
		}
		wrapper = WrapperUtils.beanToWrapper(wrapper, input);
//		User user = UserUtils.getUser(request);
//		List<FieldWebpageAuthority> fieldList = fieldWebpageAuthorityService.getFieldList(input.getWebId(), user.getPropertyAuthorityId());
//		String[] columns = WrapperUtils.entityToColumns(fieldList);
//		wrapper.select(columns);
		Page<TaskTaskScenes> pageList = new Page<TaskTaskScenes>(input.getPage(), input.getRows());
		List<TaskTaskScenes> entityList = taskTaskScenesService.page(pageList, wrapper).getRecords();
		List<TaskTaskScenesOutput> outList = new ArrayList<TaskTaskScenesOutput>();
		if (entityList.size() > 0) {
			for (TaskTaskScenes bean : entityList) {
				TaskTaskScenesOutput outputBean = new TaskTaskScenesOutput();
				BeanUtils.copyProperties(bean, outputBean);
				outList.add(outputBean);
			}
		}
		output.setPage(pageList.getCurrent());
		output.setRecords(pageList.getTotal());
		output.setTotal(pageList.getPages());
		output.setRows(outList);
		return ResultResponseBeanUtil.success(output);
	}

	@ApiOperation(value = "巡检场景导出")
	@PostMapping("/scenesExport")
	public void scenesExport(HttpServletRequest request, HttpServletResponse response, @RequestBody TaskTaskScenesPageInput input) throws IOException {
		if (StringUtil.isNull(input.getDistrictId())) {
			return;
		}
		User user = UserUtils.getUser(request);
		List<TaskTaskScenesExport> outList = new ArrayList<TaskTaskScenesExport>();
		QueryWrapper<TaskTaskScenes> wrapper = WrapperUtils.getWrapper(false);
		wrapper.ge("status", 4);// 条件限定
		wrapper.eq("task_type", 5);
		if (StringUtil.isNotEmpty(input.getGridAndScenes())) {
			Set<Long> scenesIds = GetQueryScenesIds(input);
			if (scenesIds.size() >= 0) {
				wrapper.in("scenes_id", scenesIds);
			}
			input.setGridAndScenes(null);
		}
		wrapper = WrapperUtils.beanToWrapper(wrapper, input);
		List<TaskTaskScenes> entityList = taskTaskScenesService.list(wrapper);
		for (TaskTaskScenes taskInfo : entityList) {
			TaskTaskScenesExport taskInfoExport = new TaskTaskScenesExport();
			BeanUtils.copyProperties(taskInfo, taskInfoExport);
			outList.add(taskInfoExport);
		}

		List<FieldWebpageAuthority> fieldList = fieldWebpageAuthorityService.getExportFieldList(input.getWebId(), user.getPropertyAuthorityId());
		String[] exportColumns = WrapperUtils.entityToColumns(fieldList);
		ExcelUtil<TaskTaskScenesExport> util = new ExcelUtil<TaskTaskScenesExport>(TaskTaskScenesExport.class);
		util.exportExcelByColumns(response, outList, "巡检明细", exportColumns);
	}

	/********
	 * 查询列表和导出统一处理查询条件
	 * 
	 * @param input
	 * @return
	 */
	private Set<Long> GetQueryScenesIds(TaskTaskScenesPageInput input) {
		Set<Long> scenesIds = new HashSet<Long>();
		List<GridAndSceneInput> gridAndScenes = input.getGridAndScenes();
		for (GridAndSceneInput gridAndSceneInput : gridAndScenes) {
			Integer isscene = gridAndSceneInput.getIsscene();
			if (isscene == 1) {
				scenesIds.add(gridAndSceneInput.getSceneId());
			}
		}
		return scenesIds;
	}

	@ApiOperation(value = "巡检任务统计查询")
	@RequestMapping(value = "/statistics", method = RequestMethod.POST)
	public BaseOutput<TaskInfoInspectStatusOutput> statistics(HttpServletRequest request, @RequestBody TaskInfoInspectPageInput input) {
		TaskInfoInspectStatusOutput output = new TaskInfoInspectStatusOutput();
		Long districtId = input.getDistrictId();
		if (StringUtil.isNull(districtId)) {
			return ResultResponseBeanUtil.fail("请选择站点");
		}
		QueryWrapper<TaskInfo> wrapper = WrapperUtils.getWrapper(false);
		wrapper.ge("status", 4);// 条件限定
		wrapper.eq("task_type", 5);
		if (StringUtil.isNotEmpty(input.getGridAndScenes())) {
			Set<Long> taskIds = GetQueryCiteria(input);
			if (taskIds.size() == 0) {
				return ResultResponseBeanUtil.success(output);
			} else {
				wrapper.in("id", taskIds);
			}
			input.setGridAndScenes(null);
		}
		wrapper = WrapperUtils.beanToWrapper(wrapper, input);
		QueryWrapper<TaskInfo> wrapper1 = wrapper.clone();
//		统计：查询日期2021-05-01 00:00:00 至2021-07-31 23:59:59 ，路线名称合计6；应巡合计60；实巡合计19；未巡合计41；。
		wrapper.select("count(*) allInspect");
		Map<String, Object> allInspectMap = taskInfoService.getMap(wrapper);
		Long allInspect = (Long) allInspectMap.get("allInspect");
		wrapper1.select("sum(should_inspect) shouldInspect,sum(actual_inspect) actualInspect,sum(not_inspect) notInspect");
		allInspectMap = taskInfoService.getMap(wrapper1);
		if (allInspectMap != null) {
			BigDecimal shouldInspect = (BigDecimal) allInspectMap.get("shouldInspect");
			BigDecimal actualInspect = (BigDecimal) allInspectMap.get("actualInspect");
			BigDecimal notInspect = (BigDecimal) allInspectMap.get("notInspect");
			output.setActualInspect(actualInspect);
			output.setAllInspect(allInspect);
			output.setNotInspect(notInspect);
			output.setShouldInspect(shouldInspect);
		}
		output.setCreateTimeEnd(input.getCreateTimeEnd());
		output.setCreateTimeStart(input.getCreateTimeStart());
		return ResultResponseBeanUtil.success(output);
	}

	/********
	 * 查询列表和导出统一处理查询条件
	 * 
	 * @param input
	 * @return
	 */
	private Set<Long> GetQueryCiteria(TaskInfoInspectPageInput input) {
		Set<Long> taskIds = new HashSet<Long>();
		List<GridAndSceneInput> gridAndScenes = input.getGridAndScenes();
		for (GridAndSceneInput gridAndSceneInput : gridAndScenes) {
			QueryWrapper<TaskScenes> wrapperTaskScenes = WrapperUtils.getWrapper(false);
			wrapperTaskScenes.eq("district_id", input.getDistrictId());
//				@ApiModelProperty("网格或场景级别")
			Integer level = gridAndSceneInput.getLevel();
//				@ApiModelProperty(value = "网格ID")
			Long gridId = gridAndSceneInput.getGridId();
//				@ApiModelProperty(value = "场景ID")
			Long sceneId = gridAndSceneInput.getSceneId();
//				@ApiModelProperty(value = "是否场景，0:否;1:是")
			Integer isscene = gridAndSceneInput.getIsscene();
			if (isscene == 0) {
				switch (level) {
				case 1:
					wrapperTaskScenes.eq("building_id", gridId);
					break;
				case 2:
					wrapperTaskScenes.eq("floor_id", gridId);
					break;
				default:
					wrapperTaskScenes.eq("multistage_grid_id", gridId);
					break;
				}
				wrapperTaskScenes.eq("grid_level", level);
			} else {
				switch (level) {
				case 1:
					wrapperTaskScenes.eq("scenes_id", sceneId);
					break;
				case 2:
					wrapperTaskScenes.eq("scenes_id", sceneId);
					break;
				}
				wrapperTaskScenes.eq("scenes_level", level);
			}
//			@ApiModelProperty(value = "任务生成时间")
//			private String createTimeStart;
			if (StringUtil.isNotEmpty(input.getCreateTimeStart())) {
				wrapperTaskScenes.ge("create_time", input.getCreateTimeStart());
				wrapperTaskScenes.le("create_time", input.getCreateTimeEnd());
			}
			List<TaskScenes> taskScenes = taskScenesService.list(wrapperTaskScenes);
			taskIds.addAll(taskScenes.stream().map(taskScen -> taskScen.getTaskId()).collect(Collectors.toSet()));
		}
		return taskIds;
	}


	@ApiOperation(value = "巡检任务总览导出")
	@PostMapping("/export")
	public void export(HttpServletRequest request, HttpServletResponse response, @RequestBody TaskInfoInspectPageInput input) throws IOException {
		if (StringUtil.isNull(input.getDistrictId())) {
			return;
		}
		QueryWrapper<TaskInfo> wrapper = WrapperUtils.getWrapper(false);
		wrapper.eq("task_type", 5);
		wrapper.ge("status", 4);// 条件限定
		if (StringUtil.isNotEmpty(input.getGridAndScenes())) {
			Set<Long> taskIds = GetQueryCiteria(input);
			if (taskIds.size() == 0) {
				return;
			} else {
				wrapper.in("id", taskIds);
			}
			input.setGridAndScenes(null);
		}
		wrapper = WrapperUtils.beanToWrapper(wrapper, input);
		TaskInfoInspectStatusOutput output = new TaskInfoInspectStatusOutput();
		QueryWrapper<TaskInfo> wrapper1 = wrapper.clone();
		QueryWrapper<TaskInfo> wrapper2 = wrapper.clone();
//		统计：查询日期2021-05-01 00:00:00 至2021-07-31 23:59:59 ，路线名称合计6；应巡合计60；实巡合计19；未巡合计41；。
		wrapper.select("count(*) allInspect");
		Map<String, Object> allInspectMap = taskInfoService.getMap(wrapper);
		Long allInspect = (Long) allInspectMap.get("allInspect");
		wrapper1.select("sum(should_inspect) shouldInspect,sum(actual_inspect) actualInspect,sum(not_inspect) notInspect");
		allInspectMap = taskInfoService.getMap(wrapper1);
		if (allInspectMap != null) {
			BigDecimal shouldInspect = (BigDecimal) allInspectMap.get("shouldInspect");
			BigDecimal actualInspect = (BigDecimal) allInspectMap.get("actualInspect");
			BigDecimal notInspect = (BigDecimal) allInspectMap.get("notInspect");
			output.setActualInspect(actualInspect);
			output.setAllInspect(allInspect);
			output.setNotInspect(notInspect);
			output.setShouldInspect(shouldInspect);
		}
		output.setCreateTimeEnd(input.getCreateTimeEnd());
		output.setCreateTimeStart(input.getCreateTimeStart());
		// 查明细
		List<TaskInfo> taskInfoList = taskInfoService.list(wrapper2);
		String fileTemplate = "./temp/inspectStatistics.xlsx";
		File fileOut = new File(fileTemplate);
		// 从jar里读取文件 然后建立临时文件模板 如果temp 目录已经有了就不读取了
		if (!fileOut.exists()) {
			File dirPath = new File("./temp");
			if (!dirPath.exists()) {
				dirPath.mkdir();
			}
			fileOut.createNewFile();// 将模板文件放到临时目录
			InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/inspectStatistics.xlsx");
			FileOutputStream fos = new FileOutputStream(fileTemplate);
			byte[] b = new byte[1024];
			while ((inputStream.read(b)) != -1) {
				fos.write(b);// 写入数据
			}
			inputStream.close();
			fos.close();// 保存数据
		}
		TemplateExportParams params = new TemplateExportParams(fileTemplate);
		params.setColForEach(true);
		// 2021年5月1日-2021年5月12日入库明细表
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("createTimeStart", input.getCreateTimeStart());
		map.put("createTimeEnd", input.getCreateTimeEnd());
		map.put("allInspect", allInspect);
		map.put("shouldInspect", output.getShouldInspect());
		map.put("actualInspect", output.getShouldInspect());
		map.put("notInspect", output.getNotInspect());
		List<Map<String, String>> listMap = new ArrayList<Map<String, String>>();
		QueryWrapper<Wage> wagWrapper = WrapperUtils.getWrapper(false);
		wagWrapper.eq("district_id", input.getDistrictId());
		for (TaskInfo beanOutput : taskInfoList) {
			Map<String, String> lm = new HashMap<String, String>();
			lm.put("no", beanOutput.getNo());
			lm.put("name", beanOutput.getName());
			lm.put("taskPosition", beanOutput.getTaskPosition());
			lm.put("taskDistributiUser", beanOutput.getTaskDistributiUser());
			lm.put("taskAcceptUser", beanOutput.getTaskAcceptUser());
			lm.put("createTime", DateUtil.format(beanOutput.getStartTime(), "yyyy-MM-dd HH:mm:ss"));
			lm.put("preFinishTime", DateUtil.format(beanOutput.getEndTime(), "yyyy-MM-dd HH:mm:ss"));
			lm.put("createTaskTime", DateUtil.format(beanOutput.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
			lm.put("status", getOrderState(beanOutput.getStatus()));
			lm.put("shouldInspect", beanOutput.getShouldInspect() + "");
			lm.put("actualInspect", beanOutput.getActualInspect() + "");
			lm.put("notInspect", beanOutput.getNotInspect() + "");
			lm.put("lookTime", DateUtil.format(beanOutput.getLookTime(), "yyyy-MM-dd HH:mm:ss"));
			lm.put("actionTime", DateUtil.format(beanOutput.getActionTime(), "yyyy-MM-dd HH:mm:ss"));
			lm.put("finishTime", DateUtil.format(beanOutput.getFinishTime(), "yyyy-MM-dd HH:mm:ss"));
			lm.put("wageType", beanOutput.getWageName());
			lm.put("wageHour", beanOutput.getWageHour() + "");
			lm.put("taskActualActionTiming", beanOutput.getTaskActualActionTiming() + "");
			lm.put("point", beanOutput.getPoint() + "");
			lm.put("districtName", beanOutput.getDistrictName());
			listMap.add(lm);
		}
		map.put("list", listMap);
		String fileName = "巡检任务总览" + DateUtil.format(new Date(), "yyyMMddHHmmsss") + ".xlsx";
		Workbook workbook = ExcelExportUtil.exportExcel(params, map);
		response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("UTF-8"), "iso8859-1"));
		response.setContentType("application/vnd.ms-excel;charset=UTF-8");
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		BufferedOutputStream bufferedOutPut = new BufferedOutputStream(response.getOutputStream());
		workbook.write(bufferedOutPut);
		bufferedOutPut.flush();
		bufferedOutPut.close();
	}

	public String getOrderState(int orderState) {
		String name = "";
//		4:作业中;5:按时完成;6:超时完成;7:人工取消;8:系统取消;9:未完成
		switch (orderState) {
		case 4:
			name = "作业中";
			break;
		case 5:
			name = "按时完成";
			break;
		case 6:
			name = "超时完成";
			break;
		case 7:
			name = "人工取消";
			break;
		case 8:
			name = "系统取消";
			break;
		default:
			name = "未完成";
			break;
		}
		return name;
	}

	@Autowired
	private RedisService4 redisService4;
	@Autowired
	private RedisTemplate<String, String> redisTemplate5;

	@ApiOperation(value = "取消任务")
	@AvoidRepeatSubmit
	@RequestMapping(value = "/cancel", method = RequestMethod.POST)
	public BaseOutput<String> cancel(HttpServletRequest request, @RequestBody TaskCancel input) {
		User user = UserUtils.getUser(request);
		if (StringUtil.isNull(input.getId())) {
			return ResultResponseBeanUtil.fail("请输入任务ID");
		}
		TaskInfo taskInfo = taskInfoService.getById(input.getId());
		if (StringUtil.isNull(taskInfo)) {
			return ResultResponseBeanUtil.fail("任务不存在");
		}
//		待抢单 已接单 作业中
//		任务状态(0:已生成;1:待派发;2:待抢单;3:已接单;4:作业中;5:按时完成;6:超时完成;7:人工取消;8:系统取消;9:未完成)")
//		待派发 待抢单 已接单  作业中
		if (taskInfo.getStatus() == 4) {
			taskInfo.setStatus(7);
			taskInfo.setModifyTime(new Date());
			taskInfoService.updateById(taskInfo);
			TaskStatusLog taskStatusLog = new TaskStatusLog();
			BeanUtils.copyProperties(taskInfo, taskStatusLog, "id");
			taskStatusLog.setCreateTime(new Date());
			taskStatusLog.setTaskId(taskInfo.getId());
			taskStatusLog.setTaskStatus(7);
			taskStatusLog.setCancelReason(input.getCancelReason());
			taskStatusLog.setDetailReason(input.getDetailReason());
			taskStatusLog.setContent(user.getName() + " " + user.getMobile());
			taskStatusLogService.save(taskStatusLog);
			// 同时取消taskuser表的数据
			UpdateWrapper<TaskUser> taskUserWrapper = WrapperUtils.getUpdateWrapper(false);
			taskUserWrapper.eq("task_id", input.getId());
			taskUserWrapper.set("status", 7);
			taskUserWrapper.set("modify_time", new Date());
			taskUserService.update(taskUserWrapper);
			// 个推推送
			MessageNotification messageNotification = new MessageNotification();
			messageNotification.setDistrictId(taskInfo.getDistrictId());
			messageNotification.setStatus(taskInfo.getStatus());
			messageNotification.setTaskId(taskInfo.getId());
			messageNotification.setTaskName(taskInfo.getName());
			redisService4.lPush("taskPushQueue", JSON.toJSONString(messageNotification));
			/*** 通知匹配算法重新算 ***/
			redisTemplate5.opsForSet().add("RepeatTaskQueue", taskInfo.getDistrictId() + "");
			/****** 任务结束通知 ******/
			redisTemplate5.opsForList().leftPush("FinishTaskQueue", taskInfo.getId() + "");
			// 修改人员状态
			QueryWrapper<TaskUser> qWrapper = WrapperUtils.getWrapper(false);
			qWrapper.eq("task_id", input.getId());
			List<TaskUser> tempList = taskUserService.list(qWrapper);
			if (tempList.size() > 0) {
				for (TaskUser taskUser : tempList) {
					if (taskUser.getUserId() != null && taskUser.getUserId().intValue() != 0) {
						User temUser = userService.getById(taskUser.getUserId());
						if (temUser.getWorkAtStatus() != 3) {// 工作中状态0:作业;1:转场;2:空闲;3:休息
							// 查询有没有待完成的任务
							QueryWrapper<TaskUser> taskUserQuery = WrapperUtils.getWrapper(false);
							taskUserQuery.eq("status", 4);// 3:已接单;4:作业中;
							taskUserQuery.eq("user_id", temUser.getId());
							int countTemp = taskUserService.count(taskUserQuery);
							if (countTemp > 0) {
								temUser.setWorkAtStatus(0);// 工作中状态0:作业;1:转场;2:空闲;3:休息
								temUser.setModifyTime(new Date());
								userService.updateById(temUser);
							} else {
								QueryWrapper<TaskUser> taskUserQuery1 = WrapperUtils.getWrapper(false);
								taskUserQuery1.eq("status", 3);// 3:已接单;4:作业中;
								taskUserQuery1.eq("user_id", temUser.getId());
								countTemp = taskUserService.count(taskUserQuery1);
								if (countTemp > 0) {
									temUser.setWorkAtStatus(1);// 工作中状态0:作业;1:转场;2:空闲;3:休息
									temUser.setModifyTime(new Date());
									userService.updateById(temUser);
								} else {
									temUser.setWorkAtStatus(2);// 工作中状态0:作业;1:转场;2:空闲;3:休息
									temUser.setModifyTime(new Date());
									userService.updateById(temUser);
								}
							}
						}
					}

				}

			}
			return ResultResponseBeanUtil.success("取消成功");
		} else {
			return ResultResponseBeanUtil.fail("当前状态不支持此操作");
		}
	}

	@Autowired
	TaskPicService taskPicService;
	@Autowired
	InspectPicService inspectPicService;

	@ApiOperation(value = "查看巡检任务详情")
	@RequestMapping(value = "/look", method = RequestMethod.POST)
	public BaseOutput<TaskInspectDetailOutput> look(HttpServletRequest request, @RequestBody IdEntity input) {
		TaskInspectDetailOutput taskInfoDetailOutput = new TaskInspectDetailOutput();
		if (StringUtil.isNull(input.getId())) {
			return ResultResponseBeanUtil.fail("请输入任务ID");
		}
		TaskInfo taskInfo = taskInfoService.getById(input.getId());
		if (StringUtil.isNull(taskInfo)) {
			return ResultResponseBeanUtil.fail("任务不存在");
		}
		// 第一步格式化时间
		BeanUtils.copyProperties(taskInfo, taskInfoDetailOutput);
		String beginTime = DateUtil.format(taskInfo.getCreateTime(), DatePattern.NORM_DATETIME_MINUTE_PATTERN);
		taskInfoDetailOutput.setBeginTime(beginTime);
		String endTime = DateUtil.format(taskInfo.getPreFinishTime(), DatePattern.NORM_DATETIME_MINUTE_PATTERN);
		taskInfoDetailOutput.setEndTime(endTime);
		QueryWrapper<TaskScenes> wrapperTaskScenes = WrapperUtils.getWrapper(false);
		wrapperTaskScenes.eq("task_id", input.getId());
		wrapperTaskScenes.orderByAsc("order_by");
		List<TaskScenes> allTaskList = taskScenesService.list(wrapperTaskScenes);
		// 查询取消的原因
		if (taskInfo.getStatus() == 7) {// 取消
			QueryWrapper<TaskStatusLog> taskStatusLogWrapper = WrapperUtils.getWrapper(false);
			taskStatusLogWrapper.eq("task_id", taskInfo.getId());
			taskStatusLogWrapper.eq("task_status", 7);
			taskStatusLogWrapper.orderByAsc("id");
			TaskStatusLog taskStatusLog = taskStatusLogService.getOne(taskStatusLogWrapper);
			if (StringUtil.isNotNull(taskStatusLog)) {
				TaskCancelProgress taskProgress = new TaskCancelProgress();
				BeanUtils.copyProperties(taskStatusLog, taskProgress);
				taskProgress.setCancelUser(taskStatusLog.getContent().split(" ")[0]);
				taskInfoDetailOutput.setCancelReason(taskProgress);
			}

		}
		// 查询打卡记录
		List<TaskInspectScenes> taskInspectScenesS = new ArrayList<TaskInspectScenes>();
		for (TaskScenes taskScenes : allTaskList) {
			TaskInspectScenes taskInspectScene = new TaskInspectScenes();
			BeanUtils.copyProperties(taskScenes, taskInspectScene);
			taskInspectScene.setName(taskScenes.getSuperiorGridName() + "->" + taskScenes.getName());
			if (taskScenes.getIsCheck() == 1) {
				User user = userService.getById(taskScenes.getModifyId());
				if (user != null) {
					taskInspectScene.setModifyName(user.getName());
					taskInspectScene.setModifyNameMobile(DesensitizedUtil.mobilePhone(user.getMobile()));
				}
				// 查询巡检图片
				QueryWrapper<InspectPic> wrapperInspectPic = WrapperUtils.getWrapper(false);
				wrapperInspectPic.eq("task_id", input.getId());
				wrapperInspectPic.eq("task_scenes_id", taskScenes.getId());
				List<InspectPic> inspectPicList = inspectPicService.list(wrapperInspectPic);
				taskInspectScene.setInspectPicList(inspectPicList);
			} else {
				taskInspectScene.setName(taskInspectScene.getName() + "(未巡)");
			}
			taskInspectScenesS.add(taskInspectScene);
		}
		taskInfoDetailOutput.setTaskInspectScenes(taskInspectScenesS);
//		任务积分
		TaskPoint taskPoint = new TaskPoint();
		if (taskInfo.getPoint()>0) {
			if (taskInfo.getFinishTime() != null) {
				if (taskInfo.getStatus() == 5 || taskInfo.getStatus() == 6) {
					taskPoint.setCreateTime(taskInfo.getFinishTime());
					taskPoint.setPoint(taskInfo.getPoint());
					taskInfoDetailOutput.setTaskPoint(taskPoint);
				}
			}else {
				taskPoint.setCreateTime(null);
				taskPoint.setPoint(taskInfo.getPoint());
				taskInfoDetailOutput.setTaskPoint(taskPoint);
			}
		}

		return ResultResponseBeanUtil.success(taskInfoDetailOutput);

	}

	@ApiOperation(value = "查看巡检场景详情")
	@RequestMapping(value = "/lookInspectDetail", method = RequestMethod.POST)
	public BaseOutput<TaskInspectScenes> lookInspectDetail(HttpServletRequest request, @RequestBody IdEntity input) {
		if (StringUtil.isNull(input.getId())) {
			return ResultResponseBeanUtil.fail("请输入记录ID");
		}
		TaskScenes taskScenes = taskScenesService.getById(input.getId());
		TaskInspectScenes taskInspectScene = new TaskInspectScenes();
		BeanUtils.copyProperties(taskScenes, taskInspectScene);
		taskInspectScene.setName(taskScenes.getSuperiorGridName() + "->" + taskScenes.getName());
		if (taskScenes.getIsCheck() == 1) {
			// 查询巡检图片
			QueryWrapper<InspectPic> wrapperInspectPic = WrapperUtils.getWrapper(false);
			wrapperInspectPic.eq("task_id", taskScenes.getTaskId());
			wrapperInspectPic.eq("task_scenes_id", taskScenes.getId());
			List<InspectPic> inspectPicList = inspectPicService.list(wrapperInspectPic);
			taskInspectScene.setInspectPicList(inspectPicList);
		} else {
			taskInspectScene.setName(taskInspectScene.getName() + "(未巡)");
		}

		return ResultResponseBeanUtil.success(taskInspectScene);

	}

	// 提取文本手机号
	public static String getPhoneNum(String text) {
		String regex = "[\\d]{11}";
		Pattern compile = Pattern.compile(regex);
		Matcher matcher = compile.matcher(text);
		String result = "";
		while (matcher.find()) {
			result += "," + matcher.group();
		}
		return result.replaceFirst(",", "");
	}

}
