package com.zcloud.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zcloud.entity.PageData;
import com.zcloud.service.corp.CorpPlsInfoService;
import com.zcloud.service.system.UsersService;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.locks.ReentrantLock;

@Component
public class PLSUtil {
    private static final Logger logger = LoggerFactory.getLogger(PLSUtil.class);
    private static CorpPlsInfoService corpplsinfoService;
    private static UsersService usersService;
    // 后台地址
    public static HashMap<String, String> BAKEADDR = new HashMap<>();
    private static RestTemplate restTemplate;


    public static byte[] getGltfFlow(String CORPINFO_ID, String filename) throws Exception {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", getToken(CORPINFO_ID));
        HttpEntity<JSONObject> httpEntity = new HttpEntity<>(headers);
        ResponseEntity<byte[]> exchange = restTemplate.exchange(getBakeAddr(CORPINFO_ID).replace("8084", "9000") + "/buildr/public/models/glb/" + filename + ".gltf", HttpMethod.GET, httpEntity, byte[].class);
        return exchange.getBody();
    }

    public static JSONObject getSceneJson(String CORPINFO_ID) throws Exception {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", getToken(CORPINFO_ID));
        HttpEntity<JSONObject> httpEntity = new HttpEntity<>(headers);
        ResponseEntity<JSONObject> exchange = restTemplate.exchange(getBakeAddr(CORPINFO_ID).replace("8084", "9000") + "/buildr/public/models/scene_000001.json", HttpMethod.GET, httpEntity, JSONObject.class);
        return exchange.getBody();
    }

    public static JSONObject getPersonnelPositioningCount(String CORPINFO_ID, Integer currentPage, Integer showCount) throws Exception {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", getToken(CORPINFO_ID));
        HttpEntity<JSONObject> httpEntity = new HttpEntity<>(headers);
        ResponseEntity<JSONObject> exchange = restTemplate.exchange(getBakeAddr(CORPINFO_ID) + "/deploy/card/list?sortThePowerLevel=1&pageNum=" + currentPage + "&pageSize=" + showCount, HttpMethod.GET, httpEntity, JSONObject.class);
        return exchange.getBody();
    }

    public static JSONObject GetGeneral(String url, String CORPINFO_ID) throws Exception {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", getToken(CORPINFO_ID));
        HttpEntity<JSONObject> httpEntity = new HttpEntity<>(headers);
        ResponseEntity<JSONObject> exchange = restTemplate.exchange(getBakeAddr(CORPINFO_ID) + url, HttpMethod.GET, httpEntity, JSONObject.class);
        return exchange.getBody();
    }

    public static int getPsnByRegionName(String CORPINFO_ID, String regionName) throws Exception {

        HttpHeaders headers = new HttpHeaders();

        headers.set("Authorization", getToken(CORPINFO_ID));
        //  "/region/alarm/list?pageNum=" +
        //                currentPage + "&pageSize=" + showCount +"&str="  + "&eleType="+eleType+ "&status="+status
        HttpEntity<JSONObject> httpEntity = new HttpEntity<>(headers);
        ResponseEntity<JSONObject> exchange = restTemplate.exchange(getBakeAddr(CORPINFO_ID) + "/region/region/getPsnByRegionName?regionName=" + regionName, HttpMethod.GET, httpEntity, JSONObject.class);

        if (exchange.getBody().getString("code").equals("500")) return -1;
        return exchange.getBody().getJSONArray("data").getJSONObject(0).getJSONArray("psn").toJavaList(JSONObject.class).size();

    }

    @Autowired
    public void setCorpplsinfoService(CorpPlsInfoService corpplsinfoServicebean, UsersService usersServicebean, @Qualifier("restTemplate") RestTemplate restTemplatebean) {
        corpplsinfoService = corpplsinfoServicebean;
        usersService = usersServicebean;
        restTemplate = restTemplatebean;
    }

    /**
     * @Description: 告警类型统计
     * @Author: dearLin
     * @Date: 2024/1/25/025 14:37
     * @Param: [java.lang.String, java.lang.Integer, java.lang.Integer] [keywords, currentPage, showCount]
     * @Return: com.alibaba.fastjson.JSONObject
     */
    public static JSONObject getAlarmTypeCount(String CORPINFO_ID) throws Exception {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", getToken(CORPINFO_ID));
        HttpEntity<JSONObject> httpEntity = new HttpEntity<>(headers);
        ResponseEntity<JSONObject> exchange = restTemplate.exchange(getBakeAddr(CORPINFO_ID) + "/region/alarm/alarmStatistics?type=day", HttpMethod.GET, httpEntity, JSONObject.class);
        return exchange.getBody();
    }

    public static JSONObject GeneralPost(String Url, PageData pageData, String CORPINFO_ID) throws Exception {
        JSONObject uriVariables = JSONObject.parseObject(JSON.toJSONString(pageData));
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", getToken(CORPINFO_ID));
        HttpEntity<JSONObject> httpEntity = new HttpEntity<>(uriVariables, headers);
        ResponseEntity<JSONObject> exchange = restTemplate.exchange(getBakeAddr(CORPINFO_ID) + Url, HttpMethod.POST, httpEntity, JSONObject.class);
        return exchange.getBody();
    }

    public static JSONObject GeneralGetById(String Url, Object id, String CORPINFO_ID) throws Exception {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", getToken(CORPINFO_ID));
        HttpEntity<JSONObject> httpEntity = new HttpEntity<>(headers);
        ResponseEntity<JSONObject> exchange = restTemplate.exchange(getBakeAddr(CORPINFO_ID) + Url + id, HttpMethod.GET, httpEntity, JSONObject.class);
        return exchange.getBody();
    }

    public static JSONObject GeneralList(String Url, PageData pageData) throws Exception {
        String params = buildGetParams(JSONObject.parseObject(JSON.toJSONString(pageData)));
        String CORPINFO_ID = Jurisdiction.getCORPINFO_ID();
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", getToken(CORPINFO_ID));
        HttpEntity<JSONObject> httpEntity = new HttpEntity<>(headers);
        ResponseEntity<JSONObject> exchange = restTemplate.exchange(getBakeAddr(CORPINFO_ID) + Url + params, HttpMethod.GET, httpEntity, JSONObject.class);
        return exchange.getBody();
    }

    public static JSONObject GeneralPut(String Url, PageData pageData, String CORPINFO_ID) throws Exception {
        JSONObject uriVariables = JSONObject.parseObject(JSON.toJSONString(pageData));
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", getToken(CORPINFO_ID));
        HttpEntity<JSONObject> httpEntity = new HttpEntity<>(uriVariables, headers);
        ResponseEntity<JSONObject> exchange = restTemplate.exchange(getBakeAddr(CORPINFO_ID) + Url, HttpMethod.PUT, httpEntity, JSONObject.class);
        return exchange.getBody();
    }

    public static JSONObject GeneralDelete(String Url, Object id, String CORPINFO_ID) throws Exception {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", getToken(CORPINFO_ID));
        HttpEntity<JSONObject> httpEntity = new HttpEntity<>(headers);
        ResponseEntity<JSONObject> exchange = restTemplate.exchange(getBakeAddr(CORPINFO_ID) + Url + id, HttpMethod.DELETE, httpEntity, JSONObject.class);
        return exchange.getBody();
    }

    /**
     * @Description: 电子围栏列表
     * @Author: dearLin
     * @Date: 2024/1/25/025 14:37
     * @Param: [java.lang.String, java.lang.Integer, java.lang.Integer] [keywords, currentPage, showCount]
     * @Return: com.alibaba.fastjson.JSONObject
     */
    public static JSONObject getLayerList(String CORPINFO_ID, Integer currentPage, Integer showCount, String keywords) throws Exception {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", getToken(CORPINFO_ID));

        HttpEntity<JSONObject> httpEntity = new HttpEntity<>(headers);
        String url = "/region/layer/list?pageNum=" + currentPage + "&pageSize=" + showCount + "&str=";
        if (Tools.notEmpty(keywords)) {
            url = url + keywords;
        }
        ResponseEntity<JSONObject> exchange = restTemplate.exchange(getBakeAddr(CORPINFO_ID) + url, HttpMethod.GET, httpEntity, JSONObject.class);
        return exchange.getBody();
    }

    /**
     * @Description: 电子围栏列表
     * @Author: dearLin
     * @Date: 2024/1/25/025 14:37
     * @Param: [java.lang.String, java.lang.Integer, java.lang.Integer] [keywords, currentPage, showCount]
     * @Return: com.alibaba.fastjson.JSONObject
     */
    public static JSONObject getAlArmDataList(String CORPINFO_ID, Integer currentPage, Integer showCount, String keywords, Integer status, Integer eleType) throws Exception {
        HttpHeaders headers = new HttpHeaders();

        headers.set("Authorization", getToken(CORPINFO_ID));
        //  "/region/alarm/list?pageNum=" +
        //                currentPage + "&pageSize=" + showCount +"&str="  + "&eleType="+eleType+ "&status="+status
        HttpEntity<JSONObject> httpEntity = new HttpEntity<>(headers);
        ResponseEntity<JSONObject> exchange = restTemplate.exchange(getBakeAddr(CORPINFO_ID) + "/region/alarm/list?eleType=" + eleType + "&status=" + status + "&pageNum=" + currentPage + "&pageSize=" + showCount + "&str=", HttpMethod.GET, httpEntity, JSONObject.class);
        return exchange.getBody();
    }


    /**
     * @Description: 人员卡列表
     * @Author: dearLin
     * @Date: 2024/1/25/025 14:37
     * @Param: [java.lang.String, java.lang.Integer, java.lang.Integer] [keywords, currentPage, showCount]
     * @Return: com.alibaba.fastjson.JSONObject
     */
    public static JSONObject getUserCardDataList(String CORPINFO_ID, Integer currentPage, Integer showCount, String keywords) throws Exception {
        HttpHeaders headers = new HttpHeaders();

        headers.set("Authorization", getToken(CORPINFO_ID));
        String url = "/deploy/card/list?pageNum=" + currentPage + "&pageSize=" + showCount + "&str=";
        if (Tools.notEmpty(keywords)) {
            url = url + keywords;
        }
        HttpEntity<JSONObject> httpEntity = new HttpEntity<>(headers);
        ResponseEntity<JSONObject> exchange = restTemplate.exchange(getBakeAddr(CORPINFO_ID) + url, HttpMethod.GET, httpEntity, JSONObject.class);
        return exchange.getBody();
    }


    /**
     * @Description: 查询摄像头
     * @Author: dearLin
     * @Date: 2024/1/25/025 14:37
     * @Param: [java.lang.String, java.lang.Integer, java.lang.Integer] [keywords, currentPage, showCount]
     * @Return: com.alibaba.fastjson.JSONObject
     */
    public static JSONObject getCameraList(String CORPINFO_ID) throws Exception {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", getToken(CORPINFO_ID));
        HttpEntity<JSONObject> httpEntity = new HttpEntity<>(headers);
        ResponseEntity<JSONObject> exchange = restTemplate.exchange(getBakeAddr(CORPINFO_ID) + "/device/camera/list?pageNum=1&pageSize=100000&str=", HttpMethod.GET, httpEntity, JSONObject.class);
        return exchange.getBody();
    }

    /**
     * @Description: 添加摄像头
     * @Author: dearLin
     * @Date: 2024/1/25/025 14:37
     * @Param: [java.lang.String, java.lang.Integer, java.lang.Integer] [keywords, currentPage, showCount]
     * @Return: com.alibaba.fastjson.JSONObject
     */
    public static JSONObject saveCamera(String CORPINFO_ID, PageData camera) throws Exception {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", getToken(CORPINFO_ID));
        headers.setContentType(org.springframework.http.MediaType.valueOf("application/json"));
        JSONObject uriVariables = new JSONObject();
        uriVariables.put("camNo", camera.getString("CODE"));
        uriVariables.put("camName", camera.getString("VIDEONAME"));
        uriVariables.put("camIp", "127.0.0.1");
        uriVariables.put("type", "0");
        uriVariables.put("port", "");
        uriVariables.put("camUserName", "1");
        uriVariables.put("camPassword", "1");
        uriVariables.put("lon", "");
        uriVariables.put("lat", "");
        uriVariables.put("alt", "");
        HttpEntity<JSONObject> httpEntity = new HttpEntity<>(uriVariables, headers);
//        HttpEntity<JSONObject> httpEntity = new HttpEntity<>(uriVariables,headers);
//        ResponseEntity<JSONObject> jsonObjectResponseEntity = restTemplate.postForEntity(getBakeAddr(CORPINFO_ID) + "/device/camera",
//                httpEntity, JSONObject.class);


        ResponseEntity<JSONObject> exchange = restTemplate.exchange(getBakeAddr(CORPINFO_ID) + "/device/camera", HttpMethod.POST, httpEntity, JSONObject.class);
        return exchange.getBody();
    }

    /**
     * @Description: 修改摄像头
     * @Author: dearLin
     * @Date: 2024/1/25/025 14:37
     * @Param: [java.lang.String, java.lang.Integer, java.lang.Integer] [keywords, currentPage, showCount]
     * @Return: com.alibaba.fastjson.JSONObject
     */
    public static JSONObject editCamera(String CORPINFO_ID, PageData camera) throws Exception {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", getToken(CORPINFO_ID));
        headers.setContentType(org.springframework.http.MediaType.valueOf("application/json"));
        JSONObject uriVariables = new JSONObject();
        uriVariables.put("camNo", camera.getString("CODE"));
        uriVariables.put("camName", camera.getString("VIDEONAME"));
        uriVariables.put("camId", camera.getString("PLS_ID"));
        HttpEntity<JSONObject> httpEntity = new HttpEntity<>(uriVariables, headers);
        ResponseEntity<JSONObject> exchange = restTemplate.exchange(getBakeAddr(CORPINFO_ID) + "/device/camera", HttpMethod.PUT, httpEntity, JSONObject.class, uriVariables);
        return exchange.getBody();
    }

    /**
     * @Description: 删除摄像头
     * @Author: dearLin
     * @Date: 2024/1/25/025 14:37
     * @Param: [java.lang.String, java.lang.Integer, java.lang.Integer] [keywords, currentPage, showCount]
     * @Return: com.alibaba.fastjson.JSONObject
     */
    public static JSONObject removeCamera(String CORPINFO_ID, PageData camera) throws Exception {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", getToken(CORPINFO_ID));
        HttpEntity<JSONObject> httpEntity = new HttpEntity<>(headers);
        ResponseEntity<JSONObject> exchange = restTemplate.exchange(getBakeAddr(CORPINFO_ID) + "/device/camera/" + Integer.parseInt(camera.getString("PLS_ID")), HttpMethod.DELETE, httpEntity, JSONObject.class);
        return exchange.getBody();
    }


    /**
     * @Description: 电子围栏列表
     * @Author: dearLin
     * @Date: 2024/1/25/025 14:37
     * @Param: [java.lang.String, java.lang.Integer, java.lang.Integer] [keywords, currentPage, showCount]
     * @Return: com.alibaba.fastjson.JSONObject
     */
    public static JSONObject getRyRegionList(String CORPINFO_ID, String keywords, Integer currentPage, Integer showCount, Integer type) throws Exception {
        HttpHeaders headers = new HttpHeaders();
        String url = "/region/region/list?pageNum=" + currentPage + "&pageSize=" + showCount + "&type=" + type + "&str=";
        if (Tools.notEmpty(keywords)) url += keywords;
        headers.set("Authorization", getToken(CORPINFO_ID));
        HttpEntity<JSONObject> httpEntity = new HttpEntity<>(headers);
        ResponseEntity<JSONObject> exchange = restTemplate.exchange(getBakeAddr(CORPINFO_ID) + url, HttpMethod.GET, httpEntity, JSONObject.class);
        return exchange.getBody();
    }

    /**
     * @Description: 所有区域列表
     * @Param: [java.lang.String, java.lang.Integer, java.lang.Integer] [keywords, currentPage, showCount]
     * @Return: com.alibaba.fastjson.JSONObject
     */
    public static JSONObject getAreaRegionList(String CORPINFO_ID, Integer currentPage, Integer showCount) throws Exception {
        HttpHeaders headers = new HttpHeaders();

        headers.set("Authorization", getToken(CORPINFO_ID));
        HttpEntity<JSONObject> httpEntity = new HttpEntity<>(headers);
        ResponseEntity<JSONObject> exchange = restTemplate.exchange(getBakeAddr(CORPINFO_ID) + "/region/region/list?pageNum=" + currentPage + "&pageSize=" + showCount, HttpMethod.GET, httpEntity, JSONObject.class);
        return exchange.getBody();
    }

    /**
     * @Description: 电子围栏详情
     * @Param: [java.lang.String, java.lang.Integer] [CORPINFO_ID, id]
     * @Return: com.alibaba.fastjson.JSONObject
     */
    public static JSONObject getRyRegionInfo(String CORPINFO_ID, int id) throws Exception {
        HttpHeaders headers = new HttpHeaders();

        headers.set("Authorization", getToken(CORPINFO_ID));
        HttpEntity<JSONObject> httpEntity = new HttpEntity<>(headers);
        ResponseEntity<JSONObject> exchange = restTemplate.exchange(getBakeAddr(CORPINFO_ID) + "/region/region/" + id, HttpMethod.GET, httpEntity, JSONObject.class);
        return exchange.getBody();
    }

    /**
     * @Description: 电子围栏详情
     * @Param: [java.lang.String, java.lang.Integer] [CORPINFO_ID, id]
     * @Return: com.alibaba.fastjson.JSONObject
     */
    public static JSONObject getRyRegionLayerInfo(String CORPINFO_ID, int id) throws Exception {
        HttpHeaders headers = new HttpHeaders();

        headers.set("Authorization", getToken(CORPINFO_ID));
        HttpEntity<JSONObject> httpEntity = new HttpEntity<>(headers);
        ResponseEntity<JSONObject> exchange = restTemplate.exchange(getBakeAddr(CORPINFO_ID) + "/region/layer/" + id, HttpMethod.GET, httpEntity, JSONObject.class);
        return exchange.getBody();
    }

    /**
     * @Description: 获取拥有历史轨迹的全部角色
     * @Return: com.alibaba.fastjson.JSONObject
     */
    public static JSONObject getPersonnelTrajectories(String CORPINFO_ID) throws Exception {
        HttpHeaders headers = new HttpHeaders();

        headers.set("Authorization", getToken(CORPINFO_ID));
        HttpEntity<JSONObject> httpEntity = new HttpEntity<>(headers);
        ResponseEntity<JSONObject> exchange = restTemplate.exchange(getBakeAddr(CORPINFO_ID) + "/location/loca/personnelTrajectories", HttpMethod.GET, httpEntity, JSONObject.class);
        return exchange.getBody();
    }

    /**
     * @Description: 人员历史轨迹查询
     * @Return: com.alibaba.fastjson.JSONObject
     */
    public static JSONObject characterTrajectories(String CORPINFO_ID, int id, String startTime, String endTime, int type) throws Exception {

        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", getToken(CORPINFO_ID));
        headers.setContentType(org.springframework.http.MediaType.valueOf("application/json"));
        JSONObject uriVariables = new JSONObject();
        uriVariables.put("id", id);
        uriVariables.put("startTime", startTime);
        uriVariables.put("endTime", endTime);
        uriVariables.put("type", type);
        HttpEntity<JSONObject> httpEntity = new HttpEntity<>(uriVariables, headers);

        ResponseEntity<JSONObject> exchange = restTemplate.exchange(getBakeAddr(CORPINFO_ID) + "/location/loca/characterTrajectories", HttpMethod.POST, httpEntity, JSONObject.class);
        return exchange.getBody();

    }

    /**
     * @Description: 当前在线人员实时位置信息
     * @Date: 2024/1/25/025 14:37
     * @Return: com.alibaba.fastjson.JSONObject
     */
    public static JSONObject getRealTimeList(String CORPINFO_ID) throws Exception {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", getToken(CORPINFO_ID));
        HttpEntity<JSONObject> httpEntity = new HttpEntity<>(headers);
        SimpleClientHttpRequestFactory clientHttpRequestFactory = new SimpleClientHttpRequestFactory();
        clientHttpRequestFactory.setConnectTimeout(5000);
        clientHttpRequestFactory.setReadTimeout(5000);

//        ResponseEntity<JSONObject> forEntity = restTemplate.getForEntity(getBakeAddr(CORPINFO_ID) + "/location/loca", JSONObject.class);
        String path = getBakeAddr(CORPINFO_ID) + "/location/loca";
        restTemplate.setRequestFactory(clientHttpRequestFactory);
        ResponseEntity<JSONObject> exchange = restTemplate.exchange(path, HttpMethod.GET, httpEntity, JSONObject.class);
        return exchange.getBody();

    }

    /**
     * @Description: 根据定位卡号获取人是否再电子围栏里
     * @Author: dearLin
     * @Date: 2024/1/25/025 14:37
     * @Param: [java.lang.String, java.lang.Integer, java.lang.Integer] [keywords, currentPage, showCount]
     * @Return: com.alibaba.fastjson.JSONObject
     */
    public static Boolean determineWhetherThePersonIsInTheElectronicFence(String CORPINFO_ID, Integer PLS_ID, String ELECTRONIC_FENCE_ID) throws Exception {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", getToken(CORPINFO_ID));
        HttpEntity<JSONObject> httpEntity = new HttpEntity<>(headers);
        ResponseEntity<Boolean> exchange = restTemplate.exchange(getBakeAddr(CORPINFO_ID) + "/region/api/electronicFence/determineWhetherThePersonIsInTheElectronicFence2?psn=" + PLS_ID + "&id=" + ELECTRONIC_FENCE_ID, HttpMethod.GET, httpEntity, Boolean.class);
        return exchange.getBody();
    }


    private static void initBakeAddr() {
        List<PageData> dataList = null;
        try {
            dataList = corpplsinfoService.listAll(new PageData());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        dataList.forEach(item -> {
            BAKEADDR.put(item.getString("CORPINFO_ID"), item.getString("POST_URL"));
        });
    }

    private static String getBakeAddr(String CORPINFO_ID) throws Exception {
        return BAKEADDR.computeIfAbsent(CORPINFO_ID, key -> {
            initBakeAddr();
            return BAKEADDR.get(CORPINFO_ID);
        });
    }

    /**
     * @Description: 获取token
     * @Author: dearLin
     * @Date: 2024/1/24/024 9:59
     * @Param: [] []
     * @Return: java.lang.String
     */
    public static String getToken(String CORPINFO_ID) throws Exception {
        PageData pd = new PageData();
        pd.put("CORPINFO_ID", CORPINFO_ID);
        pd = corpplsinfoService.findById(pd);
        String token = pd.getString("TOKEN");
        String backAddr = pd.getString("POST_URL");
        String expireTime = pd.getString("EXPIRE_TIME");
        String userName = pd.getString("ACCOUNT");
        String passWord = pd.getString("PASSWORD");
        String loginUrl = pd.getString("POST_URL") + "/auth/login";
        if (token == null || expireTime == null || expireTime.trim().isEmpty() || DateUtil.compareDate(DateUtil.getTime(), expireTime)) {
            JSONObject loginPayload = new JSONObject();
            loginPayload.put("username", userName);
            loginPayload.put("password", passWord);
            loginPayload.put("isPresentationMode", "2");
            PageData response = sendPostHttpRequest(loginUrl, loginPayload.toJSONString(), null);
            if (response != null) {
                PageData valueData = JSONObject.parseObject(response.getString("data"), PageData.class);
                token = valueData.getString("access_token");
                String newExpireTime = DateUtil.getAfterHourDate("24");
                pd.put("TOKEN", token);
                pd.put("EXPIRE_TIME", newExpireTime);
                corpplsinfoService.edit(pd);
                return token;
            } else {
                System.out.println("登录失败");
            }
        }
        return token;
    }


    /**
     * @Description: 查询这个人的定位卡号是否存在
     * @Author: dearLin
     * @Date: 2024/1/24/024 10:00
     * @Param: [com.zcloud.entity.PageData] [user]
     * @Return: void
     */
    public static boolean hasCardNumber(PageData user) throws Exception {
        if (Tools.isEmpty(user.getString("CARDNO"))) {
            return true;
        }
        // 根据 定位卡号获取对应的人
        String url = getBakeAddr(Jurisdiction.getCORPINFO_ID()) + "/deploy/card/peopleDisplay/" + user.getString("CARDNO");
        PageData response = sendGetHttpRequest(url, null, getToken(Jurisdiction.getCORPINFO_ID()));
        if (response != null) {
            if (!"200".equals(response.getString("code"))) {
                return false;
            }
            List<PageData> dataList = JSONObject.parseArray(response.getString("data"), PageData.class);
            return dataList.isEmpty();
        }
        return false;
    }

    /**
     * @Description: 查询这个人的定位卡号是否存在
     * @Author: dearLin
     * @Date: 2024/1/24/024 10:00
     * @Param: [com.zcloud.entity.PageData] [user]
     * @Return: void
     */
    public static PageData getCardNumberPeople(PageData user) throws Exception {
        // 根据 定位卡号获取对应的人
        String url = getBakeAddr(Jurisdiction.getCORPINFO_ID()) + "/deploy/card/peopleDisplay/" + user.getString("CARDNO");
        PageData response = sendGetHttpRequest(url, null, getToken(Jurisdiction.getCORPINFO_ID()));
        if (response != null) {
            if (!"200".equals(response.getString("code"))) {
                return null;
            }
            List<PageData> dataList = JSONObject.parseArray(response.getString("data"), PageData.class);
            return dataList.size() > 0 ? dataList.get(0) : null;
        }
        return null;
    }

    /**
     * @Description: 把人新增到 人员定位系统
     * @Author: dearLin
     * @Date: 2024/1/24/024 10:00
     * @Param: [com.zcloud.entity.PageData] [user]
     * @Return: void
     */
    public static PageData saveUser(PageData user) throws Exception {
        String url = getBakeAddr(Jurisdiction.getCORPINFO_ID()) + "/deploy/psnmgt/insertPsnIfon";
        JSONObject loginPayload = new JSONObject();
        PageData dataPd = corpplsinfoService.getDeptIdandempId(user);
        // 部门id
        loginPayload.put("deptId", dataPd.getString("deptId"));
        // 公司id
        loginPayload.put("empId", dataPd.getString("enterpriseId"));
        loginPayload.put("name", user.getString("NAME"));
        loginPayload.put("cardNo", user.getString("CARDNO"));

        loginPayload.put("empNo", "");
        loginPayload.put("sex", "");
        loginPayload.put("certType", "");
        loginPayload.put("certNo", "");
        loginPayload.put("staffType", "");
        loginPayload.put("phone", "");
        loginPayload.put("officeName", user.getString("WORK_NAME"));
        loginPayload.put("office", user.getString("WORK_ID"));
        loginPayload.put("age", "");
        loginPayload.put("addr", "");
        loginPayload.put("remark", "");
        loginPayload.put("enterpriseName", "");
        loginPayload.put("jobsName", "");
        loginPayload.put("avatar", "");
        return sendPostHttpRequest(url, loginPayload.toJSONString(), getToken(Jurisdiction.getCORPINFO_ID()));

    }

    /**
     * @Description: 把人新增到 人员定位系统
     * @Author: dearLin
     * @Date: 2024/1/24/024 10:00
     * @Param: [com.zcloud.entity.PageData] [user]
     * @Return: void
     */
    public static boolean editUser(PageData user) throws Exception {
        // 这个人没有卡号与人id的话
        if (!Tools.notEmpty(user.getString("PLS_ID"))) {
            PageData response = saveUser(user);
            if ("200".equals(response.getString("code"))) {
                user.put("PLS_ID", response.getString("data"));
                return true;
            }
            return false;
        }
        String url = getBakeAddr(Jurisdiction.getCORPINFO_ID()) + "/deploy/psnmgt/updPsnInfoById";

        JSONObject loginPayload = new JSONObject();
        loginPayload.put("name", user.getString("NAME"));
        loginPayload.put("psnId", user.getString("PLS_ID"));
        loginPayload.put("cardNo", user.getString("CARDNO") == null ? "" : user.getString("CARDNO"));
        PageData dataPd = corpplsinfoService.getDeptIdandempId(user);
        // 部门id
        loginPayload.put("deptId", dataPd.getString("deptId"));
        // 公司id
        loginPayload.put("empId", dataPd.getString("enterpriseId"));
        loginPayload.put("empNo", "");
        loginPayload.put("sex", "");
        loginPayload.put("certType", "");
        loginPayload.put("certNo", "");
        loginPayload.put("staffType", "");
        loginPayload.put("phone", "");
        loginPayload.put("age", "");
        loginPayload.put("addr", "");
        loginPayload.put("remark", "");
        loginPayload.put("enterpriseName", "");
        loginPayload.put("officeName", user.getString("WORK_NAME"));
        loginPayload.put("office", user.getString("WORK_ID"));
        loginPayload.put("jobsName", "");
        loginPayload.put("deptName", "");
        loginPayload.put("avatar", "");
        PageData response = sendPostHttpRequest(url, loginPayload.toJSONString(), getToken(Jurisdiction.getCORPINFO_ID()));
        return "200".equals(response.getString("code"));
    }

    public static boolean removeUser(PageData user) throws Exception {
        String url = getBakeAddr(Jurisdiction.getCORPINFO_ID()) + "/deploy/psnmgt";
        PageData removeUser = usersService.findById(user);
        PageData response = sendDeleteHttpRequest(url, Long.parseLong(removeUser.getString("PLS_ID")), getToken(Jurisdiction.getCORPINFO_ID()));
        return "200".equals(response.getString("code"));
    }

    /**
     * 发送get类型请求
     *
     * @param url
     * @param queryParams
     * @param token
     * @return PageData
     * @throws IOException
     */

    private static PageData sendGetHttpRequest(String url, Map<String, String> queryParams, String token) throws IOException {
        OkHttpClient client = new OkHttpClient();

        HttpUrl.Builder httpBuilder = Objects.requireNonNull(HttpUrl.parse(url)).newBuilder();
        //封装请求参数
        if (queryParams != null) {
            for (Map.Entry<String, String> param : queryParams.entrySet()) {
                httpBuilder.addQueryParameter(param.getKey(), param.getValue());
            }
        }
        //设置请求的url
        Request.Builder requestBuilder = new Request.Builder().url(httpBuilder.build());

        if (token != null && !token.isEmpty()) {
            requestBuilder.addHeader("Authorization", "Bearer " + token);
        }

        Request request = requestBuilder.build();
        Response execute = client.newCall(request).execute();
        if (execute.code() != 200) {
            logger.error("get请求失败，返回状态码：{},url:{}", execute.code(), url);
            throw new RuntimeException("get请求失败");
        }
        return JSONObject.parseObject(execute.body().string(), PageData.class);
        //发送请求并返回响应数据
    }


    /**
     * 发送post类型请求
     *
     * @param url
     * @param jsonPayload
     * @param token
     * @return
     * @throws IOException
     */
    private static PageData sendPostHttpRequest(String url, String jsonPayload, String token) throws IOException {
        OkHttpClient client = new OkHttpClient();
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(JSON, jsonPayload);
        Request.Builder builder = new Request.Builder() // 构建一个新的Request对象。
                .url(url)// 设置请求的URL。
                .post(body);// 设置请求的方法为POST，并设置请求体。
        //构建请求头
        if (token != null && !token.isEmpty()) {// 检查token是否存在且不为空。
            builder.addHeader("Authorization", "Bearer " + token);
        }

        // 构建请求
        Request request = builder.build();
        Response execute = client.newCall(request).execute();
        if (execute.code() != 200) {
            logger.error("post请求失败，返回状态码：{},url:{}", execute.code(), url);
            throw new RuntimeException("get请求失败");
        }
        PageData pageData = JSONObject.parseObject(execute.body().string(), PageData.class);
        if (!"200".equals(pageData.getString("code"))) {
            logger.error("post请求失败，返回值：{},url:{}", pageData.getString("msg"), url);
        }
        return pageData;
        //发起请求并响应数据
    }

    /**
     * 发送PUT类型请求
     *
     * @param url
     * @param jsonPayload
     * @param token
     * @return
     * @throws IOException
     */
    private static Response sendPutHttpRequest(String url, String jsonPayload, String token) throws IOException {
        OkHttpClient client = new OkHttpClient();
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(JSON, jsonPayload);
        Request.Builder builder = new Request.Builder().url(url).put(body);
        if (token != null && !token.isEmpty()) {
            builder.addHeader("Authorization", "Bearer " + token);
        }
        Request request = builder.build();

        return client.newCall(request).execute();
    }

    /**
     * 发送delete类型请求
     *
     * @param url
     * @param camIds
     * @param token
     * @return
     * @throws IOException
     */
    private static PageData sendDeleteHttpRequest(String url, Long camIds, String token) throws IOException {
        OkHttpClient client = new OkHttpClient();
        //将要删除的Id列表转换为逗号分隔的字符串
        //构建完整的url
        url = url + "/" + camIds;

        Request.Builder builderBuilder = new Request.Builder().url(url).delete();

        if (token != null && !token.isEmpty()) {
            builderBuilder.addHeader("Authorization", "Bearer " + token);
        }

        Request request = builderBuilder.build();
        Response execute = client.newCall(request).execute();
        if (execute.code() != 200) {
            logger.error("post请求失败，返回状态码：{},url:{}", execute.code(), url);
            throw new RuntimeException("get请求失败");
        }
        PageData pageData = JSONObject.parseObject(execute.body().string(), PageData.class);
        if (!"200".equals(pageData.getString("code"))) {
            logger.error("post请求失败，返回值：{},url:{}", pageData.getString("msg"), url);
        }
        return pageData;
    }

    public static String buildGetParams(Map<String, Object> params) throws Exception {
        StringBuilder sb = new StringBuilder();
        sb.append("?");
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            if (sb.length() > 1) {
                sb.append("&");
            }
            String key = entry.getKey();
            if ("currentPage".equals(entry.getKey())) key = "pageNum";
            if ("showCount".equals(entry.getKey())) key = "pageSize";
            sb.append(URLEncoder.encode(key, StandardCharsets.UTF_8.toString()));
            sb.append("=");
            sb.append(entry.getValue());
        }
        return sb.toString();
    }

    /**
     * 获取区域内随机坐标点
     *
     * @param polygon [[lng,lat,alt],[lng,lat,alt],[lng,lat,alt],...]
     * @return [lng, lat, alt]
     * @throws IOException
     */
    public static List<String> getRandomPointInPolygon(List<List<Double>> polygon) {
        double minX = Double.POSITIVE_INFINITY;
        double minY = Double.POSITIVE_INFINITY;
        double maxX = Double.NEGATIVE_INFINITY;
        double maxY = Double.NEGATIVE_INFINITY;

        for (List<Double> point : polygon) {
            minX = Math.min(minX, point.get(0));
            minY = Math.min(minY, point.get(1));
            maxX = Math.max(maxX, point.get(0));
            maxY = Math.max(maxY, point.get(1));
        }

        Random rand = new Random();
        while (true) {
            Double x = minX + rand.nextDouble() * (maxX - minX);
            Double y = minY + rand.nextDouble() * (maxY - minY);

            if (pointInPolygon(polygon, x, y)) {
                List<String> point = Arrays.asList(x.toString(), y.toString(), polygon.get(0).get(2).toString());
                return point;
            }
        }
    }

    /**
     * 判断点是否在多边形内
     *
     * @param polygon
     * @param lng
     * @param lat
     * @return
     */
    private static boolean pointInPolygon(List<List<Double>> polygon, double lng, double lat) {
        boolean inside = false;
        int n = polygon.size();
        for (int i = 0, j = n - 1; i < n; j = i++) {
            if (((polygon.get(i).get(1) > lat) != (polygon.get(j).get(1) > lat)) && (lng < (polygon.get(j).get(0) - polygon.get(i).get(0)) * (lat - polygon.get(i).get(1)) / (polygon.get(j).get(1) - polygon.get(i).get(1)) + polygon.get(i).get(0))) {
                inside = !inside;
            }
        }
        return inside;
    }

    public static boolean checkWebSiteStatus(PageData pd) {
        try {
            String userName = pd.getString("ACCOUNT");
            String passWord = pd.getString("PASSWORD");
            String loginUrl = pd.getString("POST_URL") + "/auth/login";
            JSONObject loginPayload = new JSONObject();
            loginPayload.put("username", userName);
            loginPayload.put("password", passWord);
            loginPayload.put("isPresentationMode", "2");
            sendPostHttpRequest(loginUrl, loginPayload.toJSONString(), null);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
