package com.zcloud.modules.map.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zcloud.common.utils.DateUtil;
import com.zcloud.modules.map.service.FourColourService;
import com.zcloud.modules.sys.entity.PageData;
import com.zcloud.util.HttpRequestUtil;
import com.zcloud.util.PerLocUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.util.*;
import java.util.stream.Collectors;


/**
 * 说明：地图四色四固定图层
 * 作者：zhaoyu
 * 时间：2024-05-20
 * 官网：www.zcloudchina.com
 */
@Service
@Transactional //开启事物
public class FourColourServiceImpl implements FourColourService {


	@Autowired
	private PerLocUtil perLocUtil;

	@Autowired
	private RestTemplate restTemplate;

	@Value("${perLoc.url}")
	private String url;

	@Override
	public Object getAlarmStatistics(String route) throws Exception {
		Map<String, Object> map = new HashMap<>();
		String errInfo = "success";
		String path = url + route;
		String _response = HttpRequestUtil.doGetUser(path, perLocUtil.getToken());
		if (StringUtils.isNotEmpty(_response)) {
			JSONObject response = JSONObject.parseObject(_response);
			if(response.get("data") != null){
				map.put("varList",response.get("data"));
			}
		}
		map.put("result",errInfo);
		return map;
	}


	@Override
	public Object personInAndCarIn() throws Exception {
		Map<String, Object> map = new HashMap<>();
		String errInfo = "success";
		List<PageData> varList = new ArrayList<>();
		// 车辆趋势
		String carPath = url +"/region/access/inOrOutFactoryCarAnalysis?dateStr=day";
		String _response = HttpRequestUtil.doGetUser(carPath, perLocUtil.getToken());
		if (StringUtils.isNotEmpty(_response)) {
			JSONObject response = JSONObject.parseObject(_response);
			if(response.get("detailList") != null){
				varList = JSONObject.parseArray(JSON.toJSON(response.get("detailList")).toString(), PageData.class);
			}
		}
		//车辆趋势完成
		//人员趋势
		//开始时间为当天0点
		String start = DateUtil.getDay()+" 00:00:00";
		//结束时间为当前时间
		String end = DateUtil.date2Str(new Date());
		String personPath = url + "/region/access/bayonetPersonnelEntryAndExitRecords?"+"fstartDate="+start+"&fendDate="+end+"&empNo=&empId=&entrystatus=&accId=";
		RestTemplate restTemplate = new RestTemplate();
		HttpHeaders headers = new HttpHeaders();
		headers.set("Authorization", perLocUtil.getToken());
		HttpEntity<String> entity = new HttpEntity<>(headers);

		ResponseEntity<String> response = restTemplate.exchange(personPath, HttpMethod.GET, entity, String.class);
		if (response.getStatusCode().is2xxSuccessful()) {
			String responseBody = response.getBody(); // 获取响应体字符串
			JSONObject responseObject = JSONObject.parseObject(responseBody);
			if(responseObject.get("code") != null && responseObject.get("code").toString().equals("200") ){
				List<PageData> presonList = JSONObject.parseArray(JSON.toJSON(responseObject.get("data")).toString(), PageData.class);
				presonList = presonList.stream().filter(n -> "0".equals(n.getString("entrystatus"))).collect(Collectors.toList());
				Map<String,List<PageData>> listMap = presonList.stream().collect(Collectors.groupingBy(n-> n.getString("chtime").substring(0,13)));
				for(PageData pageData:varList){
					if(listMap.containsKey(pageData.getString("fdate"))){
						pageData.put("personNum",listMap.get(pageData.getString("fdate")).size());
					}else {
						pageData.put("personNum",0);
					}
				}
			}
		} else {
			// 处理非成功状态码的情况
			System.out.println("Request failed with status code: " + response.getStatusCode());
		}
		map.put("varList",varList);
		map.put("result",errInfo);
		return map;
	}

	@Override
	public Object currentDayGdDetailInfor(String route) throws Exception {
		Map<String, Object> map = new HashMap<>();
		String errInfo = "success";
		String path = url + route;
		String _response = HttpRequestUtil.doGetUser(path, perLocUtil.getToken());
		if (StringUtils.isNotEmpty(_response)) {
			JSONObject response = JSONObject.parseObject(_response);
			if(response.get("list") != null){
				map.put("varList",response.get("list"));
			}
		}
		map.put("result",errInfo);
		return map;
	}

	@Override
	public Object getGDDetailListByArea(String pageNum,String pageSize,String str,String type) throws Exception {
		Map<String, Object> map = new HashMap<>();
		String errInfo = "success";
		List<PageData> varList = new ArrayList<>();
		List<PageData> gdList = new ArrayList<>();
		HttpHeaders headers = new HttpHeaders();
		headers.set("Authorization", perLocUtil.getToken());
		HttpEntity<String> entity = new HttpEntity<>(headers);
		ResponseEntity<String> response = restTemplate.exchange(url + "/region/region/list?pageNum="
						+ pageNum
						+ "&pageSize=" + pageSize
						+ "&str=" + str
						+ "&type=" + type
				, HttpMethod.GET, entity, String.class);
		if (response.getStatusCode().is2xxSuccessful()) {
			String responseBody = response.getBody(); // 获取响应体字符串
			JSONObject responseObject = JSONObject.parseObject(responseBody);
			if (responseObject.get("code") != null && responseObject.get("code").toString().equals("200")) {
				varList = JSONObject.parseArray(JSON.toJSON(responseObject.get("rows")).toString(), PageData.class);
				for (PageData pageData : varList) {
					if (
							pageData.getString("regName").equals("一期码头")
						 || pageData.getString("regName").equals("二期码头")
						 || pageData.getString("regName").equals("一期堆场")
						 || pageData.getString("regName").equals("二期堆场")
						 || pageData.getString("regName").equals("杂货码头")
					) {
						PageData gdTongJi = new PageData();
						if (pageData.getString("regName").equals("杂货码头")) {
							gdTongJi.put("regName","杂货码头场区");
						} else {
							gdTongJi.put("regName",pageData.getString("regName"));
						}
						int red = 0;
						int orange = 0;
						int blue = 0;
						int yellow = 0;
						ResponseEntity<String> tempResponse = restTemplate.exchange(url + "/region/region/getPsnByRegionName?regionName=" + pageData.getString("regName"), HttpMethod.GET, entity, String.class);
						if (tempResponse.getStatusCode().is2xxSuccessful()) {
							String tempResponseBody = tempResponse.getBody(); // 获取响应体字符串
							JSONObject tempResponseObject = JSONObject.parseObject(tempResponseBody);
							if (tempResponseObject.get("code") != null && tempResponseObject.get("code").toString().equals("200")) {
								List<PageData> pList = JSONObject.parseArray(JSON.toJSON(tempResponseObject.get("data")).toString(), PageData.class);
								//不是人员数
								if (pList.size()>0) {
									for (PageData data : pList) {
										List<PageData> psn = JSONArray.parseArray(data.get("psn").toString(), PageData.class);
										for (PageData person : psn) {
											//根据人员获取工单
											String path = url + "/region/access/aListOfTicketsCurrentlyInProgress?workNumber=" + person.getString("empNo");
											String _response = HttpRequestUtil.doGetUser(path, perLocUtil.getToken());
											if (StringUtils.isNotEmpty(_response)) {
												JSONObject result = JSONObject.parseObject(_response);
												if(result.get("data") != null){
													List<PageData> dataList = JSONObject.parseArray(result.getString("data"), PageData.class);
													for (PageData gdData : dataList) {
														//工单信息
														if (gdData.getString("fcolorStr").equals("红")) {
															red+=1;
														} else if (gdData.getString("fcolorStr").equals("橙")) {
															orange+=1;
														} else if (gdData.getString("fcolorStr").equals("黄")) {
															yellow+=1;
														} else if (gdData.getString("fcolorStr").equals("蓝")) {
															blue+=1;
														}
													}
												}
											}
										}
									}
								}
							}
						}
						gdTongJi.put("red",red);
						gdTongJi.put("blue",blue);
						gdTongJi.put("yellow",yellow);
						gdTongJi.put("orange",orange);
						gdTongJi.put("total",red+blue+yellow+orange);
						gdList.add(gdTongJi);
					}
				}
			} else {
				// 处理非成功状态码的情况
				System.out.println("Request failed with status code: " + response.getStatusCode());
			}
		}
		map.put("result",errInfo);
		ArrayList<PageData> finalGDList = new ArrayList<>();
		PageData yiErQiDuiChang = new PageData();
		yiErQiDuiChang.put("regName","一、二期堆场");
		int red = 0;
		int orange = 0;
		int yellow = 0;
		int blue = 0;
		int total = 0;
		for (PageData gongDan : gdList) {
			if (gongDan.get("regName").equals("二期堆场") || gongDan.get("regName").equals("一期堆场")) {
				red = red + Integer.parseInt(gongDan.getString("red"));
				orange = orange + Integer.parseInt(gongDan.getString("orange"));
				yellow = yellow + Integer.parseInt(gongDan.getString("yellow"));
				blue = blue + Integer.parseInt(gongDan.getString("blue"));
				total = total + Integer.parseInt(gongDan.getString("total"));
			} else {
				finalGDList.add(gongDan);
			}
		}
		yiErQiDuiChang.put("red",red);
		yiErQiDuiChang.put("orange",orange);
		yiErQiDuiChang.put("yellow",yellow);
		yiErQiDuiChang.put("blue",blue);
		yiErQiDuiChang.put("total",total);
		finalGDList.add(yiErQiDuiChang);
		map.put("gdList",finalGDList);
		return map;
	}

	@Override
	public Object carTypeAnalysis(String route) throws Exception {
		Map<String, Object> map = new HashMap<>();
		String errInfo = "success";
		String path = url + route;
		String _response = HttpRequestUtil.doGetUser(path, perLocUtil.getToken());
		if (StringUtils.isNotEmpty(_response)) {
			JSONObject response = JSONObject.parseObject(_response);
			if(response.get("list") != null){
				map.put("varList",response.get("list"));
			}
		}
		map.put("result",errInfo);
		return map;
	}

}

