package com.bcxin.ars.rest;

import com.alibaba.fastjson.JSON;
import com.bcxin.ars.dto.*;
import com.bcxin.ars.dto.task.UpdateTaskDTO;
import com.bcxin.ars.model.*;
import com.bcxin.ars.model.sys.Sysarea;
import com.bcxin.ars.model.task.*;
import com.bcxin.ars.rest.dto.AppAjaxResult;
import com.bcxin.ars.rest.util.ArsRestUtil;
import com.bcxin.ars.service.DatasyncService;
import com.bcxin.ars.service.SecurityCompanyService;
import com.bcxin.ars.service.SecurityPersonService;
import com.bcxin.ars.service.sys.SysareaService;
import com.bcxin.ars.service.task.TaskFeedbackService;
import com.bcxin.ars.service.task.TaskService;
import com.bcxin.ars.service.task.TaskTrackService;
import com.bcxin.ars.util.BeanUtils;
import com.bcxin.ars.util.DateUtil;
import com.bcxin.ars.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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 org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.*;


@Controller
@RequestMapping("task")
public class TaskController {
	
	private static final Logger logger = LoggerFactory.getLogger(TaskController.class);
	
	@Autowired
	private TaskService taskService;
	
	@Autowired
	private TaskTrackService trackService;
	
	@Autowired
	private TaskFeedbackService feedbackService;
	
	@Autowired
	private SecurityCompanyService companyService;

	@Autowired
	private SecurityPersonService securityPersonService;
	
	@Autowired
	private SecurityPersonService personService;


	@Autowired
	private SysareaService sysareaService;


	@Autowired
	private ArsRestUtil arsRestUtil;

	@Autowired
	private TaskTrackService taskTrackService;

	@Autowired
	private DatasyncService datasyncService;

	@Autowired
	private ArsRestUtil arsUtil;

	@Value("${task-download-folder}")
	private String downloadFolder;

	@Value("${upload-folder}")
	private String uploadFolder;

	/**
	 * 任务一键搜功能
	 * @param dto
	 * @return
	 */
	@RequestMapping("search")
//	@RequiresPermissions("search:read")
	public @ResponseBody AjaxResult search(TaskSearchDto dto) throws Exception {
		AjaxResult result = new AjaxResult();
		try {
			TaskSearchDto data = taskService.search(dto);
			result.setSuccessful(true);
			result.setData(data);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	
	/**
	 * 任务管理搜索功能
	 * @param dto
	 * @return
	 */
	@RequestMapping("searchForManage")
//	@RequiresPermissions("search:read")
	public @ResponseBody AjaxResult searchForManage(TaskSearchDto dto) throws Exception {
		AjaxResult result = new AjaxResult();
		try {
			TaskSearchDto data = taskService.searchForManage(dto);
			result.setSuccessful(true);
			result.setData(data);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	
	/**
	 * 任务流水一键搜功能
	 * @param dto
	 * @return
	 */
	@RequestMapping("feedback/search")
//	@RequiresPermissions("search:read")
	@Deprecated
	public @ResponseBody AjaxResult searchFeedback(TaskFeedbackSearchDto dto) throws Exception {
		AjaxResult result = new AjaxResult();
		try {
			TaskFeedbackSearchDto data = feedbackService.search(dto);
			result.setSuccessful(true);
			result.setData(data);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	
	/**
	 * 根据ID获取任务明细
	 * @return
	 */
	@RequestMapping("findById/{id}")
	public @ResponseBody AjaxResult findById(@PathVariable("id")Long id) throws Exception {
		AjaxResult result = new AjaxResult();
		try {
			Task task = taskService.findById(id);
			result.setSuccessful(true);
			result.setData(task);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	/**
	 * 根据ID获取紧急任务详细信息
	 * @return
	 */
	@RequestMapping("findUrgentById/{id}")
	public @ResponseBody AjaxResult findUrgentById(@PathVariable("id")Long id) throws Exception {
		AjaxResult result = new AjaxResult();
		try {
			Task task = taskService.findUrgentById(id);
			result.setSuccessful(true);
			result.setData(task);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	/**
	 * 新增或更新任务
	 * @return
	 */
	@RequestMapping("update")
	public @ResponseBody AjaxResult update(UpdateTaskDTO task, Long[] schedules, String persons) throws Exception {
		AjaxResult result = new AjaxResult();
		try{
			//解析排班数据
			/*
			{"personList":
			[{"id":"121","inCharge":true,"scheduleList":
			[{"taskDate":"2011-08-09","scheduleDetail":[111,222,333]}]},{"id":"132","inCharge":false,"scheduleList":[{"taskDate":"2012-08-09","scheduleDetail":[122,322,3233]}]}]}
				* */

			if(persons != null && persons.trim().length() > 10) {
				List<TaskPerson> pList = new ArrayList<TaskPerson>();
				//转化任务
				TaskScheduleDto schedule = JSON.parseObject(persons, TaskScheduleDto.class);
				for(TaskScheduleListDto person : schedule.getPersonList()) {
					TaskPerson tp = new TaskPerson();
					SecurityPerson p = new SecurityPerson();
					p.setId(Long.valueOf(person.getId()));
					tp.setPerson(p);
					tp.setInCharge(person.getInCharge());
					List<TaskPersonSchedule> tpsList = new ArrayList<TaskPersonSchedule>();
					Map map=new HashMap();
					List<SecurityCompanySchedule> scheduleList = new ArrayList<SecurityCompanySchedule>();
					for(TaskScheduleDetailDto detail : person.getScheduleList()) {
						TaskPersonSchedule tps = new TaskPersonSchedule();
						tps.setTaskPersonId(p.getId());
						tps.setTaskDate(detail.getTaskDate());
						List<SecurityCompanySchedule> csList = new ArrayList<SecurityCompanySchedule>();
						for(Long scheduleId : detail.getScheduleDetail()) {
							SecurityCompanySchedule cs = new SecurityCompanySchedule();
							cs.setId(scheduleId);
							csList.add(cs);
							if (map.get(scheduleId)==null){
								scheduleList.add(cs);
								map.put(scheduleId,scheduleId);
							}

						}

						tps.setScheduleDetail(csList);
						tpsList.add(tps);
					}
					task.setScheduleList(scheduleList);
					tp.setScheduleList(tpsList);
					pList.add(tp);
				}
				task.setPersonList(pList);
			}
			//如果是紧急任务的话，那么没有班次
			if(schedules!=null && schedules.length>0) {
				//赋值班次列表
				for (Long s : schedules) {
					SecurityCompanySchedule cs = new SecurityCompanySchedule();
					cs.setId(s);
					task.getScheduleList().add(cs);
				}
			}
			//modify zjh time:2018年8月6日 18:00:44 任务开始时间赋初值
			String startDate="";
			if (!(task.getStartDate()!=null&&StringUtil.isNotEmpty(task.getStartDate())&&task.getStartDate()!="null")){
				startDate=DateUtil.getCurrentDate("yyyy-MM-dd")+" 00:00:00";
			}else {
				startDate=task.getStartDate()+" 00:00:00";
			}
			//modify zjh time:2018年8月6日 18:00:44 任务结束时间如果没有值则不需要赋值
			task.setStartDate(startDate);
			if ((task.getEndDate()!=null&&StringUtil.isNotEmpty(task.getEndDate())&&task.getEndDate()!="null")) {
				task.setEndDate(task.getEndDate() + " 23:59:59");
			}
			Task task1=new Task();
			BeanUtils.copyPropertiesIgnore(task,task1);

		/***
		 * 地区编码转换
		 */
		Sysarea sysarea = sysareaService.findByCode(task.getArea());

		if(sysarea !=null) {
			task1.setArea(sysarea.getName());
		}


		TaskType taskType=new TaskType();
			taskType.setId(task.getTaskTypeId());
			task1.setTaskType(taskType);
			TaskLevel taskLevel=new TaskLevel();
			taskLevel.setId(task.getTaskLevelId());
			task1.setTaskLevel(taskLevel);
			TaskCatalog taskCatalog=new TaskCatalog();
			taskCatalog.setId(task.getTaskCatalogId());
			task1.setTaskCatalog(taskCatalog);



			taskService.saveOrUpdate(task1);
			result.setSuccessful(true);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	
	/**
	 * 删除任务
	 * @return
	 */
	@RequestMapping("delete/{id}")
	public @ResponseBody AjaxResult delete(@PathVariable("id")Long id) throws Exception {
		AjaxResult result = new AjaxResult();
		try {
			Task task = taskService.findById(id);
			if(task != null) {
				User user = arsRestUtil.getCurrentUser();
				SecurityCompany userCompany = null;
				if(user.getPlatform() == 2){
					userCompany = companyService.findByUserid(user.getId());
				}
				
				if(userCompany != null && userCompany.getId().longValue() == task.getCompany().getId().longValue()) {
					taskService.delete(task);
					result.setSuccessful(true);
				} else {
					result.setSuccessful(false);
					result.setMsg("你无权删除此任务，ID:" + id);
				}
			} else {
				result.setSuccessful(false);
				result.setMsg("无此任务记录，ID:" + id);
			}
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	
	/**
	 * 获取用户进行中及即将开始的任务列表
	 * @return
	 */
	@RequestMapping("findTaskList/{personId}")
	@Deprecated
	public @ResponseBody AjaxResult findTaskList(@PathVariable("personId")Long personId) throws Exception {
		AjaxResult result = new AjaxResult();
		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);
			
			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 (TaskFeedback taskFeedback : feedbackList) {
						taskList.add(taskFeedback);
					}
				}
				result.setData(taskList);
			}else{
				result.setData(feedbackList);
			}
			result.setSuccessful(true);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	
	/**
	 * 获取用户进行中的任务列表
	 * @return
	 */
	@RequestMapping("findDoingTaskList/{personId}")
	@Deprecated
	public @ResponseBody AjaxResult findDoingTaskList(@PathVariable("personId")Long personId) throws Exception {
		AjaxResult result = new AjaxResult();
		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.setData(taskList);
			result.setSuccessful(true);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	/**
	 * 获取用户末接收任务列表
	 * @return
	 */
	@RequestMapping("findUnAcceptByPerson/{personId}")
	@Deprecated
	public @ResponseBody AjaxResult findUnAcceptByPerson(@PathVariable("personId")Long personId) throws Exception {
		AjaxResult result = new AjaxResult();
		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.setData(taskList);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}

	/**
	 * 更新Feedback（签到与反馈）
	 * @return
	 */
	@RequestMapping("updateFeedback")
	@Deprecated
	public @ResponseBody AjaxResult updateFeedback(TaskFeedback feedback) throws Exception {
		AjaxResult result = new AjaxResult();
		try {
			TaskFeedback taskFeedback = feedbackService.saveOrUpdate(feedback);
			result.setSuccessful(true);
			result.setData(taskFeedback);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}

	/**
	 * 根据任务ID获取反馈列表
	 * @param taskId
	 * @return
	 */
	@RequestMapping("findFeedbackList/{taskId}")
	@Deprecated
	public @ResponseBody AjaxResult findFeedbackList(@PathVariable("taskId")Long taskId) throws Exception {
		AjaxResult result = new AjaxResult();
		try {
			List<TaskFeedback> feedbackList = feedbackService.findByTaskId(taskId);
			result.setSuccessful(true);
			result.setData(feedbackList);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	
	/**
	 * 返回当前登录用户未给反馈的列表
	 * @return
	 */
	@RequestMapping("findNotFeedback")
	@Deprecated
	public @ResponseBody AjaxResult findNotFeedback() throws Exception {
		AjaxResult result = new AjaxResult();
		try {
			result.setSuccessful(true);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	

	/**
	 * 返回指定用户未给反馈的列表
	 * @return
	 */
	@RequestMapping("findNotFeedbackByPersonId/{personId}")
	@Deprecated
	public @ResponseBody AjaxResult findNotFeedbackByPersonId(@PathVariable("personId")Long personId) throws Exception {
		AjaxResult result = new AjaxResult();
		try {
			List<TaskFeedback> feedbackList = feedbackService.findNotFeedback(personId);
			result.setSuccessful(true);
			result.setData(feedbackList);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	
	/**
	 * 记录任务轨迹
	 * @param track
	 * @return
	 */
	@RequestMapping("updateTrack")
	@Deprecated
	public @ResponseBody AjaxResult updateTrack(TaskTrack track) throws Exception {
		AjaxResult result = new AjaxResult();
		try {
			if(track.getLongitude() != null && track.getLongitude().trim().length() > 0
					&& track.getLatitude() != null && track.getLatitude().trim().length() > 0) {
				trackService.save(track);
				result.setSuccessful(true);
			}
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}




	/**
	 * 记录任务轨迹用于SaaS保存
	 * @param track
	 * @return
	 */
	@RequestMapping("saas/saveTrack")
	@Deprecated
	public @ResponseBody AjaxResult saveTrackForSaaS(TaskTrack track) throws Exception {
		AjaxResult result = new AjaxResult();
		try {
			if(track.getLongitude() != null && track.getLongitude().trim().length() > 0
					&& track.getLatitude() != null && track.getLatitude().trim().length() > 0) {
				trackService.save(track);
				result.setSuccessful(true);
			}
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}

	/**
	 * 获取任务轨迹
	 * @return
	 */
	@RequestMapping("findTrackList/{feedbackId}")
	public @ResponseBody AjaxResult findTrackList(@PathVariable("feedbackId")Long feedbackId) throws Exception {
		AjaxResult result = new AjaxResult();
		try {
			List<TaskTrack> trackList = trackService.findByFeedbackId(feedbackId);
			result.setSuccessful(true);
			result.setData(trackList);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	
	/**
	 * 新增或更新人员的任务接受状态(接受或者拒绝任务)
	 * @return
	 */
	@RequestMapping("updateAcceptStatus")
	@Deprecated
	public @ResponseBody AjaxResult updateAcceptStatus(TaskPerson taskPerson) throws Exception{
		AjaxResult result = new AjaxResult();
		try {
			taskService.updateAcceptStatus(taskPerson);
			result.setSuccessful(true);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	
	/**
	 * 任务地区画像
	 * 今后可能会用基于task表的画像接口
	 * @return
	 */
	@RequestMapping("findAreaReport")
	public @ResponseBody AjaxResult findAreaReport() throws Exception{
		AjaxResult result = new AjaxResult();
		try {
			List<ReportData> list = taskService.findAreaReport();
			result.setSuccessful(true);
			result.setData(list);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	
	/**
	 * 任务种类画像
	 * 今后可能会用基于task表的画像接口
	 * @return
	 */
	@RequestMapping("findCatalogReport")
	public @ResponseBody AjaxResult findCatalogReport() throws Exception{
		AjaxResult result = new AjaxResult();
		try {
			Map<String, String[]> data = taskService.findCatalogReport();
			result.setSuccessful(true);
			result.setData(data);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	
	/**
	 * 任务人员等级画像
	 * 今后可能会用基于task表的画像接口
	 * @return
	 */
	@RequestMapping("findLevelReport")
	public @ResponseBody AjaxResult findLevelReport() throws Exception{
		AjaxResult result = new AjaxResult();
		try {
			List<ReportData> list = taskService.findLevelReport();
			result.setSuccessful(true);
			result.setData(list);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	
	/**
	 * 任务地区画像
	 * @return
	 */
	@RequestMapping("feedback/findAreaReport")
	@Deprecated
	public @ResponseBody AjaxResult findFeedbackAreaReport() throws Exception{
		AjaxResult result = new AjaxResult();
		try {
			List<ReportData> list = feedbackService.findAreaReport();
			result.setSuccessful(true);
			result.setData(list);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	
	/**
	 * 任务种类画像
	 * @return
	 */
	@RequestMapping("feedback/findCatalogReport")
	@Deprecated
	public @ResponseBody AjaxResult findFeedbackCatalogReport() throws Exception{
		AjaxResult result = new AjaxResult();
		try {
			Map<String, String[]> data = feedbackService.findCatalogReport();
			result.setSuccessful(true);
			result.setData(data);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	
	/**
	 * 任务人员等级画像
	 * @return
	 */
	@RequestMapping("feedback/findLevelReport")
	@Deprecated
	public @ResponseBody AjaxResult findFeedbackLevelReport() throws Exception{
		AjaxResult result = new AjaxResult();
		try {
			List<ReportData> list = feedbackService.findLevelReport();
			result.setSuccessful(true);
			result.setData(list);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	
	/**
	 * 检查任务班次重复
	 * <b>Function </b> 
	 * 
	 * @param taskId
	 * @param personId
	 * @param scheduleId
	 * @param taskTypeId
	 * @param taskDate
	 * @return
	 * @throws Exception
	 * @author LinQingLin 
	 * @date 2017年8月1日 上午10:01:34
	 * @注意事项 </b>
	 * <b>
	 */
	@RequestMapping("checkTaskDateSchedule")
	public @ResponseBody AjaxResult checkTaskDateSchedule(Long taskId,Long personId,Long scheduleId,Long taskTypeId,String taskDate) throws Exception{
		AjaxResult result = new AjaxResult();
		try {
			taskService.checkTaskDateSchedule(taskId,personId,scheduleId,taskTypeId,taskDate);
			result.setSuccessful(true);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	/***
	 * 根据任务ID、人员ID获取反馈信息
	 * @param taskId 任务ID
	 * @param personId  人员ID
	 * @return
	 */
	@RequestMapping(value="findPersonTaskdetailed" )
	public @ResponseBody AjaxResult findPersonTaskdetailed(Long taskId,Long personId) throws Exception {
		AjaxResult result = new AjaxResult();
		try {
			/**
			 * 获取人员获取轨迹信息
			 */
			TaskFeedback taskFeedback = feedbackService.findByTaskIdAndPerson(taskId, personId);
			if(taskFeedback!=null){
				result.setData(taskFeedback);
				result.setSuccessful(true);
			}else {
				result.setMsg("无轨迹信息数据！");
				result.setSuccessful(false);
			}
		} 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 {
//			id=131l;
			Task task = taskService.findDetailByIdPerson(id,personId);
			if(task != null){
				result.setSuccessful(true);
				result.setData(task);
			}else{
				result.setMsg("无相关数据！");
				result.setSuccessful(false);
			}
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	/**
	 * 获取反馈信息
	 * @return
	 */
	@RequestMapping("findTaskFeedBack/{id}")
	public @ResponseBody AppAjaxResult findTaskFeedBack(@PathVariable("id")Long id ) throws Exception {
		AppAjaxResult result = new AppAjaxResult();
		try {
			TaskFeedback feedback = feedbackService.findById(id);
			if(feedback != null){
				result.setSuccessful(true);
				result.setData(feedback);
			}else{
				result.setMsg("无相关数据！");
				result.setSuccessful(false);
			}
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}


	/***
	 * 公安查询所有紧急任务
	 * @return
	 */
	@RequestMapping(value="findAllUrgentTask" )
	@Deprecated
	public @ResponseBody AjaxResult findAllUrgentTask() throws Exception {
		AjaxResult result = new AjaxResult();
		try {
			List<TaskFeedback> taskList = feedbackService.findByTaskId(new Long(131));
			result.setData(taskList);
			result.setSuccessful(true);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}


	/***
	 * 根据保安公司查询紧急任务列表
	 * @param companyId 保安公司
	 * @return
	 */
	@RequestMapping(value="findAllTaskUrgent" )
	@Deprecated
	public @ResponseBody AjaxResult findAllUrgentTaskForCompany(String companyId) throws Exception {
		AjaxResult result = new AjaxResult();
		try {
			List<Task> taskList = taskService.findByPersonAcceptStatus(new Long(0), 0);
			result.setData(taskList);
			result.setSuccessful(true);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	/**
	 * 新增紧急任务或更新紧急任务
	 * @return
	 */
	@RequestMapping("saveUrgentTask")
	public @ResponseBody AjaxResult saveOrUpdateUrgentTask(Task task,String peopletype) throws Exception {
		AjaxResult result = new AjaxResult();
		try {
//			taskService.saveOrUpdateUrgentTask(task);
			result.setSuccessful(true);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}


	/**
	 * 结束紧急任务
	 * @return
	 */
	@RequestMapping("endUrgentTaskMessage")
	public @ResponseBody AjaxResult endUrgentTaskMessage(Long taskid) throws Exception {
		AjaxResult result = new AjaxResult();
		try {
			taskService.endUrgentTaskMessage(taskid);
			result.setSuccessful(true);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	/**
	 * 结束任务
	 * @return
	 */
	@RequestMapping("endTask")
	public @ResponseBody AjaxResult saveOrUpdateUrgentTask(Long taskid) throws Exception {
		AjaxResult result = new AjaxResult();
		try {
			//结束任务
			taskService.endUrgentTask(taskid);
			result.setSuccessful(true);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	/**
	 * 查询紧急任务，当前用户是保安公司的话，那么查询保安公司相关的紧急任务，公关则查询全部
	 * @return
	 */
	@RequestMapping("findUrgentTask")
	public @ResponseBody AjaxResult findUrgentTask(UrgentTaskDTO dto) throws Exception {
		AjaxResult result = new AjaxResult();
		try {
			User user = arsRestUtil.getCurrentUser();
			if(user.getPlatform().intValue() == 2 ) {
				SecurityCompany company= companyService.findByUserid(user.getId());
				dto.setCompanyId(company.getId());
				dto = taskService.findUrgentTask(dto);
			}else{
				dto = taskService.findUrgentTask(dto);
			}
			result.setSuccessful(true);
			result.setData(dto);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	/***
	 * 保存任务与保安人员关系
	 * @param taskid
	 * @param personid
	 * @return
	 */
	@RequestMapping("saveUrgentTaskPerson")
	@Deprecated
	public @ResponseBody AjaxResult saveUrgentTaskPerson(Long taskid,Long personid) throws Exception{
		AjaxResult result = new AjaxResult();
		try {
			//保安任务与保安人员关系
			taskService.saveUrgentTaskPerson(taskid,personid);
			result.setSuccessful(true);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}

	/***
	 * 获取人员热力轨迹信息
	 * @param personid
	 * @return
	 */
	@RequestMapping("findPersonTaskHotMap/{id}")
	public @ResponseBody AjaxResult findPersonTaskHotMap(@PathVariable("id")Long personid) throws Exception{
		AjaxResult result = new AjaxResult();
		try {
			List<HotMap> data = null;
			data = taskService.findPersonHot(personid);
			result.setSuccessful(true);
			result.setData(data);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	/***
	 * 获取公司人员热力轨迹信息
	 * @param companyid
	 * @return
	 */
	@RequestMapping("findCompanyHot/{id}")
	public @ResponseBody AjaxResult findCompanyHot(@PathVariable("id")Long companyid) throws Exception{
		AjaxResult result = new AjaxResult();
		try {
			List<HotMap> data = null;
			data = taskService.findCompanyHot(companyid);
			result.setSuccessful(true);
			result.setData(data);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}

	/**
	 * 导出任务信息-生成excel
	 * @param dto
	 * @param request
	 */
	@RequestMapping("createTaskExcel")
	public @ResponseBody AjaxResult createApprovalsExcel(Task dto,HttpServletRequest request) throws Exception{
		AjaxResult result = new AjaxResult();
		try{
			User user = arsUtil.getCurrentUser();
			if(user != null) {
				Task data = taskService.findById(dto.getId());

				if(data != null) {
					Date now = new Date();
					String dirDate = DateUtil.systemDate.format(now);
					File dir = new File(downloadFolder + dirDate);
					if(!dir.exists()) {
						dir.mkdirs();
					}
					String templateName = downloadFolder + dirDate+"/" + (now.getTime() + "_任务.xls");
					File file = new File(templateName);
					taskService.exportTask(data, file);

					Datasync datasync = new Datasync();

					Datasync dbdatasync  = datasyncService.findByBid(dto.getId());
					//为空新增
					if(dbdatasync==null){
						//标识ID
						datasync.setBid(dto.getId());
						datasync.setOpdate(DateUtil.convertDateToString(new Date(),"yyyy-MM-dd HH:mm:ss"));
						//任务导出
						datasync.setOpfun("1");
						//状态未同步
						datasync.setState("1");
						datasync.setCreateTime(new Date());
						datasync.setUpdateTime(datasync.getCreateTime());
						//默认可用
						datasync.setActive(true);
						datasync.setUpdateBy(user.getUsername());
						datasyncService.saveOrUpdate(datasync);
					}


					//数据同步
					result.setData(templateName);
					result.setSuccessful(true);
				}else{
					result.setSuccessful(false);
				}
			}
		}catch(Exception e){
			throw e;
		}
		return result;
	}

	/**
	 * 导出任务信息
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("exportTask")
	public void exportApprovals(String templateName, HttpServletResponse response)throws Exception{
		User user = arsUtil.getCurrentUser();
		if(user != null) {
			File file = new File(templateName);
			if(file != null) {
				ServletOutputStream out = response.getOutputStream();
				String fileName = new String(file.getName().substring(file.getName().indexOf("_")+1).getBytes("UTF-8"),"iso-8859-1");
				response.addHeader("Content-Disposition","attachment;filename=" + fileName);
				InputStream is = new FileInputStream(file);
				int read = 0;
				byte[] buffer = new byte[8192];
				while ((read = is.read(buffer)) != -1) {
					out.write(buffer, 0, read);
				}
				is.close();
				out.flush();
				out.close();
			}
		}
	}

	/**
	 * 导入任务信息
	 */
	@RequestMapping("importTaskData")
	public @ResponseBody AjaxResult importApprovalData(MultipartFile file, HttpServletRequest request) throws Exception {
		AjaxResult result = new AjaxResult();
		try {
			Date now = new Date();
			String fileName = now.getTime() + "_" + file.getOriginalFilename();
			String dirDate = DateUtil.systemDate.format(now);
			File dir = new File(uploadFolder + dirDate);
			if(!dir.exists()) {
				dir.mkdirs();
			}
			String targetPath = uploadFolder + dirDate + "/" + fileName;
			File targetFile = new File(targetPath);
			logger.info("执行文件上传..." + targetFile);
			file.transferTo(targetFile);

			Map<String, Object> resultMap = taskService.importTask(targetFile);

			result.setData(resultMap);
			if(resultMap.get("faildFilePath") == null || StringUtil.isEmpty(resultMap.get("faildFilePath").toString())) {
				result.setMsg("导入成功");
			} else {
				result.setMsg("导入失败，请下载失败列表，修改后再上传.");//#1013
			}
			result.setSuccessful(true);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}


}
