package com.scpyun.platform.jilinsscgsdp.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.scpyun.base.core.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.scpyun.base.bean.Page;
import com.scpyun.base.core.annotation.Api;
import com.scpyun.base.core.annotation.ApiOperation;
import com.scpyun.base.core.exception.CustomException;
import com.scpyun.base.db.service.CommonService;
import com.scpyun.base.utils.DateUtils;
import com.scpyun.base.utils.UUID;
import com.scpyun.platform.jilinsscgsdp.constant.Constant;
import com.scpyun.platform.jilinsscgsdp.enums.PatrolStatusEnum;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

@Api("网格巡查")
@Service("patrolService")
public class AppPatrolServiceImpl {

	/**
	 *  Junit API
	 *  TODO 测后删
	 * @param map
	 * @return
	 */
	@ApiOperation(value="巡查统计", nologin = true)
	public Map<String, Object> aaaa(Map<String, Object> map){
		System.err.println(JedisUtils.set("a", "a", 0));
		System.err.println(JedisUtils.get("a"));
		return new HashMap<>();
	}
	
	private static final String DATE_TIME_PATTEN="yyyy-MM-dd HH:mm:ss";

	public static final String PATROL_KEY = Constant.SYS_NAME+":patrol:lock";
	
	/**
	 * 巡查轨迹缓存数据
	 */
	public static String PATROL_TRAJECTORY_CACHE_PREFIX=Constant.SYS_NAME+":patrol:trajectory:";
	
	/**
	 * 巡查当前点缓存数据
	 */
	public static String PATROL_CURRENT_CACHE_PREFIX=Constant.SYS_NAME+"patrol:current_info:";
	
	@Autowired
	private CommonService commonService;

	
	@Deprecated
	@ApiOperation(value="巡查统计",desc="",nologin=false)
	public Map<String, Object> getPatrolStatistics(Map<String, Object> map){
		if(!map.containsKey("card_no")) {
			throw new CustomException("缺少必要参数card_no");
		}
		Map<String, Object> NumMap = new HashMap<String, Object>();
		NumMap = commonService.getObject(Constant.NAMESPACE_PATROL + "getPatrolRecordNum", map);
		Map<String, Object> EventNum = commonService.getObject(Constant.NAMESPACE_PATROL + "getEventNum", map);
		BigDecimal time = (BigDecimal) EventNum.get("consumption_times");
		BigDecimal report_num = new BigDecimal(EventNum.get("report_num")+"");
		BigDecimal avg_time = new BigDecimal("0");
		if (!new BigDecimal("0").equals(time)) {
			BigDecimal bigInteger = new BigDecimal((60*60)+"");
			avg_time = time.divide(report_num,BigDecimal.ROUND_HALF_UP).divide(bigInteger,BigDecimal.ROUND_HALF_UP);
		}

		NumMap.put("report_num", report_num);
		NumMap.put("avg_time", avg_time);
		return NumMap;
	}
	
	
	@ApiOperation(value = "查询定时巡查时间",desc = "查询定时巡查时间",nologin = false)
	public List dsPatrolTimeList(Map<String,Object> params){
		if(!params.containsKey("card_no")) {
			throw new CustomException("缺少必要参数card_no");
		}
		if(!params.containsKey("garden_id")) {
			throw new CustomException("缺少必要参数garden_id");
		}
		return commonService.findList(Constant.NAMESPACE_PATROL+"dsPatrolTimeList",params);
	}
	
	@ApiOperation(value="网格巡查",desc="开始巡查时网格信息载入",nologin=false)
	public Map<String, Object> getPatrol(Map<String, Object> map){
		if(!map.containsKey("card_no")) {
			throw new CustomException("缺少必要参数card_no");
		}
		if(!map.containsKey("grid_type")) {
			throw new CustomException("缺少必要参数grid_type");
		}
		Map<String, Object> patrol = new HashMap<String, Object>();
		patrol = commonService.getObject(Constant.NAMESPACE_PATROL + "getGridInfo", map);
		List<Map<String, Object>> grid_list = new ArrayList<>();
		if(StringUtils.isNotEmpty(map.get("record_id"))) {
			//查询历史巡查项
			grid_list=commonService.findList(Constant.NAMESPACE_PATROL + "selectGridListByRecord", map);
		}else {
			//查询专职巡查项
			grid_list = commonService.findList(Constant.NAMESPACE_PATROL + "selectGridList", map);
		}
        if(StringUtils.isNotEmpty(patrol)) {
        	for(Map<String, Object> grid_map: grid_list) {
        		if(StringUtils.isNotEmpty(grid_map.get("csc_mapjson"))&&grid_map.get("csc_mapjson").toString().contains(",")) {
        			String[] a=grid_map.get("csc_mapjson").toString().split(",");
        			if(a.length==2) {
        				grid_map.put("csc_mapjson", a[1]+","+a[0]);
        			}
        		}
        	}
        	patrol.put("grid_list", grid_list);
		}
		return patrol;
	}
	
	@ApiOperation(value = "更新巡查状态", desc = "", nologin = false)
	public Map<String, Object> updatePatrolStatus(Map<String, Object> map) {
		Map<String, Object> result = new HashMap<String, Object>();
		if (map.containsKey("garden_id") && StringUtils.isNotEmpty(map.get("garden_id"))) {
			String garden_id = map.get("garden_id").toString();
			String cardNo = map.get("card_no").toString();
			String patrol_time_id = map.get("id").toString();

			String mapKey = garden_id + "_" + cardNo + "_" + patrol_time_id;
			String endTime = JedisImplUtils.hget(PATROL_KEY, mapKey);
			if (StringUtils.isEmpty(endTime)) {
				JedisImplUtils.hset(PATROL_KEY, mapKey, String.valueOf(DateUtil.endOfDay(new Date()).getTime()));
			} else if (Long.valueOf(endTime) >= System.currentTimeMillis()){
				throw new CustomException("当前时间段已巡查过，不能重复巡查");
			} else {
				JedisImplUtils.hset(PATROL_KEY, mapKey, String.valueOf(DateUtil.endOfDay(new Date()).getTime()));
			}

			if (PatrolStatusEnum.working.getVal().equals(map.get("patrol_status").toString())) {
				Map<String,Object> mapQuery=new HashMap<String, Object>();
				mapQuery.put("garden_id", garden_id);
				mapQuery.put("del_flag", "0");
				List<Map<String, Object>> substanceList = new ArrayList<>();
				//查询网格信息
				String gridName = null;
				Map<String, Object> query = new HashMap<>();
				query.put("id", garden_id);
				String patrol_type = null;
				patrol_type = "网格巡查";
				//基础网格员
				Map<String, Object> gardenMap = commonService.getObject(Constant.NAMESPACE_PATROL + "getGardenData", query);
				if (gardenMap != null) {
					gridName = MapUtil.getStr(gardenMap, "name");
				}
				substanceList = commonService.findList(Constant.NAMESPACE_PATROL + "selectSubstanceByGardenId", mapQuery);

				String id = UUID.getUUID();
				map.put("uuid", id);
				map.put("patrol_region", gridName);
				map.put("patrol_type", patrol_type);
				map.put("nowDate", new Date());
				map.put("create_time_str", DateUtil.format(new Date(), "yyyyMMdd"));
				map.put("patrol_time_id", map.get("id"));
				map.put("city_id", gardenMap.get("city_id"));
				map.put("area_id", gardenMap.get("area_id"));
				map.put("street_id", gardenMap.get("street_id"));
				map.put("community_id", gardenMap.get("community_id"));
				map.put("garden_id", garden_id);
				map.put("item_count", substanceList.size());
				map.put("garden_user_id", map.get("gardenUserId"));
				result.put("id", id);
				commonService.insert(Constant.NAMESPACE_PATROL + "insertPatrolRecord", map);

				try {
					//插入巡查项
					if (!substanceList.isEmpty()) {
						for (Map<String, Object> mm : substanceList) {
							mm.put("is_checked", "0");
							mm.put("record_id", id);
						}
						commonService.insertBatch(Constant.NAMESPACE_PATROL + "insertPatrolItems", substanceList);
					}
				} catch (Exception e) {
					UnifyLogger.parent(UnifyLogger.getTrace(e),UnifyLogger.Level.INFO);
				}
			}

		}
		return result;
	}
	
	//TODO
	@ApiOperation(value="坐标抖动接口",desc="",nologin=false)
	public static Object CoordTransForward(Map<String, Object> param) {
		if(!param.containsKey("bl")) {
			throw new CustomException("缺少必要参数bl");
		}
		param.put("coordinate", param.get("bl"));
		String result = null;;
		try {
			long post_before = System.currentTimeMillis();
//			result = HttpRequest.post("http://61.161.147.38:11180/ZFJservice/CoorTransService.asmx/CoordTransForward2").timeout(2000).form(param).execute().body();
			result = HttpRequest.post("http://124.95.178.244:6677/coordinateTransform/net/EncryptionTransformtodadi").timeout(2000).form(param).execute().body();
			long post_return = System.currentTimeMillis();
			UnifyLogger.parent("请求时间间隔，CoordTransForward:"+String.valueOf(post_return-post_before),UnifyLogger.Level.INFO);
		} catch (Exception e) {
			UnifyLogger.parent("请求时间间隔，CoordTransForward:"+"超过2000",UnifyLogger.Level.INFO);
			throw new CustomException("打点服务调用超时", e);
		}
		return result;
	}
	
	/**
	 * 	移除非必要属性
	 * @param map
	 */
	private void removeUnusedProperties(Map<String, Object> map) {
		map.remove("_user");
		map.remove("card_no");
		map.remove("cardNO");
		map.remove("cardNo");
	}
	
	@ApiOperation(value="往redis上存打点数据",desc="",nologin=false)
	public String insertLocationData(Map<String, Object> map){
		if(!map.containsKey("record_id")) {
			throw new CustomException("缺少必要参数record_id");
		}
		removeUnusedProperties(map);
		try {
			List<Map<String, Object>> point_list = new ArrayList<Map<String,Object>>();
			if(JedisUtils.exists(PATROL_TRAJECTORY_CACHE_PREFIX+map.get("record_id"))) {
				String jsonStr = JedisUtils.get(PATROL_TRAJECTORY_CACHE_PREFIX+map.get("record_id"));
				point_list = JSON.parseObject(jsonStr, List.class);
				point_list.add(map);
				String listStr = JSON.toJSONString(point_list);
				JedisUtils.set(PATROL_TRAJECTORY_CACHE_PREFIX+map.get("record_id"), listStr, JedisUtils.EXRP_DAY);
			} else {
				point_list.add(map);
				String listStr = JSON.toJSONString(point_list);
				JedisUtils.set(PATROL_TRAJECTORY_CACHE_PREFIX+map.get("record_id"), listStr, JedisUtils.EXRP_DAY);
			}
			JedisUtils.set(PATROL_CURRENT_CACHE_PREFIX+map.get("record_id"), JSON.toJSONString(map), JedisUtils.EXRP_DAY);
		}catch (Exception e) {
			UnifyLogger.parent(UnifyLogger.getTrace(e),UnifyLogger.Level.INFO);
			throw new CustomException("redis存入打点信息失败!");
		}

		return "success";
	}
	
	/**
	 * 结束巡查
	 * @param map
	 * @return
	 */
	
	@ApiOperation(value="网格巡检-巡查记录修改",desc="网格巡检-巡查记录修改",nologin=false)
	public String updatePatrolInfo(Map<String, Object> map) {
		map.put("nowDate", new Date());
		if(!map.containsKey("id")) {
			throw new CustomException("缺少必要参数id");
		}
		if(!map.containsKey("garden_id")) {
			throw new CustomException("缺少必要参数garden_id");
		}
		map.remove("start_time");
		//当前台缺少参数时，后台补充
		try {
			addParameters(map);
		} catch (Exception e) {
			UnifyLogger.parent(UnifyLogger.getTrace(e));
		}

		saveProperties(map);

		if (map.containsKey("photo") && StringUtils.isNotEmpty(map.get("photo"))) {
			map.put("photo_new", map.get("photo"));
		}

		try {
			//更新巡查项目数量
			if (map.containsKey("patrol_type")) {
				Map<String,Object> mapQuery=new HashMap<String, Object>();
				mapQuery.put("garden_id", map.get("garden_id"));
				mapQuery.put("del_flag", "0");
				List<Map<String, Object>> substanceList = new ArrayList<>();
				if ("网格巡查".equals(map.get("patrol_type"))) {
					substanceList = commonService.findList(Constant.NAMESPACE_PATROL + "selectSubstanceByGardenId", mapQuery);
				} 
				if (!substanceList.isEmpty()) {
					map.put("item_count", substanceList.size());
				}
			}
		} catch (Exception e) {
			UnifyLogger.parent(e.getStackTrace().toString(), UnifyLogger.Level.INFO);
		}

		//更新巡查项目巡查状态
		try {
			if (map.containsKey("checked_items")) {
				String checked_items = map.get("checked_items").toString();
				List maps = JSONArray.parseArray(checked_items, Map.class);
				Set<String> idSet = new HashSet<>();
				if (!maps.isEmpty()) {
					List<Map<String, Object>> parameters = new ArrayList<>(maps.size());
					for (Object o : maps) {
						Map<String, Object> parameter = new HashMap<>();
						Map<String, Object> mm = (Map<String, Object>) o;
						parameter.put("record_id", map.get("id"));
						parameter.put("id", mm.get("id"));
						idSet.add(mm.get("id").toString());
						//已巡查
						parameter.put("is_checked", "1");
						parameters.add(parameter);
					}
					commonService.updateBatch(Constant.NAMESPACE_PATROL + "updateSubstanceCheckState", parameters);
				}
				if (!idSet.isEmpty()) {
					map.put("current_item", idSet.size());
				}
			}
		} catch (Exception e) {
			UnifyLogger.parent(UnifyLogger.getTrace(e), UnifyLogger.Level.INFO);
		}

		if(commonService.update(Constant.NAMESPACE_PATROL + "updatePatrolRecordInfo", map) != 1) {
			throw new CustomException("操作失败");
		}

		if(map.containsKey("patrol_status")) {
			if(PatrolStatusEnum.end.getVal().equals(map.get("patrol_status"))) {
				if(JedisUtils.exists(PATROL_TRAJECTORY_CACHE_PREFIX+map.get("id"))) {
					String id = UUID.getUUID();
					map.put("uuid", id);
					map.put("record_id", map.get("id"));
					String json = JedisUtils.get(PATROL_TRAJECTORY_CACHE_PREFIX+map.get("id"));
					json = deletePatrolData(json);
					map.put("jsonparams", json);
					if(commonService.insert(Constant.NAMESPACE_PATROL + "insertPatrolHistoricalTraceData", map) != 1) {
						throw new CustomException("操作失败");
					}
				}
				//删除redis锁
				String garden_id = map.get("garden_id").toString();
				String cardNo = map.get("card_no").toString();
				String patrol_time_id = map.get("task_id").toString();
				Map<String, String> redisMap = new HashMap<>();
				Map<String, String> objectMap = JedisUtils.getMap(PATROL_KEY);
				String mapKey = garden_id + "_" + cardNo + "_" + patrol_time_id;
				JedisUtils.mapRemove(PATROL_KEY, mapKey);				
			}
		}
		
		return "success";
	}
	
	/**
	 * 结束巡查时，如果缺少参数，直接使用后台查询补充
	 * @param map
	 */
	private void addParameters(Map<String, Object> map) {
		Map<String, Object> parameter = new HashMap<>();
		parameter.put("id", map.get("id"));
		parameter.put("task_id", map.get("task_id"));
		parameter.put("garden_id", map.get("garden_id"));
		parameter.put("card_no", map.get("card_no"));
		Map<String, Object> patrolRecordInfo = getPatrolRecordInfo(parameter);
		if (StringUtils.isEmpty(map.get("time"))) {
			map.put("time", patrolRecordInfo.get("time"));
			//处理巡查项
			if (StringUtils.isNotEmpty(patrolRecordInfo.get("checked_items"))) {
				List<Map> checked_items = JSONUtil.toList(patrolRecordInfo.get("checked_items").toString(), Map.class);
				map.put("checked_items", patrolRecordInfo.get("checked_items"));
				map.put("current_item", checked_items.size());
			} else {
				map.put("checked_items", "[]");
				map.put("current_item", 0);
			}
		}
	}

	/**
	 * 	巡查报告记录其他属性
	 * @param map
	 */
	private void saveProperties(Map<String, Object> map){
		if(StringUtils.isNotEmpty(map.get("time"))) {
			String[] times=map.get("time").toString().split(":");
			if(times.length==3) {
				int seconds=Integer.parseInt(times[0].toString())*60*60+Integer.parseInt(times[1].toString())*60+Integer.parseInt(times[2].toString());
				map.put("cost_seconds", seconds);
			}
		}
		if(StringUtils.isNotEmpty(map.get("id"))) {
			Map<String,Object> mapQuery=new HashMap<String, Object>();
			mapQuery.put("record_id", map.get("id"));
			int count = commonService.getObject(Constant.NAMESPACE_PATROL + "selectPatrolEventReportCount", mapQuery);
			map.put("report_count", count);
		}
	}
	
	@ApiOperation(value="网格巡检-查询当前进行的任务记录信息",desc="网格巡检-查询当前进行的任务记录信息",nologin=false)
	public Map<String, Object> getPatrolRecordInfo(Map<String, Object> map){
		if(!map.containsKey("task_id")) {
			throw new CustomException("缺少必要参数task_id");
		}
		if(!map.containsKey("garden_id")) {
			throw new CustomException("缺少必要参数garden_id");
		}
		if(!map.containsKey("card_no")) {
			throw new CustomException("缺少必要参数card_no");
		}
		Map<String, Object> mapResult = commonService.getObject(Constant.NAMESPACE_PATROL + "getPatrolRecordInfo", map);
		if(mapResult==null) {
			throw new CustomException("请刷新界面确认当次网格巡查是否已结束！");
		}
		if(JedisUtils.exists(PATROL_CURRENT_CACHE_PREFIX+mapResult.get("id"))) {
			try {
				JSONObject parseObject = JSONUtil.parseObj(JedisUtils.get(PATROL_CURRENT_CACHE_PREFIX+mapResult.get("id")));
				String redisTime=StringUtils.isEmpty(parseObject.get("time").toString()) ? "00:00:00" : parseObject.get("time").toString();
				String dbTime=StringUtils.isNotEmpty(mapResult.get("time"))?mapResult.get("time").toString():"00:00:00";
				//判断巡查redis时间与db时间大小，看是否取缓存数据1.

				if(DateUtil.compare(DateUtil.parse(redisTime,DATE_TIME_PATTEN),
						DateUtil.parse(dbTime,DATE_TIME_PATTEN))>0) {
					mapResult.put("time", redisTime);
					mapResult.put("current_distance", parseObject.get("current_distance"));
					mapResult.put("checked_items", parseObject.get("checked_items"));
				}
			}catch (Exception e) {
				UnifyLogger.parent(UnifyLogger.getTrace(e), UnifyLogger.Level.INFO);
			}
		}
		return mapResult;
	}
	
	private String deletePatrolData(String jsonStr) {
		List<Map> maps = JSONUtil.toList(jsonStr, Map.class);
		for (Map<String, Object> mm : maps) {
			if (mm.containsKey("checked_items")) {
				mm.remove("checked_items");
			}
			if (mm.containsKey("_user")) {
				mm.remove("_user");
			}
			if (mm.containsKey("record_id")) {
				mm.remove("record_id");
			}
			if (mm.containsKey("card_no")) {
				mm.remove("card_no");
			}
			if (mm.containsKey("cardNO")) {
				mm.remove("cardNO");
			}
			if (mm.containsKey("cardNo")) {
				mm.remove("cardNo");
			}
		}
		return JSONUtil.toJsonStr(maps);
	}
	
	@ApiOperation(value = "暂停记录插入接口",desc = "",nologin = false)
	public String insertPauseReasonData(Map<String, Object> map) {
		checkParams(map);
		String id = UUID.getUUID();
		Date nowDate = new Date();
		map.put("uuid", id);
		map.put("create_time", nowDate);
		if(commonService.insert(Constant.NAMESPACE_PATROL + "insertPatrolPause", map) != 1) {
			throw new CustomException("操作失败");
		}
		return "success";
	}
	
	public void checkParams(Map<String, Object> map) {
		if(!map.containsKey("record_id")) {
			throw new CustomException("缺少 必要参数record_id");
		}
		if(!map.containsKey("reason")) {
			throw new CustomException("缺少 必要参数reason");
		}
		if(!map.containsKey("reason_desc")) {
			throw new CustomException("缺少 必要参数reason_desc");
		}
		if(!map.containsKey("lng")) {
			throw new CustomException("缺少 必要参数lng");
		}
		if(!map.containsKey("lat")) {
			throw new CustomException("缺少 必要参数lat");
		}
	}
	
	@ApiOperation(value="通过巡查记录id取巡查轨迹",desc="",nologin=false)
	public List<Map<String, Object>> getPatrolTrajectory(Map<String, Object> map){
		if(!map.containsKey("record_id")) {
			throw new CustomException("缺少必要参数record_id");
		}
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		if(JedisUtils.exists(PATROL_TRAJECTORY_CACHE_PREFIX+map.get("record_id"))) {
			String jsonStr = JedisUtils.get(PATROL_TRAJECTORY_CACHE_PREFIX+map.get("record_id"));
			list = JSON.parseObject(jsonStr, List.class);
		} else {
			Map<String, Object> ManageMap = new HashMap<String, Object>();
			ManageMap = commonService.getObject(Constant.NAMESPACE_PATROL + "getPatrolHistoricalTrace", map);
			if(StringUtils.isNotEmpty(ManageMap)) {
				String jsonStr = ManageMap.get("jsonparams")+"";
				JedisUtils.set(PATROL_TRAJECTORY_CACHE_PREFIX+map.get("record_id"), jsonStr, JedisUtils.EXRP_DAY);
				list = JSON.parseObject(jsonStr, List.class);
			}
		}
		return list;
	}
	
	@ApiOperation(value="查询暂停巡查，继续巡查位置信息接口",desc="",nologin=false)
	public List selectLocationPositionList(Map<String, Object> param) {
		if(!param.containsKey("record_id")) {
			throw new CustomException("缺少必要参数record_id");
		}
		return commonService.findList(Constant.NAMESPACE_PATROL + "selectLocationPositionList", param);
	}
	
	@ApiOperation(value="保存暂停巡查，继续巡查位置信息接口",desc="",nologin=false)
	public String insertLocationPosition(Map<String, Object> param) {
		if(!param.containsKey("record_id")) {
			throw new CustomException("缺少必要参数record_id");
		}
		if(!param.containsKey("state")) {
			throw new CustomException("缺少必要参数state");
		}
		if(!param.containsKey("lng")) {
			throw new CustomException("缺少必要参数lng");
		}
		if(!param.containsKey("lat")) {
			throw new CustomException("缺少必要参数lat");
		}
		if(!param.containsKey("point_id")) {
			throw new CustomException("缺少必要参数point_id");
		}
		String id = UUID.getUUID();
		Date date = new Date();
		param.put("uuid", id);
		param.put("create_time", date);
		
		if(commonService.insert(Constant.NAMESPACE_PATROL + "insertLocationPosition", param) != 1) {
			throw new CustomException("操作失败");
		}
		return "success";
	}
	
	@ApiOperation(value="详情列表接口",desc="",nologin=false)
	public List<Map<String, Object>> getPatroRecordlList(Map<String, Object> map){
//		if(!map.containsKey("task_id")) {
//			throw new CustomException("缺少必要参数task_id");
//		}
		if(!map.containsKey("record_id")) {
			throw new CustomException("缺少必要参数record_id");
		}
	    return commonService.findList(Constant.NAMESPACE_PATROL + "getPatroEventsList", map);	
	}
	
    @ApiOperation(value = "巡查记录",desc = "巡查记录",nologin = false)
    public Page patrolRecordPage(Page<Map>page){
        Page<Map> page1 = commonService.findPage(Constant.NAMESPACE_PATROL+"getPatrolRecordPage",page);
        return page1;
    }
	
    @ApiOperation(value = "巡查明细记录",desc = "巡查明细记录",nologin = false)
    public Map patrolRecordDetail(Map<String,Object> params){
        Map<String,Object> returnMap = new HashMap<>();
        Map<String,Object> result = commonService.getObject(Constant.NAMESPACE_PATROL+"patrolRecordDetail",params);
        if(null == result || result.size()==0){
            throw  new CustomException("未查到巡查详情");
        }
        params.put("record_id",params.get("id"));
        List<Map<String,Object>> list = commonService.findList(Constant.NAMESPACE_PATROL+"getPatroEventsList",params);
        returnMap.put("result",result);
        returnMap.put("list",list);
        return returnMap;
    }
	
	/*******************************************************/

	@ApiOperation(value="删除redis过期key",desc="",nologin=false)
	public String delRedisKey() {
		Date date = DateUtils.addDay(-1, new Date());
		long time = DateUtil.endOfDay(date).getTime();
		Map<String, String> map1 = JedisUtils.getMap(PATROL_KEY);
		map1.entrySet().forEach( mm -> {
			if (Long.valueOf(mm.getValue()) < time) {
				JedisUtils.mapRemove(PATROL_KEY, mm.getKey());
			}
		});
		return "success";
	}
	
	
	@ApiOperation(value = "查询巡查项",desc = "查询巡查项",nologin = false)
	public List patrolProjectList(Map<String,Object> params){
		List<Map<String,Object>> list = commonService.findList(Constant.NAMESPACE_PATROL+"patrolProjectList",params);
		return list;
	}
	@ApiOperation(value = "计划巡查时间是否巡查",desc = "计划巡查时间是否巡查",nologin = false)
	public List getPatrolStatus(Map<String,Object> params){
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
		params.put("create_time",simpleDateFormat.format(new Date()));
		List<Map<String,Object>> result = commonService.findList(Constant.NAMESPACE_PATROL+"getPatrolStatus",params);
		return result;
	}

	/*
	@ApiOperation(value="定时任务调用",desc="每天23点执行",nologin=false)
	public String updatePatrolState() {
		Date now = new Date();
		Map<String, Object> parameter = new HashMap<>();
		parameter.put("now", now);
		//查询当天未结束的巡查
		List<String> recordIds = commonService.findList(Constant.NAMESPACE_PATROL + "findToDoEndRecordList", parameter);
		String pluskey = "";
		if (StringUtils.isNotEmpty(recordIds)) {
			List<Map<String, Object>> list = new ArrayList<>();
			List<Map<String, Object>> parameters = new ArrayList<>();
			for (String recordId : recordIds) {
				try {
					parameter.clear();
					String id = UUID.getUUID();
					parameter.put("uuid", id);
					parameter.put("record_id", recordId);
					pluskey = PATROL_TRAJECTORY_CACHE_PREFIX + recordId;
					String pointStr = JedisUtils.get(pluskey);
					//删除无用的轨迹数据
					pointStr = deletePatrolData(pointStr);
					parameter.put("jsonparams", pointStr);
					commonService.insert(Constant.NAMESPACE_PATROL + "insertManagementData", parameter);
					double distance = 0d;
					String time = "00:00:00";
					String checked_items = null;
					Map<String, Object> data = new HashMap<>();
					if(JedisUtils.exists(PATROL_CURRENT_CACHE_PREFIX+recordId)) {
						try {
							JSONObject parseObject = JSONUtil.parseObj(JedisUtils.get(PATROL_CURRENT_CACHE_PREFIX+recordId));
							time=parseObject.get("time").toString();
							distance=Double.parseDouble(parseObject.get("current_distance").toString());
							data.put("checked_items", parseObject.get("checked_items"));
							
							//更新巡查项目巡查状态
							if (parseObject.containsKey("checked_items")) {
								checked_items = parseObject.get("checked_items").toString();
							}
						}catch (Exception e) {
							List<Map> maps = JSONArray.parseArray(pointStr, Map.class);
							if (maps != null) {
								for (Map<String, Object> mm : maps) {
									Double current_distance = Double.valueOf(mm.get("current_distance").toString());
									if (current_distance > distance) {
										distance = current_distance;
										time = mm.get("time").toString();
										checked_items = mm.get("checked_items").toString();
									}
								}
							}
							UnifyLogger.parent("exception==>"+UnifyLogger.getTrace(e), UnifyLogger.Level.INFO);
						}
					}
					
					List maps = JSONArray.parseArray(checked_items, Map.class);
					if (maps != null && !maps.isEmpty()) {
						Set<String> idSet = new HashSet<>();
						for (Object o : maps) {
							Map<String, Object> mm = (Map<String, Object>) o;
							parameter.put("record_id", recordId);
							parameter.put("id", mm.get("id"));
							idSet.add(mm.get("id").toString());
							parameter.put("is_checked", "1");//已巡查
							parameters.add(parameter);
						}
						if (!idSet.isEmpty()) {
							data.put("current_item", idSet.size());
						}
					}
					//更新巡查状态
					parameter.clear();
					data.put("id", recordId);
					data.put("end_time", DateUtil.format(now, "yyyy-MM-dd HH:mm:ss"));
					data.put("patrol_distance", distance);
					data.put("patrol_type", "网格巡查");
					data.put("time", time);
					data.put("patrol_status", PatrolStatusEnum.end.getVal());
					data.put("nowDate", now);

					try {
						//更新巡查项目数量
						Map<String,Object> mapQuery=new HashMap<String, Object>();
						mapQuery.clear();
						mapQuery.put("id", recordId);
						Map<String, Object> patrolResult = commonService.getObject(Constant.nameSpace_patrolRecord + "getOne", mapQuery);
						mapQuery.clear();
						mapQuery.put("garden_id", patrolResult.get("garden_id"));
						mapQuery.put("del_flag", "0");
						List<Map<String, Object>> sublist = new ArrayList<>();
						sublist = commonService.findList(Constant.nameSpace_auditGridSubstance + "selectByGardenId", mapQuery);
						if (!sublist.isEmpty()) {
							data.put("item_count", sublist.size());
						}
					} catch (Exception e) {
						UnifyLogger.parent(e.getStackTrace().toString());
					}

					saveProperties(data);
					list.add(data);
				} catch (Exception e) {
					UnifyLogger.parent(e.getStackTrace().toString());
				}


			}
			if (list != null && !list.isEmpty()) {
				commonService.updateBatch(Constant.NAMESPACE_PATROL + "updatePatrolInfo", list);
			}
			if (parameters != null && !parameters.isEmpty()) {
				commonService.updateBatch(Constant.nameSpace_patrolRecordSubstance + "updateState", parameters);
			}
		}
		return "success";
	}
	*/
	
	@ApiOperation(value="获取坐标信息",desc="获取坐标信息",nologin=false)
	public Map<String, Object> selectPointSQJD(Map map) {
		Map<String, Object> newMap = new HashMap<>();
		Map<String, Object> parameter = new HashMap<>();
		parameter.put("location",map.get("coordinate"));
		String post = null;
		try {
//			post = HttpUtil.createGet("http://172.18.4.121:6677/syxxzx/net/selectPointSQJD").timeout(2000).form(parameter).execute().body();
//			post = HttpUtil.createGet("http://172.18.4.121:6679/sqjd/net/selectPointSQJD").timeout(2000).form(parameter).execute().body();
			post = HttpUtil.createGet("http://172.18.4.121:6680/sqjdapp/net/selectPointSQJD").timeout(2000).form(parameter).execute().body();
		} catch (Exception e) {
			throw new CustomException("获取地图坐标信息失败", e);
		}
		UnifyLogger.parent("selectPointSQJD result : " + post);
    	newMap.put("info", post);
		return newMap;
	}
	
	
	

	@ApiOperation(value="巡查工单管理查询",desc = "巡查工单管理")
	public Page patrolRecordManagementList(Page<Map<String, Object>> page){
		com.scpyun.platform.jilinsscgsdp.utils.DateUtil.queryDateRange(page.getParams(),"patrol_time");
		page = commonService.findPage(Constant.NAMESPACE_PATROL + "getPatrolRecordPageForPC", page);
		return page;
	}
	
	@ApiOperation(value="网格排查隐患查询",desc = "网格排查隐患查询")
	public Page hiddenDangerDisposaList(Page<Map<String, Object>> page){
		com.scpyun.platform.jilinsscgsdp.utils.DateUtil.queryDateRange(page.getParams(),"patrol_time");
		com.scpyun.platform.jilinsscgsdp.utils.DateUtil.queryDateRange(page.getParams(),"disposal_time");
		page.getParams().put("hidden_danger_query", "true");
		page = commonService.findPage(Constant.NAMESPACE_PATROL + "getPatrolRecordPageForPC", page);
		return page;
	}
	
	@ApiOperation(value="网格排查隐患处置",desc = "网格排查隐患处置")
	public String updateHiddenDangerDisposa(Map<String, Object> map){
		if(commonService.update(Constant.NAMESPACE_PATROL + "updateHiddenDangerDisposa", map)==1) {
			return "处置完成"; 
		}
		return "操作异常";
	}
}

