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.modules.map.mapper.PlatformvideomanagementMapper;
import com.zcloud.modules.map.service.MapService;
import com.zcloud.modules.sys.entity.PageData;
import com.zcloud.util.PerLocUtil;
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 javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;


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


	@Autowired
	private PerLocUtil perLocUtil;

	@Autowired
	private PlatformvideomanagementMapper platformvideomanagementMapper;

	@Autowired
	private RestTemplate restTemplate;

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

	@Override
	public Map<String, Object> listMapSluiceCount() {
		PageData pd = new PageData();
		pd.put("CORPINFO_ID","8854edee3aa94be496cee676b6d4845a");
		List<PageData> cameraList = platformvideomanagementMapper.listAllForMap(pd);
		Map<String, Object> result = restTemplate.getForObject(url + "/region/access/obtainBayonetData?type=", Map.class);
		int onlinePerGate = 0;
		int onlineCarGate = 0;
		ArrayList<String> peopleIds = new ArrayList<>();
		ArrayList<String> carIds = new ArrayList<>();
		if (result != null && result.get("data") != null) {
			List<JSONObject> gateList = JSONObject.parseArray(JSON.toJSONString(result.get("data")), JSONObject.class);
			if (gateList != null && gateList.size() > 0) {
				for (JSONObject gate : gateList) {
					if ("0".equals(gate.getString("type"))) {
						carIds.add(gate.getString("id"));
					} else if ("1".equals(gate.getString("type"))) {
						peopleIds.add(gate.getString("id"));
					}
				}
			}
		}
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String fendDate = simpleDateFormat.format(new Date());
		Calendar now = Calendar.getInstance();
		now.add(Calendar.MINUTE, -10);
		Date before = now.getTime();
		String fstartDate = simpleDateFormat.format(before);
		Map<String, Object> result2 = restTemplate.getForObject(url + "/region/access/bayonetPersonnelEntryAndExitRecords?fstartDate=" + fstartDate + "&fendDate=" + fendDate + "&empNo=&empId=&entrystatus=&accId=", Map.class);
		if (result2 != null && result2.get("data") != null) {
			List<JSONObject> gateList = JSONObject.parseArray(JSON.toJSONString(result2.get("data")), JSONObject.class);
			Set<String> ids = new HashSet<>();
			for (JSONObject gateId : gateList) {
				ids.add(gateId.getString("accId"));
			}
			for (String peopleId : peopleIds) {
				if (ids.contains(peopleId)) {
					onlinePerGate++;
				}
			}
			for (String carId : carIds) {
				if (ids.contains(carId)) {
					onlineCarGate++;
				}
			}
		}
		result.put("onlinePerGate", onlinePerGate);
		result.put("offlinePerGate", peopleIds.size() - onlinePerGate);
		result.put("onlineCarGate", onlineCarGate);
		result.put("offlineCarGate", carIds.size() - onlineCarGate);
		result.put("cameraCount", cameraList.size());
		if ("200".equals(result.get("code").toString())) {
			result.put("result", "success");
		} else {
			result.put("result", "error");
		}
		result.remove("data");
		return result;
	}

	@Override
	public Object getAreaDetail(String pageNum, String pageSize, String str, String type) throws Exception {
		Map<String, Object> map = new HashMap<>();
		List<PageData> varList = new ArrayList<>();
		String errInfo = "success";
		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) {
					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) {
								PageData p = pList.get(0);
								List<PageData> psn = JSONArray.parseArray(p.get("psn").toString(), PageData.class);
								pageData.put("pCount",psn.size());
							}
						}
					}
				}
			} else {
				// 处理非成功状态码的情况
				System.out.println("Request failed with status code: " + response.getStatusCode());
			}
		}
		map.put("varList", varList);
		map.put("result", errInfo);
		System.out.println(response);
		return map;
	}
}

