package com.zcloud.controller.mapApi;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zcloud.controller.base.BaseController;
import com.zcloud.entity.Page;
import com.zcloud.entity.PageData;
import com.zcloud.service.eightwork.ConfinedspaceService;
import com.zcloud.service.eightwork.EightWorkService;
import com.zcloud.service.eightwork.HighworkService;
import com.zcloud.service.eightwork.HotworkService;
import com.zcloud.service.integratedmanagement.access.GateEntryExitService;
import com.zcloud.service.system.UsersService;
import com.zcloud.service.video.VideoManagerService;
import com.zcloud.util.DateUtil;
import com.zcloud.util.Jurisdiction;
import com.zcloud.util.PLSUtil;
import com.zcloud.util.ReturnMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.file.Files;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 说明：TODO
 * 作者：wangxuan
 * 官网：www.zcloudchina.com
 */
@Controller
@RequestMapping("/map")
public class MapController extends BaseController {
    @Autowired
    private UsersService usersService;
    @Autowired
    private EightWorkService eightWorkService;
    @Autowired
    private VideoManagerService videomanagerService;
    @Autowired
    private HotworkService hotworkService;
    @Autowired
    private ConfinedspaceService confinedspaceService;
    @Autowired
    private HighworkService highworkService;

    @Resource
    private GateEntryExitService gateEntryExitService;

    /**
     * @Description: 地图上进出闸机
     * @Author: dearLin
     * @Date: 2024/1/26/026 16:42
     * @Param: [] []
     * @Return: java.lang.String
     */
    @RequestMapping(value = "/getGateMachineList")
    @ResponseBody
    public ReturnMap getGateMachineList() throws Exception {
        PageData pageData = getPageData();
        pageData.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
        List<PageData> varList = gateEntryExitService.getGateMachineList(pageData);
        return ReturnMap.ok().put("varList", varList);
    }
// ----------人员定位相关-------------//

    /**
     * @Description: 人员类型统计 告警类型统计
     * @Author: dearLin
     * @Date: 2024/1/26/026 16:42
     * @Param: [] []
     * @Return: java.lang.String
     */
    @RequestMapping(value = "/getPersonnelTypeCount")
    @ResponseBody
    public ReturnMap getPersonnelTypeCount() throws Exception {
        PageData pageData = getPageData();
        pageData.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
        int userCount = usersService.getUserCount(pageData);
        return ReturnMap.ok().put("userCount", userCount);
    }

    /**
     * @Description: 告警类型统计 来自人员定位系统
     * @Author: dearLin
     * @Date: 2024/1/26/026 16:43
     * @Param: [] []
     * @Return: com.zcloud.util.ReturnMap
     */
    @RequestMapping(value = "/getAlarmTypeCount")
    @ResponseBody
    public ReturnMap getAlarmTypeCount() throws Exception {
        return ReturnMap.ok().put("data", PLSUtil.getAlarmTypeCount(Jurisdiction.getCORPINFO_ID()));
    }

    /**
     * @Description: 告警数据 来自人员定位系统
     * @Author: dearLin
     * @Date: 2024/1/26/026 16:43
     * @Param: [] []
     * @Return: com.zcloud.util.ReturnMap
     */
    @RequestMapping(value = "/getAlArmDataList")
    @ResponseBody
    public ReturnMap getAlArmDataList(Page page) throws Exception {
        PageData pageData = this.getPageData();
        ReturnMap returnMap = new ReturnMap();
        JSONObject body = PLSUtil.getAlArmDataList(
                Jurisdiction.getCORPINFO_ID(),
                page.getCurrentPage() + 1, page.getShowCount(),
                "",
                Integer.parseInt(pageData.getString("status")),
                Integer.parseInt(pageData.getString("eleType"))
        );
        if (body != null) {
            List<JSONObject> list = body.getJSONArray("rows").toJavaList(JSONObject.class);
            returnMap.put("varList", list);
            page.setTotalResult(body.getIntValue("total"));
            returnMap.put("page", page);
        }
        return returnMap;
    }

    /**
     * @Description: 人员定位情况 来自人员定位系统
     * @Author: dearLin
     * @Date: 2024/1/26/026 16:43
     * @Param: [] []
     * @Return: com.zcloud.util.ReturnMap
     */
    @RequestMapping(value = "/getPersonnelPositioningCount")
    @ResponseBody
    public ReturnMap getPersonnelPositioningCount(Page page) throws Exception {
        JSONObject personnelPositioningCount = PLSUtil.getPersonnelPositioningCount(Jurisdiction.getCORPINFO_ID(), page.getCurrentPage(), page.getShowCount());
        return ReturnMap.ok().put("data", personnelPositioningCount);
    }

    /**
     * @Description: 当前在线人员实时位置信息
     * @Param: [] []
     * @Return: com.zcloud.util.ReturnMap
     */
    @RequestMapping(value = "/getRealTimeList")
    @ResponseBody
    public ReturnMap getRealTimeList() throws Exception {
        return ReturnMap.ok().put("data", PLSUtil.getRealTimeList(Jurisdiction.getCORPINFO_ID()));
//        return ReturnMap.ok();
    }

    @RequestMapping(value = "/getSceneJson")
    @ResponseBody
    public ReturnMap getSceneJson() throws Exception {
        return ReturnMap.ok().put("data", PLSUtil.getSceneJson(Jurisdiction.getCORPINFO_ID()));
    }


    /**
     * @Description: 电子围栏信息
     * @Param: [] []
     * @Return: com.zcloud.util.ReturnMap
     */
    @RequestMapping(value = "/getFenceList")
    @ResponseBody
    public ReturnMap getFenceList() throws Exception {
        PageData pd = this.getPageData();
        return ReturnMap.ok().put("data", PLSUtil.getRyRegionList(Jurisdiction.getCORPINFO_ID(), "", 1, 999999, Integer.parseInt(pd.getString("type"))));
    }

    /**
     * @Description: 电子围栏信息
     * @Param: [] []
     * @Return: com.zcloud.util.ReturnMap
     */
    @RequestMapping(value = "/getFenceListInfo")
    @ResponseBody
    public ReturnMap getFenceListInfo() throws Exception {
        PageData pageData = this.getPageData();
        return ReturnMap.ok().put("data", PLSUtil.getRyRegionInfo(Jurisdiction.getCORPINFO_ID(), Integer.parseInt(pageData.getString("id"))));
    }

    /**
     * @Description: 电子围栏信息
     * @Param: [] []
     * @Return: com.zcloud.util.ReturnMap
     */
    @RequestMapping(value = "/getLayerListInfo")
    @ResponseBody
    public ReturnMap getLayerListInfo() throws Exception {
        PageData pageData = this.getPageData();
        return ReturnMap.ok().put("data", PLSUtil.getRyRegionLayerInfo(Jurisdiction.getCORPINFO_ID(), Integer.parseInt(pageData.getString("id"))));
    }

    /**
     * @Description: 获取八项作业数
     * @Param: [] []
     * @Return: com.zcloud.util.ReturnMap
     */
    @RequestMapping(value = "/getEightWorks")
    @ResponseBody
    public ReturnMap getEightWorks() throws Exception {
        return eightWorkService.getEightWorks();
    }

    /**
     * @Description: 获取八项作业数
     * @Param: [] []
     * @Return: com.zcloud.util.ReturnMap
     */
    @RequestMapping(value = "/getEightWorksByType")
    @ResponseBody
    public ReturnMap getEightWorksByType() throws Exception {
        PageData pageData = this.getPageData();
        pageData.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
        return ReturnMap.ok().put("varList", eightWorkService.getEightWorksByType(pageData));
    }

    /**
     * @Description: 获取动火作业
     * @Param: [] []
     * @Return: com.zcloud.util.ReturnMap
     */
    @RequestMapping(value = "/getHotworkList")
    @ResponseBody
    public ReturnMap getHotworkList() throws Exception {
        return hotworkService.getMapList();
    }

    /**
     * @Description: 获取受限空间作业
     * @Param: [] []
     * @Return: com.zcloud.util.ReturnMap
     */
    @RequestMapping(value = "/getConfinedspaceWorkList")
    @ResponseBody
    public ReturnMap getConfinedspaceWorkList() throws Exception {
        return confinedspaceService.getMapList();
    }

    /**
     * @Description: 获取高处作业
     * @Param: [] []
     * @Return: com.zcloud.util.ReturnMap
     */
    @RequestMapping(value = "/getHighWorkList")
    @ResponseBody
    public ReturnMap getHighWorkList() throws Exception {
        return highworkService.getMapList();
    }

    // ----------摄像头相关-------------//

    // 摄像头告警数 disposed
    @RequestMapping(value = "/getCameraTopToShow")
    @ResponseBody
    public ReturnMap getCameraTopToShow() {
        PageData pageData = getPageData();
        pageData.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
        PageData cameraCount = videomanagerService.getCameraTopToShow(pageData);
        return ReturnMap.ok().put("pd", cameraCount);
    }

    /**
     * @Description: 摄像头告警数
     * @Author: dearLin
     * @Date: 2024/1/29/029 15:35
     * @Param: [] []
     * @Return: com.zcloud.util.ReturnMap
     */
    @RequestMapping(value = "/getCameraAlarmCount")
    @ResponseBody
    public ReturnMap getCameraAlarmCount() {
        PageData pageData = getPageData();
        pageData.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
        List<PageData> cameraCount = videomanagerService.getCameraAlarmCount(pageData);
        return ReturnMap.ok().put("CameraAlarmCount", cameraCount);
    }

    /**
     * @Description: 摄像头报警类型
     * @Author: dearLin
     * @Date: 2024/1/29/029 10:52
     * @Param: [] []
     * @Return: com.zcloud.util.ReturnMap
     */
    @RequestMapping(value = "/getCameraAlarmTypeCount")
    @ResponseBody
    public ReturnMap getCameraAlarmTypeCount() {
        PageData pageData = getPageData();
        pageData.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
        List<PageData> cameraCount = videomanagerService.getCameraAlarmTypeCount(pageData);
        return ReturnMap.ok().put("varList", cameraCount);
    }

    /**
     * @Description: 摄像头告警时间趋势
     * @Author: dearLin
     * @Date: 2024/1/29/029 10:51
     * @Param: [] []
     * @Return: com.zcloud.util.ReturnMap
     */
    @RequestMapping(value = "/getCameraAlarmTimeCount")
    @ResponseBody
    public ReturnMap getCameraAlarmTimeCount() throws Exception {
        PageData pageData = getPageData();
        pageData.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
        List<Map<String, String>> generateTimeArraySevenMonth = DateUtil.generateTimeArraySevenMonth(6);
        pageData.put("generateTimeArray", generateTimeArraySevenMonth);
        return ReturnMap.ok().put("varList", videomanagerService.getCameraAlarmTimeCount(pageData));
    }

    /**
     * @Description: 摄像头告警来源
     * @Author: dearLin
     * @Date: 2024/1/29/029 10:51
     * @Param: [] []
     * @Return: com.zcloud.util.ReturnMap
     */
    @RequestMapping(value = "/getCameraAlarmSourceCount")
    @ResponseBody
    public ReturnMap getCameraAlarmSourceCount() throws Exception {
        PageData pageData = getPageData();
        pageData.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
        int cameraCount = usersService.getUserCount(pageData);
        return ReturnMap.ok().put("cameraCount", cameraCount);
    }

    /**
     * @Description: 获取轨迹
     * @Param: [] []
     * @Return: com.zcloud.util.ReturnMap
     */
    @RequestMapping(value = "/getCharacterTrajectories")
    @ResponseBody
    public ReturnMap getCharacterTrajectories() throws Exception {
        PageData pageData = getPageData();
        return ReturnMap.ok().put("data", PLSUtil.characterTrajectories(Jurisdiction.getCORPINFO_ID(), Integer.parseInt(pageData.getString("id")),
                pageData.getString("startTime"), pageData.getString("endTime"), Integer.parseInt(pageData.getString("type"))));
    }

    /**
     * @Description: 获取拥有历史轨迹的全部角色
     * @Param: [] []
     * @Return: com.zcloud.util.ReturnMap
     */
    @RequestMapping(value = "/getPersonnelTrajectories")
    @ResponseBody
    public ReturnMap getPersonnelTrajectories() throws Exception {
        return ReturnMap.ok().put("data", PLSUtil.getPersonnelTrajectories(Jurisdiction.getCORPINFO_ID()));
    }
    // -----------------------//

    public static List<Map<String, String>> generateTimeArray() {
        List<Map<String, String>> timeArray = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();

        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        for (int i = 6; i >= 0; i--) {
            Map<String, String> monthInfo = new HashMap<>();

            int year = calendar.get(Calendar.YEAR);
            int month = calendar.get(Calendar.MONTH) + 1;

            String monthString = String.format(year + "-%02d", month);
            String firstDayOfMonth = String.format("%04d-%02d-01 00:00:00", year, month);
            calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
            calendar.set(Calendar.HOUR_OF_DAY, 23);
            calendar.set(Calendar.MINUTE, 59);
            calendar.set(Calendar.SECOND, 59);
            String lastDayOfMonth = dateFormat.format(calendar.getTime());

            monthInfo.put("month", monthString);
            monthInfo.put("dateBegin", firstDayOfMonth);
            monthInfo.put("dateEnd", lastDayOfMonth);

            timeArray.add(monthInfo);

            calendar.add(Calendar.MONTH, -1); // Go to the previous month
        }

        // Reverse the timeArray to have the order from past to present
        Collections.reverse(timeArray);

        return timeArray;
    }

    /**
     * @Description: 地图获取摄像头
     * @Author: dearLin
     * @Date: 2024/2/1/001 15:43
     * @Param: [] []
     * @Return: java.lang.Object
     */
    @RequestMapping(value = "/getCameraList")
    @ResponseBody
    public Object getCameraList() throws Exception {
        return ReturnMap.ok().put("varList", videomanagerService.getCameraList(getPageData()));
    }


    /**
     * @Description: 汇博石油计算电子围栏里人员数
     * @Author: dearLin
     * @Date: 2024/2/1/001 15:43
     * @Param: [] []
     * @Return: java.lang.Object
     */
    @RequestMapping(value = "/getElectronicFencePerCount")
    @ResponseBody
    public Object getElectronicFencePerCount() throws Exception {
        PageData pageData = this.getPageData();
        String corpinfo_id = Jurisdiction.getCORPINFO_ID();
        pageData.put("CORPINFO_ID", corpinfo_id);
        // 有表 district
        return ReturnMap.ok().put("insidePeopleNumber", PLSUtil.getPsnByRegionName(corpinfo_id, "二道门内"));
    }

    /**
     * @Description: 一键处理 处置方式
     * @Author: dearLin
     * @Date: 2024/2/1/001 15:43
     * @Param: [] []
     * @Return: java.lang.Object
     */




}
