package com.yeejoin.equipmanage.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.equipmanage.common.utils.*;
import com.yeejoin.equipmanage.fegin.IotFeign;
import com.yeejoin.equipmanage.mapper.FireFightingSystemMapper;
import com.yeejoin.equipmanage.service.IEquipmentSpecificAlarmService;
import com.yeejoin.equipmanage.service.IFireFightingSystemService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

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

@RestController
@Api(tags = "组态需求 -- API")
@RequestMapping(value = "/configure", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class ConfigureController extends AbstractBaseController {


    @Autowired
    private FireFightingSystemMapper fireFightingSystemMapper;

    @Autowired
    private IEquipmentSpecificAlarmService equipmentSpecificAlarmService;

    @Autowired
    private IFireFightingSystemService iFireFightingSystemService;

    @Autowired
    private IotFeign iotFeign;

    @RequestMapping(value = "/alarmLogPage", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "列表分页查询", produces = "application/json;charset=UTF-8", notes = "列表分页查询")
    public ResponseModel pageQuery(@RequestParam(required = false) String system, CommonPageable commonPageable) {
        if (commonPageable.getPageNumber() == 0) {
            commonPageable.setPageNumber(1);
        }
        ReginParams reginParams = getSelectedOrgInfo();
        List<CommonRequest> queryRequests = new ArrayList<>();
        CommonRequest request7 = new CommonRequest();
        request7.setName("system");
        request7.setValue(StringUtil.isNotEmpty(system) ? StringUtils.trimToNull(system) : null);
        queryRequests.add(request7);
        if (!ValidationUtil.isEmpty(reginParams.getPersonIdentity())) {
            CommonRequest request13 = new CommonRequest();
            request13.setName("bizOrgCode");
            request13.setValue(StringUtil.isNotEmpty(reginParams.getPersonIdentity().getBizOrgCode()) ? reginParams.getPersonIdentity().getBizOrgCode() : null);
            queryRequests.add(request13);
        }
        CommonPageInfoParam param = CommonPageParamUtil.fillCommonPageInfoParam(queryRequests, commonPageable);
        Page<Map<String, Object>> list = equipmentSpecificAlarmService.pageQuery(param);
        return CommonResponseUtil.success(list);
    }

    @RequestMapping(value = "/equipStatusCount", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "系统设备状态统计", produces = "application/json;charset=UTF-8", notes = "系统设备状态统计")
    public ResponseModel equipStatusCount(@RequestParam(required = false) String systemCode) {
        HashMap<String, Object> hashMap = new HashMap<>();
        ReginParams reginParams = getSelectedOrgInfo();
        ReginParams.PersonIdentity personIdentity = reginParams.getPersonIdentity();
        if (!ValidationUtil.isEmpty(personIdentity)) {
            String bizOrgCode = personIdentity.getBizOrgCode();
            if (StringUtils.isNotBlank(bizOrgCode)) {
                hashMap.put("bizOrgCode", bizOrgCode);
            }
        }
        if (StringUtils.isNotBlank(systemCode)) {
            hashMap.put("systemCode", systemCode);
        }
        return CommonResponseUtil.success(equipmentSpecificAlarmService.equipStatusCount(hashMap));
    }

    @RequestMapping(value = "/equipAlarmLine", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "系统近一周告警趋势图", produces = "application/json;charset=UTF-8", notes = "系统近一周告警趋势图")
    public ResponseModel equipAlarmLine(@RequestParam(required = false) String systemCode, @RequestParam(required = false) String indexKeys) {
        HashMap<String, Object> hashMap = new HashMap<>();
        ReginParams reginParams = getSelectedOrgInfo();
        ReginParams.PersonIdentity personIdentity = reginParams.getPersonIdentity();
        if (!ValidationUtil.isEmpty(personIdentity)) {
            String bizOrgCode = personIdentity.getBizOrgCode();
            if (StringUtils.isNotBlank(bizOrgCode)) {
                hashMap.put("bizOrgCode", bizOrgCode);
            }
        }
        if (StringUtils.isNotBlank(systemCode)) {
            hashMap.put("systemCode", systemCode);
        }
        if (StringUtils.isNotBlank(indexKeys)) {
            hashMap.put("indexKeys", indexKeys.split(","));
        }
        return CommonResponseUtil.success(equipmentSpecificAlarmService.equipAlarmLine(hashMap));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "获取系统告警信息")
    @GetMapping("/getSystemAlarmInfo")
    public ResponseModel getSystemAlarmInfo(CommonPageable commonPageable) {
        if (commonPageable.getPageNumber() == 0) {
            commonPageable.setPageNumber(1);
        }
        ReginParams reginParams = getSelectedOrgInfo();
        String bizOrgCode = !ValidationUtil.isEmpty(reginParams.getPersonIdentity()) && StringUtil.isNotEmpty(reginParams.getPersonIdentity().getBizOrgCode()) ? reginParams.getPersonIdentity().getBizOrgCode() : null;
        if (StringUtils.isEmpty(bizOrgCode)) {
            return CommonResponseUtil.success(null);
        }
        Page page = new Page<>(commonPageable.getPageNumber(), commonPageable.getPageSize());
        return CommonResponseUtil.success(fireFightingSystemMapper.getSystemAlarmInfo(page, bizOrgCode));
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "获取设备告警待确认和未处理信息（根据系统编码查询）")
    @GetMapping("/getEquipAlarmInfoNum")
    public ResponseModel getEquipAlarmInfoNum(@RequestParam(required = false) String systemCode) {
        ReginParams reginParams = getSelectedOrgInfo();
        String bizOrgCode = !ValidationUtil.isEmpty(reginParams.getPersonIdentity()) && StringUtil.isNotEmpty(reginParams.getPersonIdentity().getBizOrgCode()) ? reginParams.getPersonIdentity().getBizOrgCode() : null;
        return CommonResponseUtil.success(fireFightingSystemMapper.getEquipAlarmInfoNum(systemCode, bizOrgCode));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "获取消防力量信息（队伍值班等(专职)）")
    @GetMapping("/getFireTeamInfoBy116")
    public ResponseModel getFireTeamInfoBy116() {
        ReginParams reginParams = getSelectedOrgInfo();
        String bizOrgCode = !ValidationUtil.isEmpty(reginParams.getPersonIdentity()) && StringUtil.isNotEmpty(reginParams.getPersonIdentity().getBizOrgCode()) ? reginParams.getPersonIdentity().getBizOrgCode() : null;
        return CommonResponseUtil.success(fireFightingSystemMapper.getFireTeamInfoBy116(bizOrgCode));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "获取消防力量信息（队伍值班等(志愿消防队)）")
    @GetMapping("/getFireTeamInfoBy117")
    public ResponseModel getFireTeamInfoBy117() {
        ReginParams reginParams = getSelectedOrgInfo();
        String bizOrgCode = !ValidationUtil.isEmpty(reginParams.getPersonIdentity()) && StringUtil.isNotEmpty(reginParams.getPersonIdentity().getBizOrgCode()) ? reginParams.getPersonIdentity().getBizOrgCode() : null;
        return CommonResponseUtil.success(fireFightingSystemMapper.getFireTeamInfoBy117(bizOrgCode));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "消防车辆信息")
    @GetMapping("/getFireCarInfo")
    public ResponseModel getFireCarInfo() {
        ReginParams reginParams = getSelectedOrgInfo();
        String bizOrgCode = !ValidationUtil.isEmpty(reginParams.getPersonIdentity()) && StringUtil.isNotEmpty(reginParams.getPersonIdentity().getBizOrgCode()) ? reginParams.getPersonIdentity().getBizOrgCode() : null;
        return CommonResponseUtil.success(fireFightingSystemMapper.getFireCarInfo(bizOrgCode));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "物联监控页面消防车辆信息")
    @GetMapping("/getFireCarInfoByWL")
    public ResponseModel getFireCarInfoByWL(CommonPageable commonPageable) {
        if (commonPageable.getPageNumber() == 0) {
            commonPageable.setPageNumber(1);
        }
        ReginParams reginParams = getSelectedOrgInfo();
        String bizOrgCode = !ValidationUtil.isEmpty(reginParams.getPersonIdentity()) && StringUtil.isNotEmpty(reginParams.getPersonIdentity().getBizOrgCode()) ? reginParams.getPersonIdentity().getBizOrgCode() : null;
        if (StringUtils.isEmpty(bizOrgCode)) {
            return CommonResponseUtil.success(null);
        }
        Page page = new Page<>(commonPageable.getPageNumber(), commonPageable.getPageSize());
        return CommonResponseUtil.success(fireFightingSystemMapper.getFireCarInfoByWL(page, bizOrgCode));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "概览水源信息")
    @GetMapping("/getWaterInfo")
    public ResponseModel getWaterInfo(CommonPageable commonPageable) {
        if (commonPageable.getPageNumber() == 0) {
            commonPageable.setPageNumber(1);
        }
        ReginParams reginParams = getSelectedOrgInfo();
        String bizOrgCode = !ValidationUtil.isEmpty(reginParams.getPersonIdentity()) && StringUtil.isNotEmpty(reginParams.getPersonIdentity().getBizOrgCode()) ? reginParams.getPersonIdentity().getBizOrgCode() : null;
        Page page = new Page<>(commonPageable.getPageNumber(), commonPageable.getPageSize());
        return CommonResponseUtil.success(fireFightingSystemMapper.getWaterInfo(page, bizOrgCode, null));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "概览稳压泵信息")
    @GetMapping("/getPressurePumpInfo")
    public ResponseModel getPressurePumpInfo(CommonPageable commonPageable) {
        if (commonPageable.getPageNumber() == 0) {
            commonPageable.setPageNumber(1);
        }
        ReginParams reginParams = getSelectedOrgInfo();
        String bizOrgCode = !ValidationUtil.isEmpty(reginParams.getPersonIdentity()) && StringUtil.isNotEmpty(reginParams.getPersonIdentity().getBizOrgCode()) ? reginParams.getPersonIdentity().getBizOrgCode() : null;
        Page page = new Page<>(commonPageable.getPageNumber(), commonPageable.getPageSize());
        if (StringUtils.isEmpty(bizOrgCode)) {
            return CommonResponseUtil.success(null);
        }
        Page<Map<String, Object>> pressurePumpInfo = fireFightingSystemMapper.getPressurePumpInfo(page, bizOrgCode, null);
        pressurePumpInfo.getRecords().stream().map(item -> {
            item.put("startAndStopNum", 0);
            item.put("update_time", "未知");
            item.put("equipment_index_name", "未知");
            String prefix = null;
            String suffix = null;
            String iotCode = item.get("iot_code").toString();
            if (iotCode.length() > 8) {
                prefix = iotCode.substring(0, 8);
                suffix = iotCode.substring(8);
            } else {
                throw new BadRequest("装备物联编码错误，请确认！");
            }

            String nowStrLong = DateUtils.getNowStrLong();
            Date startDate = DateUtils.dateAddMinutes(null, -4);
            String startDateStr = DateUtils.convertDateToString(startDate, DateUtils.DATE_TIME_PATTERN);
            ResponseModel entity1 = null;
            ResponseModel entity2 = null;
            try {
                entity1 = iotFeign.selectList(getAppKey(), getProduct(), getToken(), startDateStr, nowStrLong, prefix, suffix, "FHS_PressurePump_Start");
                entity2 = iotFeign.selectList(getAppKey(), getProduct(), getToken(), startDateStr, nowStrLong, prefix, suffix, "FHS_PressurePump_Stop");
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (200 == entity1.getStatus() && !ObjectUtils.isEmpty(entity1.getResult()) &&
                    200 == entity2.getStatus() && !ObjectUtils.isEmpty(entity2.getResult())) {
                String json1 = JSON.toJSONString(entity1.getResult());
                List<Map<String, String>> listObject1 = (List<Map<String, String>>) JSONArray.parse(json1);
                String json2 = JSON.toJSONString(entity1.getResult());
                List<Map<String, String>> listObject2 = (List<Map<String, String>>) JSONArray.parse(json2);
                int num = listObject1.size() + listObject2.size();
                item.put("startAndStopNum", num);
            }
            item.put("stateDesc", (Integer) item.get("startAndStopNum") <= 1 ? "正常" : "异常");
            item.put("normalNum", (Integer) item.get("startAndStopNum") <= 1 ? 1 : 0);
            item.put("unNormalNum", (Integer) item.get("startAndStopNum") <= 1 ? 0 : 1);
            Map<String, String> stateMap = fireFightingSystemMapper.queryPressureNowStateBySpecificId((Long) item.get("id"));
            if (!ObjectUtils.isEmpty(stateMap) && stateMap.containsKey("update_date") && stateMap.containsKey("equipment_index_name")) {
                item.put("update_time", stateMap.get("update"));
                item.put("equipment_index_name", stateMap.get("equipment_index_name"));
            }
            return item;
        }).collect(Collectors.toList());
        return CommonResponseUtil.success(pressurePumpInfo);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "消防给水3小稳压泵信息")
    @GetMapping("/getPressurePumpInfo3Small")
    public ResponseModel getPressurePumpInfo3Small() {
        ReginParams reginParams = getSelectedOrgInfo();
        String bizOrgCode = !ValidationUtil.isEmpty(reginParams.getPersonIdentity()) && StringUtil.isNotEmpty(reginParams.getPersonIdentity().getBizOrgCode()) ? reginParams.getPersonIdentity().getBizOrgCode() : null;
        List<Map<String, Object>> pressurePumpInfo = fireFightingSystemMapper.getPressurePumpInfo3Small(bizOrgCode, null);
        Map<String, Integer> resultMap = new HashMap<>();
        resultMap.put("total", pressurePumpInfo.size());
        resultMap.put("normalNum", 0);
        resultMap.put("unNormalNum", 0);

        pressurePumpInfo.stream().map(item -> {
            item.put("startAndStopNum", 0);
            item.put("update_time", "未知");
            item.put("equipment_index_name", "未知");
            String prefix = null;
            String suffix = null;
            String iotCode = item.get("iot_code").toString();
            if (iotCode.length() > 8) {
                prefix = iotCode.substring(0, 8);
                suffix = iotCode.substring(8);
            } else {
                throw new BadRequest("装备物联编码错误，请确认！");
            }

            String nowStrLong = DateUtils.getNowStrLong();
            Date startDate = DateUtils.dateAddMinutes(null, -4);
            String startDateStr = DateUtils.convertDateToString(startDate, DateUtils.DATE_TIME_PATTERN);
            ResponseModel entity1 = null;
            ResponseModel entity2 = null;
            try {
                entity1 = iotFeign.selectList(getAppKey(), getProduct(), getToken(), startDateStr, nowStrLong, prefix, suffix, "FHS_PressurePump_Start");
                entity2 = iotFeign.selectList(getAppKey(), getProduct(), getToken(), startDateStr, nowStrLong, prefix, suffix, "FHS_PressurePump_Stop");
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (200 == entity1.getStatus() && !ObjectUtils.isEmpty(entity1.getResult()) &&
                    200 == entity2.getStatus() && !ObjectUtils.isEmpty(entity2.getResult())) {
                String json1 = JSON.toJSONString(entity1.getResult());
                List<Map<String, String>> listObject1 = (List<Map<String, String>>) JSONArray.parse(json1);
                String json2 = JSON.toJSONString(entity1.getResult());
                List<Map<String, String>> listObject2 = (List<Map<String, String>>) JSONArray.parse(json2);
                int num = listObject1.size() + listObject2.size();
                item.put("startAndStopNum", num);
            }
            item.put("stateDesc", (Integer) item.get("startAndStopNum") <= 1 ? "正常" : "异常");
            resultMap.put("normalNum", (Integer) item.get("startAndStopNum") <= 1 ? (resultMap.get("normalNum") + 1) : resultMap.get("normalNum"));
            resultMap.put("unNormalNum",  (Integer) item.get("startAndStopNum") > 1 ? (resultMap.get("unNormalNum") + 1) : resultMap.get("unNormalNum"));
            item.put("normalNum", (Integer) item.get("startAndStopNum") <= 1 ? 1 : 0);
            item.put("unNormalNum", (Integer) item.get("startAndStopNum") <= 1 ? 0 : 1);
            Map<String, String> stateMap = fireFightingSystemMapper.queryPressureNowStateBySpecificId((Long) item.get("id"));
            if (!ObjectUtils.isEmpty(stateMap) && stateMap.containsKey("update_date") && stateMap.containsKey("equipment_index_name")) {
                item.put("update_time", stateMap.get("update"));
                item.put("equipment_index_name", stateMap.get("equipment_index_name"));
            }
            return item;
        }).collect(Collectors.toList());
        return CommonResponseUtil.success(resultMap);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "3小水源信息")
    @GetMapping("/getSmallWaterInfo")
    public ResponseModel getSmallWaterInfo(@RequestParam(required = false) String systemCode, CommonPageable commonPageable) {
        if (commonPageable.getPageNumber() == 0) {
            commonPageable.setPageNumber(1);
        }
        HashMap<String, Object> hashMap = new HashMap<>();
        ReginParams reginParams = getSelectedOrgInfo();
        ReginParams.PersonIdentity personIdentity = reginParams.getPersonIdentity();
        if (!ValidationUtil.isEmpty(personIdentity)) {
            String bizOrgCode = personIdentity.getBizOrgCode();
            if (StringUtils.isNotBlank(bizOrgCode)) {
                hashMap.put("bizOrgCode", bizOrgCode);
            }
            if (bizOrgCode == null) {
                return CommonResponseUtil.success(null);
            }
        }
        if (StringUtils.isNotBlank(systemCode)) {
            hashMap.put("systemCode", systemCode);

        }
        Page page = new Page<>(commonPageable.getPageNumber(), commonPageable.getPageSize());
        return CommonResponseUtil.success(iFireFightingSystemService.getSmallWaterInfo(page, hashMap));
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @ApiOperation(value = "获取系统名称（根据系统编码查询）")
    @GetMapping("/getSystemName")
    public ResponseModel getEquipSystemName(@RequestParam(required = false) String systemCode) {
        HashMap<String, Object> hashMap = new HashMap<>();
        ReginParams reginParams = getSelectedOrgInfo();
        ReginParams.PersonIdentity personIdentity = reginParams.getPersonIdentity();
        if (!ValidationUtil.isEmpty(personIdentity)) {
            String bizOrgCode = personIdentity.getBizOrgCode();
            if (StringUtils.isNotBlank(bizOrgCode)) {
                hashMap.put("bizOrgCode", bizOrgCode);
            }
            if (bizOrgCode == null) {
                return CommonResponseUtil.success(null);
            }
        }
        if (StringUtils.isNotBlank(systemCode)) {
            hashMap.put("systemCode", systemCode);
        }
        return CommonResponseUtil.success(iFireFightingSystemService.getSystemName(hashMap));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @ApiOperation(value = "获取系统工作状态（根据系统编码查询）")
    @GetMapping("/getSystemStatus")
    public ResponseModel getEquipSystemStatus(@RequestParam(required = false) String systemCode) {
        HashMap<String, Object> hashMap = new HashMap<>();
        ReginParams reginParams = getSelectedOrgInfo();
        ReginParams.PersonIdentity personIdentity = reginParams.getPersonIdentity();
        if (!ValidationUtil.isEmpty(personIdentity)) {
            String bizOrgCode = personIdentity.getBizOrgCode();
            if (StringUtils.isNotBlank(bizOrgCode)) {
                hashMap.put("bizOrgCode", bizOrgCode);
            }
            if (bizOrgCode == null) {
                return CommonResponseUtil.success(null);
            }
        }
        if (StringUtils.isNotBlank(systemCode)) {
            hashMap.put("systemCode", systemCode);
        }
        return CommonResponseUtil.success(iFireFightingSystemService.getSystemStatus(hashMap));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "获取系统近一月告警设备top5（根据系统编码查询）")
    @GetMapping("/getAlarmOneMonth")
    public ResponseModel getSpecificAlarmOneMonthTOP(@RequestParam(required = false) String systemCode) {
        HashMap<String, Object> hashMap = new HashMap<>();
        ReginParams reginParams = getSelectedOrgInfo();
        ReginParams.PersonIdentity personIdentity = reginParams.getPersonIdentity();
        if (!ValidationUtil.isEmpty(personIdentity)) {
            String bizOrgCode = personIdentity.getBizOrgCode();
            if (StringUtils.isNotBlank(bizOrgCode)) {
                hashMap.put("bizOrgCode", bizOrgCode);
            }
            if (bizOrgCode == null) {
                return CommonResponseUtil.success(null);
            }
        }
        if (StringUtils.isNotBlank(systemCode)) {
            hashMap.put("systemCode", systemCode);
        }
        return CommonResponseUtil.success(iFireFightingSystemService.equipAlarmTOP(hashMap));
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "获取系统设备状态（根据系统编码查询）")
    @GetMapping("/getEquipmentState")
    public ResponseModel getEquipmentState(@RequestParam(required = false) String systemCode, CommonPageable commonPageable) {
        if (commonPageable.getPageNumber() == 0) {
            commonPageable.setPageNumber(1);
        }
        Page result = new Page<>(commonPageable.getPageNumber(), commonPageable.getPageSize());
        HashMap<String, Object> hashMap = new HashMap<>();
        ReginParams reginParams = getSelectedOrgInfo();
        ReginParams.PersonIdentity personIdentity = reginParams.getPersonIdentity();
        if (!ValidationUtil.isEmpty(personIdentity)) {
            String bizOrgCode = personIdentity.getBizOrgCode();
            if (StringUtils.isNotBlank(bizOrgCode)) {
                hashMap.put("bizOrgCode", bizOrgCode);
            }
            if (bizOrgCode == null) {
                return CommonResponseUtil.success(null);
            }
        }
        if (StringUtils.isNotBlank(systemCode)) {
            hashMap.put("systemCode", systemCode);
        }
        return CommonResponseUtil.success(iFireFightingSystemService.equipmentState(result, hashMap));
    }

}
