package com.yeejoin.amos.patrol.business.controller;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.patrol.business.constants.XJConstant;
import com.yeejoin.amos.patrol.business.entity.mybatis.TaskBo;
import com.yeejoin.amos.patrol.business.entity.mybatis.TaskFeedbackBo;
import com.yeejoin.amos.patrol.business.param.FeedbackParam;
import com.yeejoin.amos.patrol.business.param.RoutePointParam;
import com.yeejoin.amos.patrol.business.param.TaskPageParam;
import com.yeejoin.amos.patrol.business.param.TaskParam;
import com.yeejoin.amos.patrol.business.param.TaskStatisticsParam;
import com.yeejoin.amos.patrol.business.service.intfc.IPointService;
import com.yeejoin.amos.patrol.business.service.intfc.ITaskService;
import com.yeejoin.amos.patrol.business.util.ClazzFieldUtil;
import com.yeejoin.amos.patrol.business.util.CommonResponse;
import com.yeejoin.amos.patrol.business.util.CommonResponseUtil;
import com.yeejoin.amos.patrol.business.util.DaoCriteria;
import com.yeejoin.amos.patrol.business.util.FileHelper;
import com.yeejoin.amos.patrol.business.util.TaskPageParamUtil;
import com.yeejoin.amos.patrol.business.vo.TaskStatisticsVo;
import com.yeejoin.amos.patrol.common.enums.TaskFeedbackType;
import com.yeejoin.amos.patrol.common.enums.TaskStatusEnum;
import com.yeejoin.amos.patrol.core.async.AsyncTask;
import com.yeejoin.amos.patrol.core.common.request.CommonPageable;
import com.yeejoin.amos.patrol.core.common.request.CommonRequest;
import com.yeejoin.amos.patrol.core.common.response.QueryCriteriaRespone;
import com.yeejoin.amos.patrol.core.util.DateUtil;
import com.yeejoin.amos.patrol.dao.entity.Task;
import com.yeejoin.amos.patrol.dao.entity.TaskFeedback;
import com.yeejoin.amos.patrol.dao.entity.TaskPicture;
import com.yeejoin.amos.patrol.feign.RemoteSecurityService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.domain.Page;
import org.springframework.scheduling.annotation.Async;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 任务
 * @author gaodongdong
 *
 */
@RestController
@RequestMapping(value = "/api/task")
@Api(tags="巡检任务")
public class TaskController extends AbstractBaseController{
	private final Logger log = LoggerFactory.getLogger(TaskController.class);
	/*@Autowired
	private OtherDeptService otherDeptService;*/
	@Autowired
	private ITaskService taskService;
	@Autowired
	private IPointService pointService;
	/*@Autowired
	private IUserService userService;*/
	@Autowired
	private AsyncTask asyncTask;
	@Autowired
    private RemoteSecurityService remoteSecurityService;
	/**
	 * 新增任务
	 * @param param
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "新增任务", notes = "新增任务")
	@RequestMapping(value = "/addTask", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	public CommonResponse addNewTask(@RequestBody TaskParam param) {
		AgencyUserModel user = getUserInfo();
		if (ObjectUtils.isEmpty(user)) {
			return CommonResponseUtil.failure("用户session过期");
		}
		try {
			Date date = new Date();
			if(date.getTime() > param.getTaskInfo().getFinishTime().getTime()){
				return CommonResponseUtil.failure("完成时间应当大于当前时间！" );
			}
			ReginParams reginParams = getSelectedOrgInfo();
            String orgCode = getOrgCode(reginParams);
			param.getTaskInfo().setOrgCode(orgCode);
//			param.getTaskInfo().setCreateDate(new Date());
			param.getTaskInfo().setPublisher(user.getUserId());
			param.getTaskInfo().setPublisherName(user.getRealName());
			param.getTaskInfo().setPublishTime(date);
			taskService.addNewTask(param);
			return CommonResponseUtil.success();
		} catch (Exception e) {
			return CommonResponseUtil.failure("新增任务失败: " + e.getMessage());
		}
	}

	/**
	 * 根据任务ID获取任务详情
	 * @param taskID
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "任务详情", notes = "任务详情")
	@RequestMapping(value = "/queryTask", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	public CommonResponse queryTaskDetail( @ApiParam(value="任务ID") @RequestParam(required = true) long taskID) {
		TaskBo bo = taskService.queryTaskDetail(taskID);
		try {
			//数据处理
			Map<String, Object> mapdate  =new HashMap<>();
			Map<String, Object> map  =new HashMap<>();
			Task   tak=bo.getTaskInfo();
			if(tak!=null){
				map= objectToMap1(tak);
			}


			mapdate.put("taskInfo", map);
			mapdate.put("taskDetails", bo.getTaskDetails());
			mapdate.put("feedback", bo.getFeedback());

			return CommonResponseUtil.success(mapdate);
		} catch (Exception e) {
			e.printStackTrace();
			return CommonResponseUtil.failure();
		}

	}



	 public static Map<String, Object> objectToMap1(Object obj) throws IllegalAccessException {
      	 Map<String, Object> map = new HashMap<String,Object>();
      	if(obj!=null){
          Class<?> clazz = obj.getClass();
          for (Field field : ClazzFieldUtil.getAllFields(obj)) {
              field.setAccessible(true);
              String fieldName = field.getName();
              Object value = nvl(field.get(obj));
              if("executorId".equals(fieldName)){
           	   map.put(fieldName, Long.valueOf(value.toString()));
              }else if("publisher".equals(fieldName)){
              	   map.put(fieldName, Long.valueOf(value.toString()));
                 }else{
           	   map.put(fieldName, value);
              }

          }
          return map;
      }
      return map;
      }

      public static Object nvl(Object param) {
          return param != null ? param : null;
      }

	/**
	 * 根据任务ID获取任务详情
	 * @param taskID
	 * @return
	 */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "任务详情", notes = "任务详情")
	@RequestMapping(value = "/printTask", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	public CommonResponse printTaskDetail( @ApiParam(value="任务ID") @RequestParam(required = true) long taskID) {
		TaskBo bo = taskService.queryTaskDetail(taskID);
		String xml = bean2xml(bo);
		InputStream inputStream = null;
		try {
			inputStream = new ByteArrayInputStream(xml.getBytes("UTF-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		Source source = new StreamSource(inputStream);
		 try {
			ClassPathResource classPathResource = new ClassPathResource("temp/template.xsl");
			InputStream stream = classPathResource.getInputStream();
	        Source template = new StreamSource(stream);
	        //String html = "D://10.html";
	        Date date = new Date();
	        String path = request.getSession().getServletContext().getRealPath("/");
	        String dir = path.substring(0, path.indexOf(File.separator)+1) + "print";
	        String html = path.substring(0, path.indexOf(File.separator)+1) + "print"+File.separator+"task_" + date.getTime() + ".html";
	        File dirFile = new File(dir);
	        if (!dirFile.exists()) {
	        	dirFile.mkdirs();
	        }

	        Result result=new StreamResult(html);
	        Transformer transformer  =TransformerFactory.newInstance().newTransformer(template);
			transformer.transform(source, result);

			File htmlFile = new File(html);
			FileInputStream fis = new FileInputStream(htmlFile);
			String data = IOUtils.toString(fis, "utf-8");
			fis.close();
			if (htmlFile.exists()) {
				htmlFile.delete();
			}
			return new CommonResponse("SUCCESS", data, "查询成功");
		 } catch (TransformerException | IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	private String bean2xml(TaskBo bo) {
		XStream xStream = new XStream(new DomDriver("UTF-8"));
		xStream.alias("taskInfo", TaskBo.class);
		xStream.alias("task", Task.class);
		xStream.alias("TaskFeedbacks", TaskFeedbackBo.class);
		//将对象转换成xml字符串
		String xml = xStream.toXML(bo);

		return xml;
	}


	/**
	 * 跟新任务
	 * @param param
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "更新任务", notes = "更新任务")
	@RequestMapping(value = "/updateTask", produces = "application/json;charset=UTF-8", method = RequestMethod.PUT)
	public CommonResponse updateTask(@ApiParam(value="修改任务信息") @RequestBody TaskParam param) {
		if (param.getTaskInfo().getId() <= 0) {
			return addNewTask(param);
		}
		try {
			taskService.updateTask(param);
			return CommonResponseUtil.success();
		} catch (Exception e) {
			return CommonResponseUtil.failure("更新任务失败: " + e.getMessage());
		}

	}

	/**
	 * 修改任务状态
	 * @param param
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "处理任务", notes = "处理任务")
	@RequestMapping(value = "/handleTask", produces = "application/json;charset=UTF-8", method = RequestMethod.PUT)
	public CommonResponse handleTask(@ApiParam(value = "任务ID", required = true) @RequestParam String taskIds,
									 @ApiParam(value = "任务状态", required = true) @RequestParam int status) {
		//LoginUserParam loginParam = getLoginUserParam();
		if (ObjectUtils.isEmpty(taskIds)) {
			return CommonResponseUtil.failure("处理人ID不能为空" );
		}
		try {
			AgencyUserModel user = getUserInfo();
            ReginParams reginParams = getSelectedOrgInfo();
            String orgCode = getOrgCode(reginParams);
			taskService.handleTask(taskIds, status, user, orgCode);
			return CommonResponseUtil.success();
		} catch (Exception e) {
			return CommonResponseUtil.failure("处理任务失败: " + e.getMessage());
		}

	}

	/**
	 * 删除任务
	 * @param taskID
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "删除任务", notes = "删除任务")
	@RequestMapping(value = "/delTask", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	public CommonResponse delTask(@ApiParam(value = "任务ID", required = true) @RequestParam long taskID) {
		try {
			taskService.delTask(taskID);
			return CommonResponseUtil.success();
		} catch (Exception e) {
			return CommonResponseUtil.failure("删除任务失败: " + e.getMessage());
		}

	}

	/**
	 * 删除任务
	 * @param taskID
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "删除任务", notes = "批量删除删除任务（任务id以半角英文字符分割。如： 1,2）")
	@RequestMapping(value = "/batchDelTask", produces = "application/json;charset=UTF-8", method = RequestMethod.DELETE)
	public CommonResponse batchDelTask(@ApiParam(value = "任务ID", required = true) @RequestParam String taskIDs) {
		try {
			taskService.batchDelTask(taskIDs);
			return CommonResponseUtil.success();
		} catch (Exception e) {
			return CommonResponseUtil.failure("删除任务失败: " + e.getMessage());
		}

	}

	/**
	 * 任务回复
	 * @param param
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "任务回复", notes = "任务回复")
	@RequestMapping(value = "/feedbackTask", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	public CommonResponse feedbackTask(@ApiParam(value = "回复信息（包含图片base64编码）") @RequestBody FeedbackParam param) {
		AgencyUserModel user = getUserInfo();
        ReginParams reginParams = getSelectedOrgInfo();
        String orgCode = getOrgCode(reginParams);
		if (ObjectUtils.isEmpty(user)) {
			return CommonResponseUtil.failure("用户session过期");
		}
		/*LoginUserParam loginParam = getLoginUserParam();*/
		TaskFeedback taskFeedback = new TaskFeedback();
		taskFeedback.setUserId(user.getUserId());
		taskFeedback.setUserName(user.getUserName());
		taskFeedback.setTaskId(param.getTaskID());
		taskFeedback.setPictureNumber(param.getPictureNumber());
		taskFeedback.setMessage(param.getMessage());
		taskFeedback.setCreateDate(new Date());
		taskFeedback.setFeedbackTime(new Date());
		taskFeedback.setOrgCode(orgCode);
		taskFeedback.setMessageType(TaskFeedbackType.FEEDBACK.getName());
		List<TaskPicture> pictures = new ArrayList<>();

		try {
			if (!ObjectUtils.isEmpty(param.getImgbase64()) ) {
				for (int i = 0; i < param.getImgbase64().size(); i++) {
					TaskPicture picture = new TaskPicture();
		            picture.setTaskId(param.getTaskID());
		            picture.setCreateDate(new Date());
		            picture.setOrgCode(orgCode);
		            picture.setPhotoData(param.getImgbase64().get(i));
		            pictures.add(picture);
				}
			}
			Task task = taskService.feedbackTask(taskFeedback, pictures);
			if(task != null && task.getStatus() == TaskStatusEnum.FINISHED.getValue()){
				//asyncTask.pushTaskDetailInfoTo3D(task.getId());
				pushTaskDetailInfoTo3D(getToken(), getProduct(), getAppKey(),task.getId());
			}
			return CommonResponseUtil.success();
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return CommonResponseUtil.failure("任务回复失败: " + e.getMessage());
		}

	}

	 @Async
	    public void pushTaskDetailInfoTo3D(String toke,String product,String appKey,Long ids ){

	    	 try {
				asyncTask.pushTaskDetailInfoTo3D( toke, product, appKey,ids);

			} catch (InterruptedException e) {
				e.printStackTrace();
			}

	    }
	/**
	 * 任务转发
	 * @param userId
	 * @param taskID
	 * @return
	 */
	 @TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "任务转发", notes = "任务转发")
	@RequestMapping(value = "/forwardTask", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	public CommonResponse forwardTask(@RequestParam(required = true) String userId, @RequestParam(required = true) long taskID) {
		AgencyUserModel user = getUserInfo();
		if (ObjectUtils.isEmpty(user)) {
			return CommonResponseUtil.failure("用户session过期");
		}
		try {
			taskService.forwardTask(getToken(),getProduct(),getAppKey(),taskID, user, userId);
			return CommonResponseUtil.success();
		} catch (Exception e) {
			e.printStackTrace();
			return CommonResponseUtil.failure("任务转发失败: " + e.getMessage());
		}

	}
	/**
	 * 分页查询任务列表
	 * @param queryRequests
	 * @param pageable
	 * @return
	 */
	 @TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "分页查询任务", notes = "人也查询任务")
	@RequestMapping(value = "/queryTaskByPage", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	public CommonResponse queryTaskByPage(
			@ApiParam(value = "组合查询条件", required = false, defaultValue = "[]") @RequestBody(required = false) List<CommonRequest> queryRequests,
			@ApiParam(value = "分页参数", required = false, defaultValue = "current=0&pageSize=10或pageNumber0&pageSize=10") CommonPageable pageable) {
		try {
            ReginParams reginParams = getSelectedOrgInfo();
            String orgCode = getOrgCode(reginParams);
            String roleTypeName = getRoleTypeName(reginParams);
            String deptId ="";
			String userId ="";
            HashMap<String, Object> paramMap = buildMybatisCriterias(orgCode, roleTypeName);

			if(XJConstant.ROLE_NAME_DEPTADMIN.equals(roleTypeName)){
				deptId =getDepartmentId(reginParams);
			}else if(XJConstant.ROLE_NAME_PERSON.equals(roleTypeName)){
				userId=getUserId();
			}
			if(deptId!=null&&!("").equals(deptId.trim()))
				paramMap.put("deptId",deptId);
			if(userId!=null&&!("").equals(userId.trim()))
				paramMap.put("userId",userId);
			TaskPageParam param = TaskPageParamUtil.fillTaskInfo(queryRequests, pageable, paramMap);
			Page<HashMap<String,Object>> tasks  = taskService.queryTaskByPage(getToken(),getProduct(),getAppKey(),param);
			return CommonResponseUtil.success(tasks);
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			return CommonResponseUtil.failure(e.getMessage());
		}

	}

	/**
	 * 条件查询所有任务
	 * @param queryRequests
	 * @return
	 */
	 @TycloudOperation(ApiLevel = UserType.AGENCY)
	@PostMapping(value = "/queryTaskByCondition",produces = "application/json;charset=UTF-8")
	@ApiOperation(value = "条件查询任务", notes = "条件查询任务")
	public CommonResponse queryTaskByCondition(
	            @ApiParam(value = "组合查询条件", required = false, defaultValue = "[]") @RequestBody(required = false) List<CommonRequest> queryRequests) {
		if (queryRequests == null) {
			queryRequests = new ArrayList<>();
		}
		 ReginParams reginParams = getSelectedOrgInfo();
	        String orgCode = getOrgCode(reginParams);
	        String roleTypeName = getRoleTypeName(reginParams);
	        List<DaoCriteria> criterias = buildDaoCriterias(queryRequests, true, orgCode, roleTypeName);
		List<Task> list = taskService.queryTaskByCondition(criterias);
		return CommonResponseUtil.success(list);
	}

	/**
	 * 条件查询任务个数
	 * @param queryRequests
	 * @return
	 */
	 @TycloudOperation(ApiLevel = UserType.AGENCY)
	@PostMapping(value = "/queryTaskCountByCondition",produces = "application/json;charset=UTF-8")
	@ApiOperation(value = "条件查询任务个数", notes = "条件查询任务个数")
	public CommonResponse queryTaskCountByCondition(
	            @ApiParam(value = "组合查询条件", required = false, defaultValue = "[]") @RequestBody(required = false) List<CommonRequest> queryRequests) {
		if (queryRequests == null) {
			queryRequests = new ArrayList<>();
		}
		 ReginParams reginParams = getSelectedOrgInfo();
	        String orgCode = getOrgCode(reginParams);
	        String roleTypeName = getRoleTypeName(reginParams);
	        List<DaoCriteria> criterias = buildDaoCriterias(queryRequests, true, orgCode, roleTypeName);
		int count = taskService.queryTaskCountByCondition(criterias);
		return CommonResponseUtil.success(count);
	}

	 @TycloudOperation(ApiLevel = UserType.AGENCY)
	@PostMapping(value = "/queryTaskCharts",produces = "application/json;charset=UTF-8")
	@ApiOperation(value = "条件查询任务图表数据(<font color='blue'>手机app</font>)", notes = "条件查询任务图表数据(<font color='blue'>手机app</font>)")
	public CommonResponse queryTaskCharts(@ApiParam(value = "组合查询条件", required = false, defaultValue = "[]") @RequestBody(required = false) List<CommonRequest> queryRequests) {
		  ReginParams reginParams = getSelectedOrgInfo();
	        String orgCode = getOrgCode(reginParams);
	        String roleTypeName = getRoleTypeName(reginParams);
	        String departmentId = getDepartmentId(reginParams);
		if (queryRequests == null) {
			queryRequests = new ArrayList<>();
		}
		HashMap<String, Object> request = TaskPageParamUtil.fillTaskInfo(queryRequests);
		//添加机构限制
		request.put("orgCode", orgCode);

		if(!ObjectUtils.isEmpty(request.get("executorId"))){
			request.put("executorId", getUserId());
		}else if(!ObjectUtils.isEmpty(request.get("publisher"))){
			request.put("publisher", getUserId());
		}else{
			 if (XJConstant.ROLE_NAME_ADMIN.equals(roleTypeName.toUpperCase()) ||
	                    XJConstant.ROLE_NAME_SUPERADMIN.equals(roleTypeName.toUpperCase())) {
	                request.put("orgCode", orgCode);
	            } else if (XJConstant.ROLE_NAME_DEPTADMIN.equals(roleTypeName.toUpperCase())) {
	                request.put("orgCode", orgCode);
	                request.put("departmentId", departmentId);
	            } else {
	                request.put("executorId", getUserId());
	                request.put("publisher", getUserId());
	            }
		}
//		String departmentId = request.get("department") != null ? request.get("department").toString() : null ;
//		if(!(ObjectUtils.isEmpty(request.get("departmentId"))) && Integer.valueOf(request.get("departmentId").toString()) > 0){
//			request.put("orgCode", request.get("orgCode") + "-" + departmentId);
//		}
		/*if (!(ObjectUtils.isEmpty(request.get("departmentId"))) && request.get("departmentId").toString().equals("-1")) {
			List<LinkedHashMap<String, Object>> userList = otherDeptService.queryDeptUsers("-1",
					orgCode);
			List ids = new ArrayList<Long>();
			for (LinkedHashMap<String, Object> linkedHashMap : userList) {
				ids.add(linkedHashMap.get("id"));
			}
			request.put("ids", ids);
		}*/

		Map charts = taskService.queryTaskCharts(request);
		return CommonResponseUtil.success(charts);
	}

	 @TycloudOperation(ApiLevel = UserType.AGENCY)
	@PostMapping(value = "/queryTasksByPage",produces = "application/json;charset=UTF-8")
	@ApiOperation(value = "条件查询任务数据(<font color='blue'>手机app</font>)", notes = "条件查询任务数据(<font color='blue'>手机app</font>)")
	public CommonResponse queryTasksByPage(@ApiParam(value = "组合查询条件", required = false, defaultValue = "[]") @RequestBody(required = false) List<CommonRequest> queryRequests,
				@ApiParam(value = "分页参数", required = false, defaultValue = "current=0&pageSize=10或pageNumber0&pageSize=10") CommonPageable pageable) {
		 ReginParams reginParams = getSelectedOrgInfo();
	        String orgCode = getOrgCode(reginParams);
	        String roleTypeName = getRoleTypeName(reginParams);
	        String departmentId = getDepartmentId(reginParams);
		if (queryRequests == null) {
			queryRequests = new ArrayList<>();
		}
		HashMap<String, Object> request = TaskPageParamUtil.fillTaskInfo(queryRequests);
		if(!ObjectUtils.isEmpty(request.get("executorId"))){
			request.put("orgCode", orgCode);
			request.put("executorId", getUserId());
		}else if(!ObjectUtils.isEmpty(request.get("publisher"))){
			request.put("orgCode", orgCode);
			request.put("publisher", getUserId());
		}else{
			 if (XJConstant.ROLE_NAME_ADMIN.equals(roleTypeName.toUpperCase()) ||
	                    XJConstant.ROLE_NAME_SUPERADMIN.equals(roleTypeName.toUpperCase())) {
	                request.put("orgCode", orgCode);
	            } else if (XJConstant.ROLE_NAME_DEPTADMIN.equals(roleTypeName.toUpperCase())) {
	                request.put("orgCode", orgCode);
	                request.put("departmentId", departmentId);
	            } else {
	                request.put("executorId", getUserId());
	                request.put("publisher", getUserId());
	            }
		}
		request.put("pageSize", pageable.getPageSize());
		request.put("pageNumber", pageable.getPageNumber());
		/*if (!(ObjectUtils.isEmpty(request.get("departmentId"))) && request.get("departmentId").toString().equals("-1")) {
			List ids = getDepartmentUserIds("-1", loginOrgCode);
			request.put("ids", ids);
		}*/
		List<Map> charts = taskService.queryTasks(request);
		return CommonResponseUtil.success(charts);
	}

	/*private List getDepartmentUserIds(String departmentId, String orgCode) {
		List<LinkedHashMap<String, Object>> userList = otherDeptService.queryDeptUsers(departmentId,
				orgCode);
		List ids = new ArrayList<Long>();
		for (LinkedHashMap<String, Object> linkedHashMap : userList) {
			ids.add(linkedHashMap.get("id"));
		}
		return ids;
	}*/


	/**
	 * 	获取任务列表查询接口
	 * @return
	 */
	 @TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "获取任务列表查询接口(<font color='blue'>release</font>)", notes = "获取任务列表查询接口")
	@RequestMapping(value = "/queryCriteria/init", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public CommonResponse getQueryCriteriaInit(){
		ReginParams reginParams = getSelectedOrgInfo();
        String orgCode = getOrgCode(reginParams);
        String roleTypeName = getRoleTypeName(reginParams);
		if (ObjectUtils.isEmpty(reginParams)) {
			return CommonResponseUtil.failure("用户session过期");
		}
        try {
    		QueryCriteriaRespone respone = new QueryCriteriaRespone();

    		respone.setStatus(TaskStatusEnum.getEnumList());
            List<AgencyUserModel> users = remoteSecurityService.listUserByOrgCode(getToken(),getProduct(),getAppKey(),orgCode);

    		 if (XJConstant.ROLE_NAME_ADMIN.equals(roleTypeName.toUpperCase()) ||
                     XJConstant.ROLE_NAME_SUPERADMIN.equals(roleTypeName.toUpperCase())) {
                 respone.setPoints(pointService.queryPointList(null, null, orgCode));
                 respone.setUsers(objectsToMaps(users));
             } else if (XJConstant.ROLE_NAME_DEPTADMIN.equals(roleTypeName.toUpperCase())) {
                 respone.setPoints(pointService.queryPointList(null, null, orgCode));
                 respone.setUsers(objectsToMaps(users));
             } else {
                 respone.setPoints(pointService.queryPointList(null, null, orgCode));
                 respone.setUsers(objectsToMaps(users));
             }

			return CommonResponseUtil.success(respone);
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage(),e);
			return CommonResponseUtil.failure();
		}
    }

	/**
	 * 隐患治理统计
	 * @param dateMonth
	 * @return
	 */
	 @TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "隐患治理统计", notes = "隐患治理统计")
	@RequestMapping(value = "/hiddenDanger/count/{dateMonth}", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	public CommonResponse hiddenDangerCountByDate(@ApiParam(value = "年月日(yyyyMMdd)8位", required = true) @PathVariable String dateMonth) {
		HashMap<String,Object> params = new HashMap<String,Object>();
		 ReginParams reginParams = getSelectedOrgInfo();
	        String orgCode = getOrgCode(reginParams);
	        String roleTypeName = getRoleTypeName(reginParams);
	        if (XJConstant.ROLE_NAME_ADMIN.equals(roleTypeName.toUpperCase()) ||
	                XJConstant.ROLE_NAME_SUPERADMIN.equals(roleTypeName.toUpperCase())) {
	            params.put("orgCode", orgCode);
	        } else {
	            params.put("orgCode", orgCode);
	        }


		params.put("startMonth", DateUtil.getFirstDayOfYear(dateMonth,"yyyyMM"));//本年开始日期
		params.put("curMonth", dateMonth.substring(0,6));//当前年月
		params.put("monthStartDate", DateUtil.getStartMonthDate(dateMonth,"yyyyMMdd"));//本月开始日期
		params.put("monthEndDate", dateMonth);//当前日期
		params.put("timeOutStatus", XJConstant.TASK_STATUS_TIMEOUT);
		params.put("cancelStatus", XJConstant.TASK_STATUS_FINISH);
		params.put("finishStatus", XJConstant.TASK_STATUS_DEAL);
		params.put("dealStatus", XJConstant.TASK_STATUS_NO_START);
		HashMap<String, List<HashMap<String, Object>>>  countList = taskService.getHiddenDangerCountData(params);
		return CommonResponseUtil.success(countList);
	}

	/**
	 * 根据巡检路线ID获取该路线上的所有点ID
	 * @return IDs
	 */
	 @TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "获取巡检路线上的所有点ID", notes = "获取巡检路线上的所有点ID")
	@RequestMapping(value = "/points", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	public CommonResponse getPointIDsByRouteID(@ApiParam(value = "巡检路线IDs") @RequestBody(required = true) RoutePointParam param) {
		List<String> routeIDs = param.getRouteIDs();
		List<HashMap<String, Object>> routeIDsAndPointIDs = taskService.getPointIDsByRouteIDs(routeIDs);
		Map<String, Object> result = new HashMap<String, Object>();
		for (HashMap<String, Object> item:routeIDsAndPointIDs) {
			String[] pointIDs = item.get("PointID").toString().split(",");
			result.put(item.get("RouteID").toString(), pointIDs);
		}
		return CommonResponseUtil.success(result);
	}

	 @TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/queryTaskStatistics",produces = "application/json;charset=UTF-8")
	@ApiOperation(value = "查询用户任务统计(<font color='blue'>手机app</font>)", notes = "查询用户任务统计(<font color='blue'>手机app</font>)")
	public CommonResponse getUserTaskStatistics() {
		HashMap<String,Object> params = new HashMap<String,Object>();		HashMap<String,Object> resp = new HashMap<String,Object>();
		 AgencyUserModel user = getUserInfo();
	        ReginParams reginParams = getSelectedOrgInfo();
	        String orgCode = getOrgCode(reginParams);
	        String roleTypeName = getRoleTypeName(reginParams);
	        String departmentId = getDepartmentId(reginParams);
		params.put("orgCode",orgCode);
		params.put("userId", getUserId());
		Map<String, Object> userResp = taskService.getTaskForAppPie(params);
		resp.put("user",userResp);
		params.put("userId", null);
		if (XJConstant.ROLE_NAME_PERSON.equals(roleTypeName.toUpperCase())){
			return CommonResponseUtil.success(resp);
		}
		if (!ObjectUtils.isEmpty( reginParams.getDepartment())) {
			params.put("departmentId",departmentId);
			Map<String, Object> deptResp = taskService.getTaskForAppPie(params);
			resp.put("department",deptResp);
			params.put("departmentId", null);
		}

		if (XJConstant.ROLE_NAME_DEPTADMIN.equals(roleTypeName)) {
			return CommonResponseUtil.success(resp);
		}

		Map<String, Object> orgResp = taskService.getTaskForAppPie(params);
		resp.put("company",orgResp);

		return CommonResponseUtil.success(resp);
	}

	 @TycloudOperation(ApiLevel = UserType.AGENCY)
	@PostMapping(value = "/getStatisticsData",produces = "application/json;charset=UTF-8")
	@ApiOperation(value = "查询任务统计", notes = "查询任务统计")
	public CommonResponse getTaskStatistics(@RequestBody(required=true) TaskStatisticsParam param) {
		 ReginParams reginParams = getSelectedOrgInfo();
	        String orgCode = getOrgCode(reginParams);
		param.setOrgCode(orgCode);
		List<TaskStatisticsVo> list = taskService.getTaskStatistics(param);
	      if (list!=null&&list.size()>0){

	            //安全处里
	            if(4==param.getStatisticsTyle()){
	            	//获取部门名称
	                String userIds="";
	                Set<String> set = new HashSet<>();
	                list.forEach(s -> {
		                     set.add(s.getName());
	                });

	                List<String> list1 = new ArrayList<>(set);
	                userIds = String.join(",", list1);
	                List<LinkedHashMap> listd=remoteSecurityService.listDepartmentByDeptIds( getToken(),getProduct(),getAppKey(),userIds);

	                //新安全
	                list.forEach(s -> {
	                	if(  listd != null && listd.size() > 0) {
	                		List<LinkedHashMap> filterDep = listd.stream().filter(d -> d.get("sequenceNbr").toString().equals(s.getName())).collect(Collectors.toList());

	            			if(filterDep != null && filterDep.size() > 0){
	            				LinkedHashMap dep = filterDep.get(0);
	                            s.setName(dep.get("departmentName").toString());
	                        }
	                	}

	                	    });
	            }


	            }

		TaskStatisticsVo vo = new TaskStatisticsVo();
		vo.setName("合计");
		for (TaskStatisticsVo item: list) {
			vo.setCancel(item.getCancel() + vo.getCancel());
			vo.setFinished(vo.getFinished() + item.getFinished());
			vo.setProccesed(vo.getProccesed() + item.getProccesed());
			vo.setTimeout(vo.getTimeout() + item.getTimeout());
			vo.setTotal(vo.getTotal() + item.getTotal());
		}
		list.add(vo);
		return CommonResponseUtil.success(list);
	}

	 @TycloudOperation(ApiLevel = UserType.AGENCY)
	@PostMapping(value = "/exportStatisticsData",produces = "application/vnd.ms-excel;charset=UTF-8")
	@ApiOperation(value = "查询任务统计", notes = "查询任务统计")
	public void exportStatisticsData(@RequestBody(required=true) TaskStatisticsParam param, HttpServletResponse response) {
		   ReginParams reginParams = getSelectedOrgInfo();
	        String orgCode = getOrgCode(reginParams);
		param.setOrgCode(orgCode);
		List<TaskStatisticsVo> list = taskService.getTaskStatistics(param);
		 if (list!=null&&list.size()>0){
	            //安全处里
	            if(1==param.getStatisticsTyle()||0==param.getStatisticsTyle()){
	             //处理用户信息
	             String userIds="";
	             Set<String> set = new HashSet<>();
	             list.forEach(s -> {
	            	if(!ObjectUtils.isEmpty(s)){
	            		set.add(s.getName());
	            	}
	             });

	                List<String> list1 = new ArrayList<>(set);
	                userIds = String.join(",", list1);

	                List<AgencyUserModel> listd=remoteSecurityService.listUserByUserIds(getToken(),getProduct(),getAppKey(), userIds);
	                //新安全
	                list.forEach(s -> {
	                listd.forEach(s1 -> {
	                  if(s.getName().equals(s1.getUserId())){
	                	   s.setName(s1.getRealName());
	                  }
	                });
                  });
	            }
			 //安全处里
			 if(4==param.getStatisticsTyle()){
				 //获取部门名称
				 String userIds="";
				 Set<String> set = new HashSet<>();
				 list.forEach(s -> {
					 set.add(s.getName());
				 });

				 List<String> list1 = new ArrayList<>(set);
				 userIds = String.join(",", list1);
				 List<LinkedHashMap> listd=remoteSecurityService.listDepartmentByDeptIds( getToken(),getProduct(),getAppKey(),userIds);

				 //新安全
				 list.forEach(s -> {
					 if(  listd != null && listd.size() > 0) {
						 List<LinkedHashMap> filterDep = listd.stream().filter(d -> d.get("sequenceNbr").toString().equals(s.getName())).collect(Collectors.toList());

						 if(filterDep != null && filterDep.size() > 0){
							 LinkedHashMap dep = filterDep.get(0);
							 s.setName(dep.get("departmentName").toString());
						 }
					 }

				 });
			 }
		 }

		TaskStatisticsVo vo = new TaskStatisticsVo();
		vo.setName("合计");
		for (TaskStatisticsVo item: list) {
			vo.setCancel(item.getCancel() + vo.getCancel());
			vo.setFinished(vo.getFinished() + item.getFinished());
			vo.setProccesed(vo.getProccesed() + item.getProccesed());
			vo.setTimeout(vo.getTimeout() + item.getTimeout());
			vo.setTotal(vo.getTotal() + item.getTotal());
		}
		list.add(vo);
		String fileName = "任务统计" + new Date().getTime();
		FileHelper.exportExcel(list, "任务统计","任务统计",TaskStatisticsVo.class, fileName+".xls", response);
	}

	 @TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "根据任务id查询任务日志", notes = "根据任务id查询任务日志")
	@RequestMapping(value = "/queryTaskRecordByTaskId", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	public CommonResponse queryTaskRecordByTaskId(@ApiParam(value="任务ID") @RequestParam(required = true)  long taskId) {
	  try {
			List<Map<String, Object>> listf = new ArrayList<>();
			List<TaskFeedback> feedbacks = taskService.queryTaskRecord(taskId);
			if (feedbacks != null && feedbacks.size() > 0) {
				for (TaskFeedback feedback : feedbacks) {
					listf.add(objectToMap2(feedback));
				}
			}
		return CommonResponseUtil.success(listf);
	  } catch (Exception e) {
		  log.error(e.getMessage(),e);
		  return CommonResponseUtil.failure("获取处理信息列表失败");
	  }
	}

	 @TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "GET", value = "查询检查项任务所有检查不合格项详情(<font color='blue'>手机app</font>)", notes = "查询检查项任务所有检查不合格项详情")
	@RequestMapping(value = "/queryCheckTaskDetail", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	public CommonResponse queryCheckTaskDetail(@RequestParam(required = true) long checkId,  @RequestParam(required = true) long taskId) {
		Map<String, Object> resp = taskService.queryCheckTaskDetail(checkId, taskId);
		return CommonResponseUtil.success(resp);
	}


	/**
	 * 同步离线任务
	 * @return
	 */
	 @TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "同步离线任务(<font color='blue'>手机app</font>)", notes = "同步离线任务")
	@RequestMapping(value = "/queryOfflineTasks", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	public CommonResponse synchronizedOfflineTasks() {		 	AgencyUserModel user = getUserInfo();
		 ReginParams reginParams = getSelectedOrgInfo();
		List<Map<String, Object>> resp = taskService.synchronizedOfflineTasks(user,reginParams);
		return CommonResponseUtil.success(resp);
	}

	public static Map<String, Object> objectToMap2(Object obj) throws IllegalAccessException{
		Map<String, Object> map = new HashMap<String,Object>();
		if(obj!=null){
			for (Field field : ClazzFieldUtil.getAllFields(obj)) {
				field.setAccessible(true);
				String fieldName = field.getName();
				Object value = nvl(field.get(obj));
				if("userId".equals(fieldName)){
					map.put(fieldName, Long.valueOf(value.toString()));
				}else if("createDate".equals(fieldName)){
					map.put(fieldName, value.toString());
				}else{
					map.put(fieldName, value);
				}

			}
			return map;
		}
	    return map;
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@ApiOperation(value = "图片上传按月分文件夹")
	@PostMapping(value = "/imageUpload")
	public ResponseModel<Object> uploadTaskFiles (@RequestBody MultipartFile file) {
		if (ValidationUtil.isEmpty(file)){
			throw new BadRequest("参数校验失败.");
		}
		Map fileMap = taskService.uploadFile(file);
		return ResponseHelper.buildResponse(fileMap);
	}


}
