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.enums.IndexStatusEnum;
import com.yeejoin.equipmanage.common.utils.*;
import com.yeejoin.equipmanage.config.PersonIdentify;
import com.yeejoin.equipmanage.fegin.IotFeign;
import com.yeejoin.equipmanage.mapper.FireFightingSystemMapper;
import com.yeejoin.equipmanage.service.IEmergencyService;
import com.yeejoin.equipmanage.service.IEquipmentSpecificAlarmService;
import com.yeejoin.equipmanage.service.IFireFightingSystemService;
import com.yeejoin.equipmanage.service.ISupervisionVideoService;
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.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.util.CollectionUtils;
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.DateTimeUtil;
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.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static org.typroject.tyboot.core.foundation.utils.DateTimeUtil.ISO8601_DATE_HOUR_MIN_SEC;

@RestController
@Api(tags = "监盘总览组态需求 -- API")
@RequestMapping(value = "/supervisionConfigure", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class SupervisionConfigureController extends AbstractBaseController {

    @Autowired
    private FireFightingSystemMapper fireFightingSystemMapper;

    @Autowired
    private IFireFightingSystemService iFireFightingSystemService;

    @Autowired
    private IEquipmentSpecificAlarmService equipmentSpecificAlarmService;

    @Autowired
    private IotFeign iotFeign;

    @Autowired
    private ISupervisionVideoService supervisionVideoService;

    @Autowired
    private IEmergencyService emergencyService;

    @Value("${equipment.pressurepump.start}")
    private String pressurePumpStart;


    @PersonIdentify
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "监盘概览水源信息")
    @GetMapping("/getWaterInfo")
    public ResponseModel getWaterInfo(CommonPageable commonPageable, @RequestParam(required = false) String bizOrgCode) {
        if (commonPageable.getPageNumber() == 0) {
            commonPageable.setPageNumber(1);
        }
        if (StringUtils.isEmpty(bizOrgCode)) {
            ReginParams reginParams = getSelectedOrgInfo();
            bizOrgCode = !ValidationUtil.isEmpty(reginParams.getPersonIdentity()) && StringUtil.isNotEmpty(reginParams.getPersonIdentity().getBizOrgCode()) ? reginParams.getPersonIdentity().getBizOrgCode() : null;
        }
        Page page = new Page<>(commonPageable.getPageNumber(), commonPageable.getPageSize());
        Page<Map<String, Object>> page1 = fireFightingSystemMapper.getWaterInfoBySuper(page, bizOrgCode);
        List<Map<String, Object>> res = page1.getRecords();
        if (0 < res.size()) {
            for (Map<String, Object> m : res) {
                Map<String, Object> transResult = UnitTransformUtil.transformValues(String.valueOf(m.get("nowLevel")),
                        String.valueOf(m.get("unit")), String.valueOf(m.get("minLevel")), String.valueOf(m.get("maxLevel")));
                m.put("nowLevel", transResult.get("nowValue"));
                if (StringUtil.isNotEmpty(IndexStatusEnum.getEnumByKey(String.valueOf(transResult.get("status"))))) {
                    m.put("levelStatus", IndexStatusEnum.getEnumByKey(String.valueOf(transResult.get("status"))).getDescribe1());
                } else {
                    m.put("levelStatus", "--");
                }
                m.put("abs", transResult.get("abs"));
                if (!String.valueOf(transResult.get("abs")).equals("--") && !ObjectUtils.isEmpty(m.get("volume"))) {
                    BigDecimal divide = new BigDecimal(100);
                    BigDecimal bigDecimal = new BigDecimal(String.valueOf(m.get("volume"))).multiply(new BigDecimal(String.valueOf(transResult.get("abs")))).divide(divide, 0, BigDecimal.ROUND_HALF_UP);
                    m.put("levelAbs", bigDecimal + "m³ " + " (" + transResult.get("abs") + "%)");
                } else {
                    m.put("levelAbs", transResult.get("abs"));
                }
            }
        }
        return CommonResponseUtil.success(page1);
    }

    @PersonIdentify
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "监盘概览泡沫罐和水箱信息（监盘概览）")
    @GetMapping("/getFoamTankBySuper")
    public ResponseModel getFoamTankBySuper(CommonPageable commonPageable, @RequestParam(required = false) String bizOrgCode) {
        if (commonPageable.getPageNumber() == 0) {
            commonPageable.setPageNumber(1);
        }
        if (StringUtils.isEmpty(bizOrgCode)) {
            ReginParams reginParams = getSelectedOrgInfo();
            bizOrgCode = !ValidationUtil.isEmpty(reginParams.getPersonIdentity()) && StringUtil.isNotEmpty(reginParams.getPersonIdentity().getBizOrgCode()) ? reginParams.getPersonIdentity().getBizOrgCode() : null;
        }
        Page page = new Page<>(commonPageable.getPageNumber(), commonPageable.getPageSize());
        Page<Map<String, Object>> page1 = fireFightingSystemMapper.getFoamTankBySuper(page, bizOrgCode);
        List<Map<String, Object>> res = page1.getRecords();
        if (0 < res.size()) {
            for (Map<String, Object> m : res) {
                Map<String, Object> transResult = UnitTransformUtil.transformValues(String.valueOf(m.get("nowLevel")),
                        String.valueOf(m.get("unit")), String.valueOf(m.get("minLevel")), String.valueOf(m.get("maxLevel")));
                m.put("nowLevel", transResult.get("nowValue"));
                if (StringUtil.isNotEmpty(IndexStatusEnum.getEnumByKey(String.valueOf(transResult.get("status"))))) {
                    m.put("levelStatus", IndexStatusEnum.getEnumByKey(String.valueOf(transResult.get("status"))).getDescribe1());
                } else {
                    m.put("levelStatus", "--");
                }
                m.put("levelAbs", transResult.get("abs"));
            }
        }
        return CommonResponseUtil.success(page1);
    }

    @PersonIdentify
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "监盘概览管网压力信息（监盘概览）")
    @GetMapping("/getPipeNetworkBySuper")
    public ResponseModel getPipeNetworkBySuper(CommonPageable commonPageable, @RequestParam(required = false) String bizOrgCode) {
        if (commonPageable.getPageNumber() == 0) {
            commonPageable.setPageNumber(1);
        }
        if (StringUtils.isEmpty(bizOrgCode)) {
            ReginParams reginParams = getSelectedOrgInfo();
            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.getPipeNetworkBySuper(page, bizOrgCode));
    }

    @PersonIdentify
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "监盘概览水池装置进水流量信息（监盘概览）")
    @GetMapping("/getInfluentFlowBySuper")
    public ResponseModel getInfluentFlowBySuper(CommonPageable commonPageable, @RequestParam(required = false) String bizOrgCode) {
        if (commonPageable.getPageNumber() == 0) {
            commonPageable.setPageNumber(1);
        }
        if (StringUtils.isEmpty(bizOrgCode)) {
            ReginParams reginParams = getSelectedOrgInfo();
            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.getInfluentFlowBySuper(page, bizOrgCode));
    }

    @PersonIdentify
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "获取某站下装备数量、摄像头数量（监盘概览）")
    @GetMapping("/statisticsBySuper")
    public ResponseModel statisticsByStation(@RequestParam(required = false) String bizOrgCode) {

        if (ObjectUtils.isEmpty(bizOrgCode)) {
            ReginParams reginParams = getSelectedOrgInfo();
            ReginParams.PersonIdentity personIdentity = reginParams.getPersonIdentity();
            if (!ValidationUtil.isEmpty(personIdentity)) {
                bizOrgCode = personIdentity.getBizOrgCode();
            }
        }
        if (ObjectUtils.isEmpty(bizOrgCode)) {
            return CommonResponseUtil.success(null);
        }
        return CommonResponseUtil.success(fireFightingSystemMapper.statisticsByStation(bizOrgCode));
    }

    @PersonIdentify
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "【监盘总览-排油系统信息】获取系统设备状态（根据系统编码查询）")
    @GetMapping("/getEquipmentStateBySuper")
    public ResponseModel getEquipmentStateBySuper(@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);
        } else {
            throw new BadRequest("系统编码不能为空");
        }
        return CommonResponseUtil.success(iFireFightingSystemService.equipmentStateBySuper(result, hashMap));
    }

    @PersonIdentify
    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @ApiOperation(value = "【监盘总览-排油系统信息】获取系统工作状态（根据系统编码查询）")
    @GetMapping("/getSystemStatusBySuper")
    public ResponseModel getSystemStatusBySuper(@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);
        } else {
            throw new BadRequest("系统编码不能为空");
        }
        return CommonResponseUtil.success(iFireFightingSystemService.getSystemStatusBySuper(hashMap));
    }


    @PersonIdentify
    @RequestMapping(value = "/fireAlarmLogPage", 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 code,
                                   @RequestParam(required = false) String typeCode,
                                   @RequestParam(required = false) String bizOrgCode,
                                   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(code) ? StringUtils.trimToNull(code) : null);
        queryRequests.add(request7);
        CommonRequest request8 = new CommonRequest();
        request8.setName("specificIndexKey");
        request8.setValue(StringUtil.isNotEmpty(typeCode) ? StringUtils.trimToNull(typeCode) : null);
        queryRequests.add(request8);
        CommonRequest request13 = new CommonRequest();
        request13.setName("bizOrgCode");
        request13.setValue(ObjectUtils.isEmpty(bizOrgCode) ? reginParams.getPersonIdentity().getBizOrgCode() : bizOrgCode);
        queryRequests.add(request13);
        CommonPageInfoParam param = CommonPageParamUtil.fillCommonPageInfoParam(queryRequests, commonPageable);
        return CommonResponseUtil.success(equipmentSpecificAlarmService.fireAlarmLogPage(param));
    }


    @PersonIdentify
    @RequestMapping(value = "/alarmTrend", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "报警类型趋势", produces = "application/json;charset=UTF-8", notes = "报警类型趋势")
    public ResponseModel alarmTrend(@RequestParam(required = false) String bizOrgCode, @RequestParam(required = false) String companyCode) {
        if (StringUtils.isEmpty(bizOrgCode)) {
            ReginParams reginParams = getSelectedOrgInfo();
            bizOrgCode = !ValidationUtil.isEmpty(reginParams.getPersonIdentity()) && StringUtil.isNotEmpty(reginParams.getPersonIdentity().getBizOrgCode()) ? reginParams.getPersonIdentity().getBizOrgCode() : null;
        }
        return CommonResponseUtil.success(equipmentSpecificAlarmService.alarmTrend(bizOrgCode, companyCode));
    }

    @PersonIdentify
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "概览稳压泵信息")
    @GetMapping("/getPressurePumpInfo")
    public ResponseModel getPressurePumpInfo(CommonPageable commonPageable, @RequestParam(required = false) String bizOrgCode) {
        if (commonPageable.getPageNumber() == 0) {
            commonPageable.setPageNumber(1);
        }
        if (ObjectUtils.isEmpty(bizOrgCode)) {
            ReginParams reginParams = getSelectedOrgInfo();
            ReginParams.PersonIdentity personIdentity = reginParams.getPersonIdentity();
            if (!ValidationUtil.isEmpty(personIdentity)) {
                bizOrgCode = personIdentity.getBizOrgCode();
                if (bizOrgCode == null) {
                    return CommonResponseUtil.success(null);
                }
            }
        }
        Page page = new Page<>(commonPageable.getPageNumber(), commonPageable.getPageSize());
        Page<Map<String, Object>> pressurePumpInfo = supervisionVideoService.queryPumpInfo(page, bizOrgCode);
        return CommonResponseUtil.success(pressurePumpInfo);
    }

    @PersonIdentify
    @RequestMapping(value = "/replaceVideo", method = RequestMethod.POST)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "替换视频", produces = "application/json;charset=UTF-8", notes = "替换视频")
    public ResponseModel replaceVideo(@RequestBody Map<String, String> ids) {
        String bizOrgCode = null;
        ReginParams reginParams = getSelectedOrgInfo();
        ReginParams.PersonIdentity personIdentity = reginParams.getPersonIdentity();
        if (!ValidationUtil.isEmpty(personIdentity)) {
            bizOrgCode = personIdentity.getBizOrgCode();
            if (bizOrgCode == null) {
                return CommonResponseUtil.success(null);
            }
        }
        return CommonResponseUtil.success(supervisionVideoService.replaceVideo(ids, bizOrgCode));
    }

    @PersonIdentify
    @RequestMapping(value = "/queryVideoList", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "查询视频列表", produces = "application/json;charset=UTF-8", notes = "查询视频列表")
    public ResponseModel queryVideoList() {
        String bizOrgCode = null;
        ReginParams reginParams = getSelectedOrgInfo();
        ReginParams.PersonIdentity personIdentity = reginParams.getPersonIdentity();
        if (!ValidationUtil.isEmpty(personIdentity)) {
            if (personIdentity.getCompanyBizOrgCode() == null) {
                bizOrgCode = personIdentity.getBizOrgCode();
            } else {
                bizOrgCode = personIdentity.getCompanyBizOrgCode();
            }
            if (bizOrgCode == null) {
                return CommonResponseUtil.success(null);
            }
        }
        return CommonResponseUtil.success(supervisionVideoService.queryVideoList(bizOrgCode));
    }

    @PersonIdentify
    @RequestMapping(value = "/queryVideoAllId", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "查询对应站下所有视频id", produces = "application/json;charset=UTF-8", notes = "根据id查询视频")
    public ResponseModel queryVideoAllId() {
        String bizOrgCode = null;
        ReginParams reginParams = getSelectedOrgInfo();
        ReginParams.PersonIdentity personIdentity = reginParams.getPersonIdentity();
        if (!ValidationUtil.isEmpty(personIdentity)) {
            bizOrgCode = personIdentity.getBizOrgCode();
            if (bizOrgCode == null) {
                return CommonResponseUtil.success(null);
            }
        }
        return CommonResponseUtil.success(supervisionVideoService.queryVideoAllId(bizOrgCode));
    }

    @PersonIdentify
    @RequestMapping(value = "/selectPressureMonth", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "统计当月稳压泵启停", produces = "application/json;charset=UTF-8", notes = "统计当月稳压泵启停")
    public ResponseModel selectPressureMonth(@RequestParam(value = "bizOrgCode", required = false) String bizOrgCode) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String startDay = df.format(new Date());
        Calendar calendar = Calendar.getInstance();
        calendar.set(Integer.parseInt(startDay.substring(0, 4)), Integer.parseInt(startDay.substring(5, 7)) - 1, 1);
        String firstDayOfMonth = new SimpleDateFormat("yyyy-MM-dd ").format(calendar.getTime());
        System.out.println("第一天：" + firstDayOfMonth + "00:00:00");
        //这里先设置要获取月份的下月的第一天
        calendar.set(Integer.parseInt(startDay.substring(0, 4)), Integer.parseInt(startDay.substring(5, 7)), 1);
        //这里将日期值减去一天，从而获取到要求的月份最后一天
        calendar.add(Calendar.DATE, -1);
        String lastDayOfMonth = new SimpleDateFormat("yyyy-MM-dd ").format(calendar.getTime());
        System.out.println("最后一天：" + lastDayOfMonth + "23:59:59");
        if (ObjectUtils.isEmpty(bizOrgCode)) {
            ReginParams reginParams = getSelectedOrgInfo();
            ReginParams.PersonIdentity personIdentity = reginParams.getPersonIdentity();
            if (!ValidationUtil.isEmpty(personIdentity)) {
                bizOrgCode = personIdentity.getBizOrgCode();
                if (bizOrgCode == null) {
                    return CommonResponseUtil.success(null);
                }
            }
        }
        // 稳压泵信息
        List<Map<String, Object>> pressurePumps = fireFightingSystemMapper.selectAllPressurePumpInfo(bizOrgCode);
        ArrayList<Map<String, Object>> names = new ArrayList<>();
        // x轴数据
        List<Map<String, Object>> data = fireFightingSystemMapper.selectAllDays();
        for (Map<String, Object> pressurePump : pressurePumps) {
            HashMap<String, Object> bar = new HashMap<>();
            bar.put("name", pressurePump.get("name"));
            bar.put("id", pressurePump.get("id"));
            names.add(bar);
            String prefix = null;
            String suffix = null;
            String iotCode = pressurePump.get("iot_code").toString();
            if (iotCode.length() > 8) {
                prefix = iotCode.substring(0, 8);
                suffix = iotCode.substring(8);
            } else {
                throw new BadRequest("装备物联编码错误，请确认！");
            }
            ResponseModel mounthEntity = null;
            try {
                mounthEntity = iotFeign.selectList(getAppKey(), getProduct(), getToken(), firstDayOfMonth + "00:00:00", lastDayOfMonth + "23:59:59", prefix, suffix, null);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (!ObjectUtils.isEmpty(mounthEntity) && "200".equals(String.valueOf(mounthEntity.getStatus()))) {
                for (Map<String, Object> item : data) {
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("name", pressurePump.get("name"));
                    String json1 = JSON.toJSONString(mounthEntity.getResult());
                    List<Map<String, String>> list = (List<Map<String, String>>) JSONArray.parse(json1);
                    List<Map<String, String>> collect = list.stream().filter(t -> (t.containsKey("time") && t.get("time").substring(0, 10).equals(item.get("date"))) && ((t.containsKey(pressurePumpStart) && t.get(pressurePumpStart).equals("true"))
                            || (t.containsKey(pressurePumpStart) && t.get(pressurePumpStart).equals("false")))).collect(Collectors.toList());
                    map.put("value", collect.size());
                    map.put("id", pressurePump.get("id"));
                    if (item.containsKey("yData")) {
                        List<Map<String, Object>> yData1 = (List<Map<String, Object>>) item.get("yData");
                        yData1.add(map);
                    } else {
                        ArrayList<Map<String, Object>> maps = new ArrayList<>();
                        maps.add(map);
                        item.put("yData", maps);
                    }
                }
            }
        }
        HashMap<String, Object> result = new HashMap<>();
        result.put("names", names);
        result.put("data", data);
        return CommonResponseUtil.success(result);
    }

    @PersonIdentify
    @RequestMapping(value = "/selectPressureDetails", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "稳压泵详情", produces = "application/json;charset=UTF-8", notes = "稳压泵详情")
    public ResponseModel selectPressureDetails(@RequestParam(value = "bizOrgCode", required = false) String bizOrgCode) {
        if (ObjectUtils.isEmpty(bizOrgCode)) {
            ReginParams reginParams = getSelectedOrgInfo();
            ReginParams.PersonIdentity personIdentity = reginParams.getPersonIdentity();
            if (!ValidationUtil.isEmpty(personIdentity)) {
                bizOrgCode = personIdentity.getBizOrgCode();
                if (bizOrgCode == null) {
                    return CommonResponseUtil.success(null);
                }
            }
        }
        List<Map<String, Object>> list = supervisionVideoService.selectPressureDetails(bizOrgCode);
        return CommonResponseUtil.success(list);
    }


    @PersonIdentify
    @RequestMapping(value = "/selectPipePressureDetail", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "管网压力详情", produces = "application/json;charset=UTF-8", notes = "管网压力详情")
    public ResponseModel selectPipePressureDetail(@RequestParam(value = "equipmentSpecificId") String equipmentSpecificId,
                                                  @RequestParam(value = "startTime", required = false) String startTime,
                                                  @RequestParam(value = "endTime", required = false) String endTime
    ) throws ParseException {
        if (!StringUtil.isNotEmpty(equipmentSpecificId)) {
            return CommonResponseUtil.success();
        }
        Map<String, Object> map = fireFightingSystemMapper.selectEquipmentSpecificById(equipmentSpecificId);
        String name = "";
        String code = "";
        if (String.valueOf(map.get("equipment_code")).indexOf("92011000") != -1) {
            name = "管网压力";
            code = "gwyl";
        } else if (String.valueOf(map.get("equipment_code")).indexOf("92011100") != -1) {
            name = "水池液位";
            code = "scyw";
        }
        if (ObjectUtils.isEmpty(map) || ObjectUtils.isEmpty(map.get("iot_code"))) {
            return CommonResponseUtil.success(null);
        }
        String iotCode = map.get("iot_code").toString();
        String prefix = null;
        String suffix = null;
        if (iotCode.length() > 8) {
            prefix = iotCode.substring(0, 8);
            suffix = iotCode.substring(8);
        } else {
            throw new BadRequest("装备物联编码错误，请确认！");
        }
        ResponseModel mounthEntity = null;
        try {
            mounthEntity = iotFeign.selectList(getAppKey(), getProduct(), getToken(), startTime, endTime, prefix, suffix, "FHS_PipePressureDetector_PipePressure");
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<Map<String, String>> result = new ArrayList<>();
        if (200 == mounthEntity.getStatus()) {
            String json1 = JSON.toJSONString(mounthEntity.getResult());
            List<Map<String, String>> list = (List<Map<String, String>>) JSONArray.parse(json1);
            Collections.reverse(list);
//            if (!CollectionUtils.isEmpty(list) && list.size() > 30) {
//                for (int i = 0; i <= 29; i++) {
//                    result.add(list.get(i));
//                }
//            } else {
//                result.addAll(list);
//            }
            if (!CollectionUtils.isEmpty(list)) {
                result.addAll(list);
            }
        }
        List<Map<String, String>> res = new ArrayList<>();
        for (Map<String, String> m : result) {
            Map<String, String> item = new HashMap<>();
            item.put("time", change(String.valueOf(m.get("time"))));
            for (String s : m.keySet()) {
                if (!s.equals("time")) {
                    item.put("value", m.get(s));
                    item.remove(s);
                    continue;
                }
            }
            res.add(item);
        }
//        result.stream().map(item -> {
//            if (!ObjectUtils.isEmpty(item.get("time"))) {
//                item.put("time", change(String.valueOf(item.get("time"))));
//            }
//            return item;
//        }).collect(Collectors.toList());
        List<Map<String, Object>> resList = new ArrayList<>();
        Map<String, Object> map1 = new HashMap<>();
        map1.put("name", name);
        map1.put("xData", res.stream().map(x -> x.get("time")).collect(Collectors.toList()));
        map1.put("yData", res.stream().map(x -> x.get("value")).collect(Collectors.toList()));
        Map<String, Object> resMap = new HashMap<>();
        resMap.put(code, map1);
        return CommonResponseUtil.success(resMap);
    }

    private String change(String time) throws ParseException {
        //进行转化时区
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.US);
        Date date1 = null;
//        if(time.contains("Z")) {
//            try {
//                myDate = dateFormat.parse(time.replace("Z", "+0000"));
//            } catch (ParseException e) {
//                e.printStackTrace();
//            }
//        }
        try {
            String strDate = time.substring(0, 19);
            SimpleDateFormat sdf = new SimpleDateFormat(ISO8601_DATE_HOUR_MIN_SEC);
            sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
            date1 = sdf.parse(strDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return DateTimeUtil.format(date1, DateTimeUtil.ISO_DATE_HOUR24_MIN_SEC);
//        return   times;

        //转换为年月日时分秒
//        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        return df.format(time);
//        return format;

    }
}
