package com.bcxin.ars.rest.app;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.bcxin.ars.dto.TaskFeedbackSearchDto;
import com.bcxin.ars.dto.TaskSearchDto;
import com.bcxin.ars.dto.task.FeedBackDetailDto;
import com.bcxin.ars.dto.task.TaskDetailSearchDto;
import com.bcxin.ars.dto.task.TaskDto;
import com.bcxin.ars.dto.task.TaskFeedBackDto;
import com.bcxin.ars.dto.task.TaskListDto;
import com.bcxin.ars.dto.task.TaskListSearchDto;
import com.bcxin.ars.exception.ArsException;
import com.bcxin.ars.model.SecurityPerson;
import com.bcxin.ars.model.task.Task;
import com.bcxin.ars.model.task.TaskFeedback;
import com.bcxin.ars.model.task.TaskFeedbackLog;
import com.bcxin.ars.model.task.TaskPerson;
import com.bcxin.ars.model.task.TaskStatus;
import com.bcxin.ars.model.task.TaskTrack;
import com.bcxin.ars.rest.dto.AppAjaxResult;
import com.bcxin.ars.service.SecurityPersonService;
import com.bcxin.ars.service.task.TaskFeedbackLogService;
import com.bcxin.ars.service.task.TaskFeedbackService;
import com.bcxin.ars.service.task.TaskPersonService;
import com.bcxin.ars.service.task.TaskService;
import com.bcxin.ars.service.task.TaskTrackService;
import com.bcxin.ars.util.Constants;
import com.bcxin.ars.util.DateUtil;
import com.bcxin.ars.util.StringUtil;

import cn.jiguang.common.utils.StringUtils;

@Controller
@RequestMapping("app/task")
public class AppTaskController {
	
	private static final Logger logger = LoggerFactory.getLogger(AppTaskController.class);
	
	@Autowired
	private TaskService taskService;
	
	@Autowired
	private TaskTrackService trackService;
	
	@Autowired
	private TaskFeedbackService feedbackService;
	
	@Autowired
	private SecurityPersonService personService;

	@Autowired
	private TaskPersonService taskPersonService;

	
	@Autowired
	private TaskFeedbackLogService taskFeedbackLogService;
	/**
	 * 任务一键搜功能
	 * @param dto
	 * @return
	 */
	@RequestMapping("search")
//	@RequiresPermissions("search:read")
	public @ResponseBody AppAjaxResult search(AppAjaxResult appResult) throws Exception {
		AppAjaxResult result = new AppAjaxResult();
		try {
			TaskSearchDto dto = appResult.getDecodeData(TaskSearchDto.class);
			TaskSearchDto data = taskService.searchForFeedback(dto);
			result.setSuccessful(true);
			result.setEncodeData(data);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	/**
	 * 任务流水一键搜功能
	 * @param dto
	 * @return
	 */
	@RequestMapping("feedback/search")
//	@RequiresPermissions("search:read")
	public @ResponseBody AppAjaxResult searchFeedback(AppAjaxResult appResult) throws Exception {
		AppAjaxResult result = new AppAjaxResult();
		try {
			TaskFeedbackSearchDto dto = appResult.getDecodeData(TaskFeedbackSearchDto.class);
			TaskFeedbackSearchDto data = feedbackService.search(dto);
			result.setSuccessful(true);
			result.setEncodeData(data);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	
	/**
	 * 根据ID获取任务明细
	 * @return
	 */
	@RequestMapping("findById/{id}")
	@Deprecated
	public @ResponseBody AppAjaxResult findById(@PathVariable("id")Long id) throws Exception {
		AppAjaxResult result = new AppAjaxResult();
		try {
			Task task = taskService.findById(id);
			result.setSuccessful(true);
			result.setEncodeData(task);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	
	/**
	 * 根据任务ID、人员id获取任务明细
	 * @return
	 */
	@RequestMapping("findDetail/{id}/{personId}")
	public @ResponseBody AppAjaxResult findDetailByIdPerson(@PathVariable("id")Long id,@PathVariable("personId")Long personId) throws Exception {
		AppAjaxResult result = new AppAjaxResult();
		try {
			Task task = taskService.findDetailByIdPerson(id,personId);
			result.setSuccessful(true);
			result.setEncodeData(task);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}

	public double calcuCounttime(List<TaskFeedback> taskFeedbackList){
		double counttime=0;
		//计算总时长
		for(TaskFeedback taskFeedback:taskFeedbackList){
			if(taskFeedback!=null&&taskFeedback.getStartTime()!=null&&taskFeedback.getEndTime()!=null){
				counttime +=DateUtil.hourDiff1(taskFeedback.getStartTime(),taskFeedback.getEndTime(),"yyyy-MM-dd HH:mm:ss");
			}
		}
		return counttime;
	}
	public void setCommonValue(Task t,TaskListDto dto){
		//任务类型
		dto.setTaskType(t.getTaskType());
		//任务ID
		dto.setTaskId(t.getId());
		//任务名称
		dto.setTaskName(t.getName());
		//任务详情
		dto.setTaskDetail(t.getDetail());
		//任务地址
		dto.setAddress(t.getAddress());
		dto.setCurrentTaskStatus(t.getCurrentTaskStatus());
		//周期还是临时
		if(t.getTaskType()!=null&&t.getTaskType().getId()==1){
			if(t.isRepeat()==true){
				dto.setPeat(true);
			}else{
				dto.setPeat(false);
			}
		}
	}
	/**
	 * 获取用户任务列表
	 * @return
	 */
	@RequestMapping("findTaskListNew")
	public @ResponseBody AppAjaxResult findTaskListNew(AppAjaxResult appResult) throws Exception {
		AppAjaxResult result = new AppAjaxResult();
		try {
			TaskSearchDto taskSearchDto = appResult.getDecodeData(TaskSearchDto.class);
			SecurityPerson person = personService.findById(taskSearchDto.getPersonId());
			if (person == null) {
				throw new RuntimeException("无此保安员，personID:" + taskSearchDto.getPersonId());
			}
			//获取用户的任务列表
			TaskSearchDto resultdto =taskService.findTaskListByPersonid(taskSearchDto);
			List<Task> taskList = resultdto.getData();


			List<TaskListDto> list = new ArrayList<>();

			for(Task t:taskList){
				TaskPerson taskPerson =taskPersonService.findStatusByTaskIdPersonId(t.getId(),taskSearchDto.getPersonId());

				//0-未接受（即新任务）
				if(taskPerson!=null&&taskPerson.getAcceptStatus()==0&&taskSearchDto.getAcceptStatus().equals(Constants.ACCEPTASKSTATUS_NEW)){
					TaskListDto dto =new TaskListDto();
					//任务状态
					dto.setTaskStatus(Constants.TASKSTATUS_NEW);
					dto.setStartDate(DateUtil.convertDateToString(t.getCreateTime(),"yyyy年MM月dd日 HH:mm"));
					setCommonValue(t,dto);
					//任务日期
//					dto.setStartdateEnddate(DateUtil.convertDateToString(DateUtil.convertStringToDate(t.getStartDate()),"yyyy年MM月dd日")+"-"+DateUtil.convertDateToString(DateUtil.convertStringToDate(t.getEndDate()),"yyyy年MM月dd日"));
					dto.setStartdateEnddate(DateUtil.convertDateToString(DateUtil.convertStringToDate(t.getStartDate()),"yyyy年MM月dd日"));
					list.add(dto);

				}//2-已拒绝
				else if(taskPerson!=null&&taskPerson.getAcceptStatus()==2&&taskSearchDto.getAcceptStatus().equals(Constants.ACCEPTASKSTATUS_DENY)){
					TaskListDto dto =new TaskListDto();
					//任务状态
					dto.setStartDate(DateUtil.convertDateToString(t.getCreateTime(),"yyyy年MM月dd日 HH:mm"));
					dto.setTaskStatus(Constants.TASKSTATUS_DENY);
					setCommonValue(t,dto);
					//任务日期
					dto.setStartdateEnddate(DateUtil.convertDateToString(DateUtil.convertStringToDate(t.getStartDate()),"yyyy年MM月dd日")+"-"+DateUtil.convertDateToString(DateUtil.convertStringToDate(t.getEndDate()),"yyyy年MM月dd日"));
					list.add(dto);

				}//3已完成
				else if(taskPerson!=null&&taskPerson.getAcceptStatus()==3&&taskSearchDto.getAcceptStatus().equals(Constants.ACCEPTASKSTATUS_FINISHALL)){
					TaskListDto dto =new TaskListDto();
					//计算执行时间
					List<TaskFeedback> taskFeedbackList =feedbackService.findAllFeedbackByTaskid(t.getId(),taskSearchDto.getPersonId());
					double counttime= calcuCounttime(taskFeedbackList);
					int fInt = (int) counttime;
					BigDecimal b1 = new BigDecimal(Double.toString(counttime));
					BigDecimal b2 = new BigDecimal(Integer.toString(fInt));
					float fPoint = b1.subtract(b2).floatValue();
					dto.setCountTime("总时长："+fInt+"小时"+(int)(fPoint*60)+"分钟");
					//任务状态
					dto.setTaskStatus(Constants.TASKSTATUS_FINISHALL);
					//结束日期
					dto.setFinishDate(DateUtil.convertDateToString(t.getUpdateTime(),"yyyy年MM月dd日"));
				//	dto.setFinishDate(DateUtil.convertDateToString(DateUtil.convertStringToDate(t.getEndDate()),"yyyy年MM月dd日 HH:mm"));
					setCommonValue(t,dto);
					//任务日期
					dto.setStartdateEnddate(DateUtil.convertDateToString(DateUtil.convertStringToDate(t.getStartDate()),"yyyy年MM月dd日")+"-"+DateUtil.convertDateToString(DateUtil.convertStringToDate(t.getEndDate()),"yyyy年MM月dd日"));
					list.add(dto);
				}//4超时
				else if(taskPerson!=null&&taskPerson.getAcceptStatus()==4&&taskSearchDto.getAcceptStatus().equals(Constants.ACCEPTASKSTATUS_DENY)){
					TaskListDto dto =new TaskListDto();
					//任务状态
					dto.setTaskStatus(Constants.TASKSTATUS_OVERTIME);
					dto.setStartDate(DateUtil.convertDateToString(t.getCreateTime(),"yyyy年MM月dd日 HH:mm"));
					setCommonValue(t,dto);
					//任务日期
					dto.setStartdateEnddate(DateUtil.convertDateToString(DateUtil.convertStringToDate(t.getStartDate()),"yyyy年MM月dd日")+"-"+DateUtil.convertDateToString(DateUtil.convertStringToDate(t.getEndDate()),"yyyy年MM月dd日"));
					list.add(dto);
				}else if(taskPerson!=null&&taskPerson.getAcceptStatus()==1&&taskSearchDto.getAcceptStatus().equals(Constants.ACCEPTASKSTATUS_OTHER)){//1-已接受
					if(t.getTaskType()!=null&&t.getTaskType().getId()==4){//紧急任务
						List<TaskFeedback> taskFeedbackList =feedbackService.findUrgentFeedbackByTaskid(t.getId(),taskSearchDto.getPersonId());
						for(TaskFeedback taskFeedback:taskFeedbackList){
							TaskListDto dto =new TaskListDto();

							//紧急任务的接受日期
							dto.setAccepDate(DateUtil.convertDateToString(taskFeedback.getCreateTime(),"yyyy年MM月dd日 HH:mm"));
							//紧急任务的发布日期
							dto.setStartDate(DateUtil.convertDateToString(DateUtil.convertStringToDate(t.getStartDate()),"yyyy年MM月dd日 HH:mm"));


							if(taskFeedback.getTaskStatus()!=null&&taskFeedback.getTaskStatus().getId()==2){
								//正在执行，已执行时长为当前时间减去开始时间
								dto.setTaskStatus(Constants.TASKSTATUS_DOING);
								dto.setCountdownTime("已执行时长："+String.valueOf(DateUtil.hourDiff(taskFeedback.getStartTime(),new Date())));
							}else {
								//完成，已执行时长为结束时间减去开始时间
								dto.setTaskStatus(Constants.TASKSTATUS_FINISH);
								dto.setCountdownTime("已执行时长："+String.valueOf(DateUtil.hourDiff(taskFeedback.getStartTime(),taskFeedback.getEndTime())));

								//紧急任务结束日期
								dto.setFinishDate(DateUtil.convertDateToString(taskFeedback.getEndTime(),"yyyy年MM月dd日"));

							}
							setCommonValue(t,dto);
							list.add(dto);
							break;

						}

					}else if(t.getTaskType()!=null&&t.getTaskType().getId()==2){//临时任务
						List<TaskFeedback> taskFeedbackList =feedbackService.findAllFeedbackByTaskid(t.getId(),taskSearchDto.getPersonId());
						List<TaskFeedback> taskFeedbackListOne =feedbackService.findFeedbackByTaskid(t.getId(),taskSearchDto.getPersonId());

						//计算执行时间
						double counttime= calcuCounttime(taskFeedbackList);
						int fInt = (int) counttime;
						BigDecimal b1 = new BigDecimal(Double.toString(counttime));
						BigDecimal b2 = new BigDecimal(Integer.toString(fInt));
						float fPoint = b1.subtract(b2).floatValue();
						//下一班次的子任务信息
						TaskListDto dto =new TaskListDto();
						dto.setPersonId(taskSearchDto.getPersonId());
						dto.setTaskId(t.getId());
						TaskFeedBackDto taskFeedBackDto = feedbackService.findNextFeedBack_back(dto);
						//任务日期
						dto.setStartdateEnddate(DateUtil.convertDateToString(DateUtil.convertStringToDate(t.getStartDate()),"yyyy年MM月dd日")+"-"+DateUtil.convertDateToString(DateUtil.convertStringToDate(t.getEndDate()),"yyyy年MM月dd日"));

						//循环子任务列表，返回正在执行的任务，有且只有一条
						for(TaskFeedback taskFeedback:taskFeedbackListOne){

							/*TaskFeedBackDto taskFeedBackDto1 = null;
							if(taskFeedback.getEndTime()!=null){
								dto.setFinishDate(DateUtil.convertDateToString(taskFeedback.getEndTime(),"yyyy-MM-dd hh:mm:ss"));
								taskFeedBackDto1 = feedbackService.findNextFeedBack_back(dto);
							}*/
							//执行状态
							if(taskFeedback.getTaskStatus()!=null&&taskFeedback.getTaskStatus().getId()==2){
								//正在执行
								dto.setTaskStatus(Constants.TASKSTATUS_DOING);
								//		dto.setCountdownTime("还有"+String.valueOf(DateUtil.dateDiff(new Date(),taskFeedback.getEndTime())*24)+"小时下班");
								//下一班次
								if(taskFeedBackDto!=null){
									dto.setNextScheduleDate(DateUtil.convertDateToString(DateUtil.convertStringToDate(taskFeedBackDto.getTaskDate()+" "+taskFeedBackDto.getDetails().get(0).getTaskStart()),"yyyy年MM月dd日 HH:mm")+"-"+DateUtil.convertDateToString(DateUtil.convertStringToDate(taskFeedBackDto.getTaskDate()+" "+taskFeedBackDto.getDetails().get(0).getTaskEnd()),"HH:mm"));
								}
								dto.setCountdownTime("已执行时长："+String.valueOf(DateUtil.hourDiff(taskFeedback.getStartTime(),new Date())));


							}//已结束
							else if(/*taskFeedback.getStartTime()!=null&&taskFeedback.getEndTime()!=null*//*(taskFeedback.getEndTime()!=null&&taskFeedBackDto1==null)||*/(taskFeedBackDto==null&&taskFeedback.getStartTime()!=null&&taskFeedback.getEndTime()!=null&&taskFeedback.getTaskStatus().getId()==3)){
								dto.setTaskStatus(Constants.TASKSTATUS_FINISH);
								dto.setFinishDate(DateUtil.convertDateToString(t.getUpdateTime(),"yyyy年MM月dd日"));

								dto.setCountTime("总时长："+fInt+"小时"+(int)(fPoint*60)+"分钟");

							}//即将开始
							else {
								dto.setTaskStatus(Constants.TASKSTATUS_TODO);
								String beginTime=String.valueOf(DateUtil.hourDiff(new Date(),DateUtil.convertStringToDate(taskFeedback.getTaskDate()+" "+taskFeedback.getTaskStart())));
								if(taskFeedback.getStartTime()!=null){
									if (taskFeedBackDto != null) {
										dto.setNextScheduleDate(DateUtil.convertDateToString(DateUtil.convertStringToDate(taskFeedBackDto.getTaskDate() + " " + taskFeedBackDto.getDetails().get(0).getTaskStart()), "yyyy年MM月dd日 HH:mm") + "-" + DateUtil.convertDateToString(DateUtil.convertStringToDate(taskFeedBackDto.getTaskDate() + " " + taskFeedBackDto.getDetails().get(0).getTaskEnd()), "HH:mm"));
									}
									beginTime=String.valueOf(DateUtil.hourDiff(new Date(),DateUtil.convertStringToDate(taskFeedBackDto.getTaskDate() + " " + taskFeedBackDto.getDetails().get(0).getTaskStart())));
									dto.setBeginTime("还有"+beginTime+"开始");
								}else{
									dto.setNextScheduleDate(DateUtil.convertDateToString(DateUtil.convertStringToDate(taskFeedback.getTaskDate()+" "+taskFeedback.getTaskStart()),"yyyy年MM月dd日 HH:mm")+"-"+DateUtil.convertDateToString(DateUtil.convertStringToDate(taskFeedback.getTaskDate()+" "+taskFeedback.getTaskEnd()),"HH:mm"));
									if(!beginTime.equals("")){
										dto.setBeginTime("还有"+beginTime+"开始");
									}else{
										dto.setBeginTime("已迟到");
									}
								}

							}
							setCommonValue(t,dto);
							list.add(dto);
							break;
						}


					}else if(t.getTaskType()!=null&&t.getTaskType().getId()==1){//周期任务
						//周期子任务列表
						List<TaskFeedback> taskFeedbackList =feedbackService.findAllFeedbackByTaskid(t.getId(),taskSearchDto.getPersonId());
						List<TaskFeedback> taskFeedbackListOne =feedbackService.findFeedbackByTaskid(t.getId(),taskSearchDto.getPersonId());

						//计算执行时间
						double counttime= calcuCounttime(taskFeedbackList);
						int fInt = (int) counttime;
						BigDecimal b1 = new BigDecimal(Double.toString(counttime));
						BigDecimal b2 = new BigDecimal(Integer.toString(fInt));
						float fPoint = b1.subtract(b2).floatValue();
						//下一班次的子任务信息
						TaskListDto dto =new TaskListDto();
						dto.setPersonId(taskSearchDto.getPersonId());
						dto.setTaskId(t.getId());
						TaskFeedBackDto taskFeedBackDto = feedbackService.findNextFeedBack_back(dto);
						//任务日期
						if(t.isRepeat()==true){
							dto.setStartdateEnddate(DateUtil.convertDateToString(t.getCreateTime(),"yyyy年MM月dd日"));
						}else{
							// 获取Calendar
							Calendar calendar = Calendar.getInstance();
							// 设置时间,当前时间不用设置
							 calendar.setTime(DateUtil.convertStringToDate(t.getEndDate()));
							// 设置日期为本月最大日期
							calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));

							dto.setStartdateEnddate(DateUtil.convertDateToString(DateUtil.convertStringToDate(t.getStartDate()),"yyyy年MM月dd日")+"-"+DateUtil.convertDateToString(calendar.getTime(),"yyyy年MM月dd日"));
						}

						for(TaskFeedback taskFeedback:taskFeedbackListOne){
							//正在执行,循环子任务列表，返回正在执行的任务，有且只有一条
							/*TaskFeedBackDto taskFeedBackDto1 = null;
							if(taskFeedback.getEndTime()!=null){
								dto.setFinishDate(DateUtil.convertDateToString(taskFeedback.getEndTime(),"yyyy-MM-dd hh:mm:ss"));
								taskFeedBackDto1 = feedbackService.findNextFeedBack_back(dto);
							}*/
							if(taskFeedback.getTaskStatus()!=null&&taskFeedback.getTaskStatus().getId()==2) {
								if (taskFeedBackDto != null) {
									dto.setNextScheduleDate(DateUtil.convertDateToString(DateUtil.convertStringToDate(taskFeedBackDto.getTaskDate() + " " + taskFeedBackDto.getDetails().get(0).getTaskStart()), "yyyy年MM月dd日 HH:mm") + "-" + DateUtil.convertDateToString(DateUtil.convertStringToDate(taskFeedBackDto.getTaskDate() + " " + taskFeedBackDto.getDetails().get(0).getTaskEnd()), "HH:mm"));
								}

								dto.setTaskStatus(Constants.TASKSTATUS_DOING);
								//		dto.setCountdownTime("还有"+String.valueOf(DateUtil.dateDiff(new Date(),taskFeedback.getEndTime())*24)+"小时下班");
								dto.setCountdownTime("已执行时长：" + String.valueOf(DateUtil.hourDiff(taskFeedback.getStartTime(), new Date())));

							}else if(/*taskFeedback.getStartTime()!=null&&taskFeedback.getEndTime()!=null*//*(taskFeedback.getEndTime()!=null&&taskFeedBackDto1==null)||*/(taskFeedBackDto==null&&taskFeedback.getStartTime()!=null&&taskFeedback.getEndTime()!=null&&taskFeedback.getTaskStatus().getId()==3)){
								dto.setTaskStatus(Constants.TASKSTATUS_FINISH);
								dto.setFinishDate(DateUtil.convertDateToString(t.getUpdateTime(),"yyyy年MM月dd日"));

								dto.setCountTime("总时长："+fInt+"小时"+(int)(fPoint*60)+"分钟");

							}//即将开始，判断是否有下一班次，如果有，则返回相应信息
							else{
								dto.setTaskStatus(Constants.TASKSTATUS_TODO);
								String beginTime=String.valueOf(DateUtil.hourDiff(new Date(),DateUtil.convertStringToDate(taskFeedback.getTaskDate()+" "+taskFeedback.getTaskStart())));
								if(taskFeedback.getStartTime()!=null){
									if (taskFeedBackDto != null) {
										dto.setNextScheduleDate(DateUtil.convertDateToString(DateUtil.convertStringToDate(taskFeedBackDto.getTaskDate() + " " + taskFeedBackDto.getDetails().get(0).getTaskStart()), "yyyy年MM月dd日 HH:mm") + "-" + DateUtil.convertDateToString(DateUtil.convertStringToDate(taskFeedBackDto.getTaskDate() + " " + taskFeedBackDto.getDetails().get(0).getTaskEnd()), "HH:mm"));
									}
									beginTime=String.valueOf(DateUtil.hourDiff(new Date(),DateUtil.convertStringToDate(taskFeedBackDto.getTaskDate() + " " + taskFeedBackDto.getDetails().get(0).getTaskStart())));
									dto.setBeginTime("还有"+beginTime+"开始");
								}else{
									dto.setNextScheduleDate(DateUtil.convertDateToString(DateUtil.convertStringToDate(taskFeedback.getTaskDate()+" "+taskFeedback.getTaskStart()),"yyyy年MM月dd日 HH:mm")+"-"+DateUtil.convertDateToString(DateUtil.convertStringToDate(taskFeedback.getTaskDate()+" "+taskFeedback.getTaskEnd()),"HH:mm"));
									if(!beginTime.equals("")){
										dto.setBeginTime("还有"+beginTime+"开始");
									}else{
										dto.setBeginTime("已迟到");
									}
								}


							}
							setCommonValue(t,dto);
							list.add(dto);
							break;
						}
					}
				}
			}

			TaskListSearchDto searchDto = new TaskListSearchDto();
			//根据状态排序
			Collections.sort(list, new Comparator<TaskListDto>() {
				@Override
				public int compare(TaskListDto o1, TaskListDto o2) {
					int i = Integer.valueOf(o1.getTaskStatus()) - Integer.valueOf(o2.getTaskStatus());
					if (i == 0) {
						long t1 = 0,t2=0;
						if(o1.getNextScheduleDate()!=null){
							t1 = DateUtil.parseDate(o1.getNextScheduleDate().substring(0, 17));
						}
						if(o2.getNextScheduleDate()!=null){
							t2 = DateUtil.parseDate(o2.getNextScheduleDate().substring(0, 17));
						}
						if (t1 > t2) {
							return 1;
						} else if (t1 < t2) {
							return -1;
						} else {
							return 0;
						}
					}

					return i;
				}
			});
			searchDto.setData(list);
			searchDto.setTotalCount(resultdto.getTotalCount());
			searchDto.setPageNum(resultdto.getPageNum());
			searchDto.setNumPerPage(resultdto.getNumPerPage());
			result.setEncodeData(searchDto);
		    result.setSuccessful(true);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	/**
	 * 获取用户进行中及即将开始的任务列表
	 * @return
	 */
	@RequestMapping("findTaskList/{personId}")
	public @ResponseBody AppAjaxResult findTaskList(@PathVariable("personId")Long personId) throws Exception {
		AppAjaxResult result = new AppAjaxResult();
		try {
			SecurityPerson person = personService.findById(personId);
			if(person == null) {
				throw new RuntimeException("无此保安员，personID:" + personId);
			}
			TaskStatus taskStatus = new TaskStatus();
			taskStatus.setId(2l);

			//获取用户进行中的任务列表
			List<Task> taskList = taskService.findTaskList(person.getId(), taskStatus.getId(), null);
			
			taskStatus.setId(1l);
			//获取用户即将开始的任务列表
			//2017-03-14 黄旭煦 取消时间限制
			List<Task> feedbackList = taskService.findTaskList(person.getId(),taskStatus.getId(),null);
			
			
			//获取用户进行中的任务列表
//			List<TaskFeedback> taskList = feedbackService.findFeedbackList(person.getId(), taskStatus.getId(), null);
			
//			taskStatus.setId(1l);
			//获取用户即将开始的任务列表
			//2017-03-14 黄旭煦 取消时间限制
//			List<TaskFeedback> feedbackList = feedbackService.findFeedbackList(person.getId(),taskStatus.getId(),null);
			
			if(taskList != null && taskList.size() >0){
				if(feedbackList != null && feedbackList.size() >0){
					for (Task taskFeedback : feedbackList) {
						taskList.add(taskFeedback);
					}
				}
				result.setEncodeData(taskList);
			}else{
				result.setEncodeData(feedbackList);
			}
			result.setSuccessful(true);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	
	/**
	 * 获取用户进行中的任务列表
	 * @return
	 */
	@RequestMapping("findDoingTaskList/{personId}")
	@Deprecated
	public @ResponseBody AppAjaxResult findDoingTaskList(@PathVariable("personId")Long personId) throws Exception {
		AppAjaxResult result = new AppAjaxResult();
		try {
			SecurityPerson person = personService.findById(personId);
			if(person == null) {
				throw new RuntimeException("无此保安员，personID:" + personId);
			}
			TaskStatus taskStatus = new TaskStatus();
			taskStatus.setId(2l);

			//获取用户进行中的任务列表
			List<TaskFeedback> taskList = feedbackService.findFeedbackList(person.getId(), taskStatus.getId(), null);
			result.setEncodeData(taskList);
			result.setSuccessful(true);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	/**
	 * 获取用户末接收任务列表
	 * @return
	 */
	@RequestMapping("findUnAcceptByPerson/{personId}")
	@Deprecated
	public @ResponseBody AppAjaxResult findUnAcceptByPerson(@PathVariable("personId")Long personId) throws Exception {
		AppAjaxResult result = new AppAjaxResult();
		try {
			SecurityPerson person = personService.findById(personId);
			if(person == null) {
				throw new RuntimeException("无此保安员，personID:" + personId);
			}
			List<Task> taskList = taskService.findByPersonAcceptStatus(personId, 0);
			result.setSuccessful(true);
			result.setEncodeData(taskList);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}

	/**
	 * 更新Feedback（签到与反馈）
	 * @return
	 */
	@RequestMapping("updateFeedback")
	public @ResponseBody AppAjaxResult updateFeedback(AppAjaxResult appResult) throws Exception {
		AppAjaxResult result = new AppAjaxResult();
		try {
			TaskFeedback feedback = appResult.getDecodeData(TaskFeedback.class);
			TaskFeedback taskFeedback = feedbackService.saveOrUpdate(feedback);
			result.setSuccessful(true);
			result.setEncodeData(taskFeedback);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	
	/**
	 * 根据任务ID获取反馈列表
	 * @param taskId
	 * @return
	 */
	@RequestMapping("findFeedbackList/{taskId}")
	public @ResponseBody AppAjaxResult findFeedbackList(@PathVariable("taskId")Long taskId) throws Exception {
		AppAjaxResult result = new AppAjaxResult();
		try {
			List<TaskFeedback> feedbackList = feedbackService.findByTaskId(taskId);
			result.setSuccessful(true);
			result.setEncodeData(feedbackList);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}

	/**
	 * 返回指定用户未给反馈的列表
	 * @return
	 */
	@RequestMapping("findNotFeedbackByPersonId/{personId}")
	@Deprecated
	public @ResponseBody AppAjaxResult findNotFeedbackByPersonId(@PathVariable("personId")Long personId) throws Exception {
		AppAjaxResult result = new AppAjaxResult();
		try {
			List<TaskFeedback> feedbackList = feedbackService.findNotFeedback(personId);
			result.setSuccessful(true);
			result.setEncodeData(feedbackList);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	/**
	 * 记录任务轨迹
	 * @param appResult
	 * @return
	 */
	@RequestMapping("updateTrack")
	public @ResponseBody AppAjaxResult updateTrack(AppAjaxResult appResult) throws Exception {
		AppAjaxResult result = new AppAjaxResult();
		try { 
			TaskTrack track = appResult.getDecodeData(TaskTrack.class);
			if(track.getLongitude() != null && track.getLongitude().trim().length() > 0
					&& track.getLatitude() != null && track.getLatitude().trim().length() > 0) {
				/*//定位位置纠偏
				double[] latlng = new  double[2];
				GpsCorrect.transform(Double.valueOf(track.getLatitude()),Double.valueOf(track.getLongitude()),latlng);
				track.setLatitude(Double.toString(latlng[0]));
				track.setLongitude(Double.toString(latlng[1]));*/
				trackService.save(track);
				result.setSuccessful(true);
			}
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	
	/**
	 * 获取任务轨迹
	 * @return
	 */
	@RequestMapping("findTrackList/{feedbackId}")
	public @ResponseBody AppAjaxResult findTrackList(@PathVariable("feedbackId")Long feedbackId) throws Exception {
		AppAjaxResult result = new AppAjaxResult();
		try {
			List<TaskTrack> trackList = trackService.findByFeedbackId(feedbackId);
			result.setSuccessful(true);
			result.setEncodeData(trackList);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	
	/**
	 * 新增或更新人员的任务接受状态(接受或者拒绝任务)
	 * @return
	 */
	@RequestMapping("updateAcceptStatus")
	public @ResponseBody AppAjaxResult updateAcceptStatus(AppAjaxResult appResult) throws Exception{
		AppAjaxResult result = new AppAjaxResult();
		try {
			TaskPerson taskPerson = appResult.getDecodeData(TaskPerson.class);
			taskService.updateAcceptStatus(taskPerson);
			result.setSuccessful(true);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}


	/**
	 * 获取反馈信息
	 * @return
	 */
	@RequestMapping("findTaskFeedBack/{id}")
	public @ResponseBody AppAjaxResult findTaskFeedBack(@PathVariable("id")Long id ) {
		AppAjaxResult result = new AppAjaxResult();
		try {
			TaskFeedback feedback = feedbackService.findById(id);
			if(feedback != null){
				result.setSuccessful(true);
				result.setEncodeData(feedback);
			}else{
				result.setMsg("无相关数据！");
				result.setSuccessful(false);
			}
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			result.setSuccessful(false);
			result.setMsg(e.getMessage());
		}
		return result;
	}
	
	@RequestMapping("findTaskDetail")
	public @ResponseBody AppAjaxResult findTaskDetail(AppAjaxResult appResult){
		AppAjaxResult result = new AppAjaxResult();
		try {
			TaskDetailSearchDto taskDetailDto = appResult.getDecodeData(TaskDetailSearchDto.class);
			if(taskDetailDto.getTaskid() == null){
				throw new ArsException("任务id错误");
			}
			if(taskDetailDto.getPersonid() == null){
				throw new ArsException("保安员id错误");
			}
			TaskDto taskDto = taskService.findTaskDetail(taskDetailDto);
			result.setSuccessful(true);
			result.setEncodeData(taskDto);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	
	@RequestMapping("findTaskDetail/test")
	@Deprecated
	public @ResponseBody AppAjaxResult findTaskDetail_test(TaskDetailSearchDto taskDetailDto){
		AppAjaxResult result = new AppAjaxResult();
		try {
			TaskDto taskDto = taskService.findTaskDetail(taskDetailDto);
			result.setSuccessful(true);
			System.out.println(JSON.toJSONString(taskDto));
			result.setEncodeData(taskDto);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}

	@RequestMapping("findTaskFeedbasksByTask")
	public @ResponseBody AppAjaxResult findTaskFeedbasksByTask(AppAjaxResult appResult){
		AppAjaxResult result = new AppAjaxResult();
		try {
			TaskDetailSearchDto taskDetailDto = appResult.getDecodeData(TaskDetailSearchDto.class);
			if(taskDetailDto.getTaskid() == null){
				throw new ArsException("任务id错误");
			}
			if(taskDetailDto.getPersonid() == null){
				throw new ArsException("保安员id错误");
			}
			if(StringUtil.isEmpty(taskDetailDto.getTaskdate())){
				throw new ArsException("查询年月错误");
			}
			List<TaskFeedBackDto> feedbasks = feedbackService.findTaskFeedbasksByTask(taskDetailDto,null);
			result.setSuccessful(true);
			result.setEncodeData(feedbasks);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	
	@RequestMapping("findTaskFeedbasksByTask/test")
	@Deprecated
	public @ResponseBody AppAjaxResult findTaskFeedbasksByTask_test(TaskDetailSearchDto taskDetailDto){
		AppAjaxResult result = new AppAjaxResult();
		try {
			List<TaskFeedBackDto> feedbasks = feedbackService.findTaskFeedbasksByTask(taskDetailDto,null);
			result.setSuccessful(true);
			System.out.println(JSON.toJSONString(feedbasks));
			result.setEncodeData(feedbasks);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	
	/*************************************V1.0.9APP版本***************************************/
	/**
	 * 获取用户任务列表
	 * @return
	 */
	@RequestMapping("v-1-0-9/findTaskListNew")
	public @ResponseBody AppAjaxResult findTaskListNew_V109(AppAjaxResult appResult) throws Exception {
		AppAjaxResult result = new AppAjaxResult();
		try {
			TaskSearchDto taskSearchDto = appResult.getDecodeData(TaskSearchDto.class);
			SecurityPerson person = personService.findById(taskSearchDto.getPersonId());
			if (person == null) {
				result.setMsg("查找不到保安员人信息，personID:" + taskSearchDto.getPersonId());
			    result.setSuccessful(false);
			    return result;
			}
			if(StringUtils.isEmpty(taskSearchDto.getAcceptStatus())){
				result.setMsg("任务状态不能为空");
			    result.setSuccessful(false);
			    return result;
			}
			//获取用户的任务列表
			String acceptStatus = ""; //查询任务状态
			String currentTaskStatus = ""; //当然任务状态
			/**
			 * 任务状态转换
			 * (2 执行中或即将开始、已完成)转换成查询条件1
			 */
			if(taskSearchDto.getAcceptStatus().equals(Constants.ACCEPTASKSTATUS_OTHER)){
				acceptStatus = "1";
			}else if(taskSearchDto.getAcceptStatus().equals(Constants.ACCEPTASKSTATUS_FINISHALL)){
				acceptStatus = "3";
			}
			TaskSearchDto resultdto =taskService.findTaskListByPersonid_V109(taskSearchDto);
			List<Task> taskList = resultdto.getData();
			List<TaskListDto> list = new ArrayList<TaskListDto>();
			if(taskList!=null&&taskList.size()>0){
				for(Task t:taskList){
					currentTaskStatus = t.getCurrentTaskStatus();
					//3 任务已结束
					if(acceptStatus.equals("3")){
						if(!currentTaskStatus.equals("3")){
							continue;
						}
						TaskListDto dto =new TaskListDto();
						//计算执行时间
						double finishSumTime = feedbackService.findFeedBackFinishSumTime(t.getId(),taskSearchDto.getPersonId());//总秒数
						double counttime= finishSumTime/3600; //转成小时
						int fInt = (int) counttime;
						BigDecimal b1 = new BigDecimal(Double.toString(counttime));
						BigDecimal b2 = new BigDecimal(Integer.toString(fInt));
						float fPoint = b1.subtract(b2).floatValue();
						dto.setCountTime("总时长："+fInt+"小时"+(int)(fPoint*60)+"分钟");
						//任务状态
						dto.setTaskStatus(Constants.TASKSTATUS_FINISHALL);
						//结束日期
						dto.setFinishDate(DateUtil.convertDateToString(t.getUpdateTime(),"yyyy年MM月dd日"));
						setCommonValue(t,dto);
						//任务日期
						dto.setStartdateEnddate(DateUtil.convertDateToString(DateUtil.convertStringToDate(t.getStartDate()),"yyyy年MM月dd日")+"-"+DateUtil.convertDateToString(DateUtil.convertStringToDate(t.getEndDate()),"yyyy年MM月dd日"));
						list.add(dto);
					}
					if(acceptStatus.equals("1")){//1-已接受
						if(currentTaskStatus.equals("3")){
							continue;
						}
						if(t.getTaskType()!=null&&t.getTaskType().getId()==4){//紧急任务
							List<TaskFeedback> taskFeedbackList =feedbackService.findUrgentFeedbackByTaskid(t.getId(),taskSearchDto.getPersonId());
							if(taskFeedbackList != null && taskFeedbackList.size() > 0){
								for(TaskFeedback taskFeedback:taskFeedbackList){
									TaskListDto dto =new TaskListDto();
									//紧急任务的接受日期
									dto.setAccepDate(DateUtil.convertDateToString(taskFeedback.getCreateTime(),"yyyy年MM月dd日 HH:mm"));
									//紧急任务的发布日期
									dto.setStartDate(DateUtil.convertDateToString(DateUtil.convertStringToDate(t.getStartDate()),"yyyy年MM月dd日 HH:mm"));
									if(taskFeedback.getTaskStatus()!=null&&taskFeedback.getTaskStatus().getId()==2){
										//正在执行，已执行时长为当前时间减去开始时间
										dto.setTaskStatus(Constants.TASKSTATUS_DOING);
										dto.setCountdownTime("已执行时长："+String.valueOf(DateUtil.hourDiff(taskFeedback.getStartTime(),new Date())));
									}else {
										//完成，已执行时长为结束时间减去开始时间
										dto.setTaskStatus(Constants.TASKSTATUS_FINISH);
										dto.setCountdownTime("已执行时长："+String.valueOf(DateUtil.hourDiff(taskFeedback.getStartTime(),taskFeedback.getEndTime())));
										//紧急任务结束日期
										dto.setFinishDate(DateUtil.convertDateToString(taskFeedback.getEndTime(),"yyyy年MM月dd日"));
									}
									setCommonValue(t,dto);
									list.add(dto);
									break;
								}
							}
							continue;
						}
						//已完成任务
						if(currentTaskStatus.equals("2")){
							TaskListDto dto =new TaskListDto();
							//计算执行时间
							double finishSumTime = feedbackService.findFeedBackFinishSumTime(t.getId(),taskSearchDto.getPersonId());//总秒数
							double counttime= finishSumTime/3600; //转成小时
							int fInt = (int) counttime;
							BigDecimal b1 = new BigDecimal(Double.toString(counttime));
							BigDecimal b2 = new BigDecimal(Integer.toString(fInt));
							float fPoint = b1.subtract(b2).floatValue();
							dto.setCountTime("总时长："+fInt+"小时"+(int)(fPoint*60)+"分钟");
							//任务状态
							dto.setTaskStatus(Constants.TASKSTATUS_FINISH);
							//结束日期
							dto.setFinishDate(DateUtil.convertDateToString(t.getUpdateTime(),"yyyy年MM月dd日"));
							setCommonValue(t,dto);
							//任务日期
							dto.setStartdateEnddate(DateUtil.convertDateToString(DateUtil.convertStringToDate(t.getStartDate()),"yyyy年MM月dd日")+"-"+DateUtil.convertDateToString(DateUtil.convertStringToDate(t.getEndDate()),"yyyy年MM月dd日"));
							list.add(dto);
							continue;
						}
						//正在执行任务
						if(currentTaskStatus.equals("1")){

							//获取正在执行的班次列表
							TaskDetailSearchDto taskDetailDto = new TaskDetailSearchDto();
							taskDetailDto.setTaskid(t.getId());
							taskDetailDto.setPersonid(taskSearchDto.getPersonId());
							taskDetailDto.setScheduleStatus("3");
							List<TaskFeedBackDto> taskFeedBackDto_list = feedbackService.findFeedBasksByScheduleStatus(taskDetailDto);
							Date startTime = null;
							if(taskFeedBackDto_list!=null&&taskFeedBackDto_list.size()>0){
								TaskFeedBackDto taskFeedBackDto = taskFeedBackDto_list.get(0);
								if(taskFeedBackDto.getDetails()!=null && taskFeedBackDto.getDetails().size() > 0){
									FeedBackDetailDto feedBackDetailDto = taskFeedBackDto.getDetails().get(0);
									startTime = DateUtil.convertStringToDate(feedBackDetailDto.getStartTime());
								}
							}
							//下一班次的子任务信息
							TaskListDto dto =new TaskListDto();
							dto.setPersonId(taskSearchDto.getPersonId());
							dto.setTaskId(t.getId());
							TaskFeedBackDto taskFeedBackDto = feedbackService.findNextFeedBack_back(dto);
							
							//周期任务
							if(t.getTaskType()!=null&&t.getTaskType().getId()==1){
								if(t.isRepeat()==true){
									dto.setStartdateEnddate(DateUtil.convertDateToString(t.getCreateTime(),"yyyy年MM月dd日"));
								}else{
									// 获取Calendar
									Calendar calendar = Calendar.getInstance();
									// 设置时间,当前时间不用设置
									 calendar.setTime(DateUtil.convertStringToDate(t.getEndDate()));
									// 设置日期为本月最大日期
									calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));
									dto.setStartdateEnddate(DateUtil.convertDateToString(DateUtil.convertStringToDate(t.getStartDate()),"yyyy年MM月dd日")+"-"+DateUtil.convertDateToString(calendar.getTime(),"yyyy年MM月dd日"));
								}
							}else{
								//任务日期
								dto.setStartdateEnddate(DateUtil.convertDateToString(DateUtil.convertStringToDate(t.getStartDate()),"yyyy年MM月dd日")+"-"+DateUtil.convertDateToString(DateUtil.convertStringToDate(t.getEndDate()),"yyyy年MM月dd日"));
							}
							//正在执行
							dto.setTaskStatus(Constants.TASKSTATUS_DOING);
							//下一班次
							if(taskFeedBackDto!=null){
								dto.setNextScheduleDate(DateUtil.convertDateToString(DateUtil.convertStringToDate(taskFeedBackDto.getTaskDate()+" "+taskFeedBackDto.getDetails().get(0).getTaskStart()),"yyyy年MM月dd日 HH:mm")+"-"+DateUtil.convertDateToString(DateUtil.convertStringToDate(taskFeedBackDto.getTaskDate()+" "+taskFeedBackDto.getDetails().get(0).getTaskEnd()),"HH:mm"));
							}
							if(startTime != null){
								dto.setCountdownTime("已执行时长："+String.valueOf(DateUtil.hourDiff(startTime,new Date())));
							}
							setCommonValue(t,dto);
							list.add(dto);
							continue;
						}
						//即将进行任务
						if(currentTaskStatus.equals("5")){
							List<TaskFeedback> taskFeedbackListOne =feedbackService.findFeedbackByTaskid_V109(t.getId(),taskSearchDto.getPersonId());
							//下一班次的子任务信息
							TaskListDto dto =new TaskListDto();
							dto.setPersonId(taskSearchDto.getPersonId());
							dto.setTaskId(t.getId());
							TaskFeedBackDto taskFeedBackDto = feedbackService.findNextFeedBack_back(dto);
							//任务日期
							//周期任务
							if(t.getTaskType()!=null&&t.getTaskType().getId()!=1){
								dto.setStartdateEnddate(DateUtil.convertDateToString(DateUtil.convertStringToDate(t.getStartDate()),"yyyy年MM月dd日")+"-"+DateUtil.convertDateToString(DateUtil.convertStringToDate(t.getEndDate()),"yyyy年MM月dd日"));
							}
							//循环子任务列表，返回正在执行的任务，有且只有一条
							if(taskFeedbackListOne != null && taskFeedbackListOne.size() > 0){
								for(TaskFeedback taskFeedback:taskFeedbackListOne){
									dto.setTaskStatus(Constants.TASKSTATUS_TODO);
									String beginTime=String.valueOf(DateUtil.hourDiff(new Date(),DateUtil.convertStringToDate(taskFeedback.getTaskDate()+" "+taskFeedback.getTaskStart())));
									if(taskFeedback.getStartTime()!=null){
										if (taskFeedBackDto != null) {
											dto.setNextScheduleDate(DateUtil.convertDateToString(DateUtil.convertStringToDate(taskFeedBackDto.getTaskDate() + " " + taskFeedBackDto.getDetails().get(0).getTaskStart()), "yyyy年MM月dd日 HH:mm") + "-" + DateUtil.convertDateToString(DateUtil.convertStringToDate(taskFeedBackDto.getTaskDate() + " " + taskFeedBackDto.getDetails().get(0).getTaskEnd()), "HH:mm"));
											beginTime=String.valueOf(DateUtil.hourDiff(new Date(),DateUtil.convertStringToDate(taskFeedBackDto.getTaskDate() + " " + taskFeedBackDto.getDetails().get(0).getTaskStart())));
											dto.setBeginTime("还有"+beginTime+"开始");
										}
									}else{
										dto.setNextScheduleDate(DateUtil.convertDateToString(DateUtil.convertStringToDate(taskFeedback.getTaskDate()+" "+taskFeedback.getTaskStart()),"yyyy年MM月dd日 HH:mm")+"-"+DateUtil.convertDateToString(DateUtil.convertStringToDate(taskFeedback.getTaskDate()+" "+taskFeedback.getTaskEnd()),"HH:mm"));
										if(!beginTime.equals("")){
											dto.setBeginTime("还有"+beginTime+"开始");
										}else{
											dto.setBeginTime("已迟到");
										}
									}
									setCommonValue(t,dto);
									list.add(dto);
									break;
								}
							}else{
								setCommonValue(t,dto);
								list.add(dto);
							}
							continue;
						}
					}
				}
			}
			TaskListSearchDto searchDto = new TaskListSearchDto();
			//根据状态排序
			Collections.sort(list, new Comparator<TaskListDto>() {
				@Override
				public int compare(TaskListDto o1, TaskListDto o2) {
					int i = Integer.valueOf(o1.getCurrentTaskStatus()) - Integer.valueOf(o2.getCurrentTaskStatus());
					if (i == 0) {
						long t1 = 0,t2=0;
						if(o1.getNextScheduleDate()!=null){
							t1 = DateUtil.parseDate(o1.getNextScheduleDate().substring(0, 17));
						}
						if(o2.getNextScheduleDate()!=null){
							t2 = DateUtil.parseDate(o2.getNextScheduleDate().substring(0, 17));
						}
						if (t1 > t2) {
							
							return 1;
						} else if (t1 < t2) {
							return -1;
						} else {
							return 0;
						}
					}

					return i;
				}
			});
			searchDto.setData(list);
			searchDto.setTotalCount(resultdto.getTotalCount());
			searchDto.setPageNum(resultdto.getPageNum());
			searchDto.setNumPerPage(resultdto.getNumPerPage());
			result.setEncodeData(searchDto);
		    result.setSuccessful(true);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	/**
	 * 保存子任务反馈日志信息
	 * @return
	 */
	@RequestMapping("v-1-0-9/savetaskfeedbacklog")
	public @ResponseBody AppAjaxResult saveTaskFeedBackLog(AppAjaxResult appResult) throws Exception {
		AppAjaxResult result = new AppAjaxResult();
		try {
			String errMsg = "";
			TaskFeedbackLog taskFeedbackLog = appResult.getDecodeData(TaskFeedbackLog.class);
			TaskFeedback taskFeedback =taskFeedbackLog.getTaskFeedback();
			if(taskFeedback==null || taskFeedback.getId() ==null){
				errMsg = "参数子任务ID不能为空";
				result.setSuccessful(false);
				result.setMsg(errMsg);
				return result;
			}
			if(taskFeedbackLog.getPerson()==null || taskFeedbackLog.getPerson().getId() ==null){
				errMsg = "用户ID不能为空";
				result.setSuccessful(false);
				result.setMsg(errMsg);
				return result;
			}
			if(StringUtils.isEmpty(taskFeedbackLog.getComment())){
				errMsg = "反馈日志不能为空";
				result.setSuccessful(false);
				result.setMsg(errMsg);
				return result;
			}
			if(StringUtils.isEmpty(taskFeedbackLog.getDutyState())){
				errMsg = "值班状态不能为空";
				result.setSuccessful(false);
				result.setMsg(errMsg);
				return result;
			}
			taskFeedbackLog = taskFeedbackLogService.saveOrUpdate(taskFeedbackLog);
			result.setSuccessful(true);
			result.setEncodeData(taskFeedbackLog);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	
	/**
	 * 根据保安员ID、子任务ID获取反馈的任务日志列表
	 * @param taskId
	 * @return
	 */
	@RequestMapping("v-1-0-9/findfeedbackloglist/{personId}/{feedbackId}")
	public @ResponseBody AppAjaxResult findFeedbackLogList(@PathVariable("personId")Long personId,
			@PathVariable("feedbackId")Long feedbackId) throws Exception {
		AppAjaxResult result = new AppAjaxResult();
		try {
			List<TaskFeedbackLog> taskFeedbackLogList = taskFeedbackLogService.findFeedbackLogList(personId, feedbackId);
			result.setSuccessful(true);
			result.setEncodeData(taskFeedbackLogList);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	
	/**
	 * 根据子任务ID获取子任务详情信息
	 * @param feedbackId
	 * @return
	 */
	@RequestMapping("v-1-0-9/findfeedbackdetailbyid/{feedbackId}")
	public @ResponseBody AppAjaxResult findFeedBackDetailById(@PathVariable("feedbackId")Long feedbackId) throws Exception {
		AppAjaxResult result = new AppAjaxResult();
		try {
			FeedBackDetailDto feedBackDetailDto = feedbackService.findFeedBackDetailById(feedbackId);
			result.setSuccessful(true);
			result.setEncodeData(feedBackDetailDto);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	/**
	 * 根据保安员ID获取正在执行的子任务
	 * @param personId
	 * @return
	 */
	@RequestMapping("v-1-0-9/findbackdetailbypersonid/{personId}")
	public @ResponseBody AppAjaxResult findBackDetailByPersonid(@PathVariable("personId")Long personId) throws Exception {
		AppAjaxResult result = new AppAjaxResult();
		try {
			List<FeedBackDetailDto> feedBackDetailDtoList = feedbackService.findBackDetailByPersonid(personId);
			if(feedBackDetailDtoList!=null && feedBackDetailDtoList.size() >0){
				result.setSuccessful(true);
				result.setEncodeData(feedBackDetailDtoList.get(0));
			}else{
				result.setSuccessful(false);
			}
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	
	/**
	 * 任务签到
	 * @return
	 */
	@RequestMapping("v-1-0-9/updateFeedback")
	public @ResponseBody AppAjaxResult updateFeedbackV109(AppAjaxResult appResult) throws Exception {
		AppAjaxResult result = new AppAjaxResult();
		try {
			TaskFeedback feedback = appResult.getDecodeData(TaskFeedback.class);
			TaskFeedback taskFeedback = feedbackService.saveAppSign(feedback);
			String msg = "您还有一个任务未完成，不能签到。如需提前离岗，请点击下班填写离岗原因。";
			if(taskFeedback == null){
				result.setSuccessful(false);
				result.setMsg(msg);
			}else{
				result.setSuccessful(true);
				result.setEncodeData(taskFeedback);
			}
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	/**
	 * 任务详情
	 * @return
	 */
	@RequestMapping("v-1-0-9/findTaskDetail")
	public @ResponseBody AppAjaxResult findTaskDetailV109(AppAjaxResult appResult){
		AppAjaxResult result = new AppAjaxResult();
		try {
			TaskDetailSearchDto taskDetailDto = appResult.getDecodeData(TaskDetailSearchDto.class);
			if(taskDetailDto.getTaskid() == null){
				throw new ArsException("任务id错误");
			}
			if(taskDetailDto.getPersonid() == null){
				throw new ArsException("保安员id错误");
			}
			TaskDto taskDto = taskService.findTaskDetailV109(taskDetailDto);
			result.setSuccessful(true);
			result.setEncodeData(taskDto);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	/**
	 * 根据任务ID，保安人员ID，查询年月获取任务班次列表
	 * @param appResult
	 * @return
	 */
	@RequestMapping("v-1-0-9/findTaskFeedbasksByTask")
	public @ResponseBody AppAjaxResult findTaskFeedbasksByTaskV109(AppAjaxResult appResult){
		AppAjaxResult result = new AppAjaxResult();
		try {
			TaskDetailSearchDto taskDetailDto = appResult.getDecodeData(TaskDetailSearchDto.class);
			if(taskDetailDto.getTaskid() == null){
				throw new ArsException("任务id错误");
			}
			if(taskDetailDto.getPersonid() == null){
				throw new ArsException("保安员id错误");
			}
			if(StringUtil.isEmpty(taskDetailDto.getTaskdate())){
				throw new ArsException("查询年月错误");
			}
			List<TaskFeedBackDto> feedbasks = feedbackService.findTaskFeedbasksByTask_V109(taskDetailDto);
			result.setSuccessful(true);
			result.setEncodeData(feedbasks);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
}
