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.equipmanage.common.enums.IndexStatusEnum;
import com.yeejoin.equipmanage.common.utils.CommonPageable;
import com.yeejoin.equipmanage.common.utils.CommonResponseUtil;
import com.yeejoin.equipmanage.common.utils.StringUtil;
import com.yeejoin.equipmanage.common.utils.UnitTransformUtil;
import com.yeejoin.equipmanage.config.PersonIdentify;
import com.yeejoin.equipmanage.fegin.IotFeign;
import com.yeejoin.equipmanage.mapper.FireFightingSystemMapper;
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.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.foundation.utils.DateTimeUtil;
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.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

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

/**
 * @author keyong
 * @title: PoolStatisticController
 * <pre>
 * @description: TODO
 * </pre>
 * @date 2024/7/29 10:43
 */
@RestController
@Api(tags = "监盘总览组态需求 -- API")
@RequestMapping(value = "/center/pool", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class PoolStatisticController {

    @Autowired
    private FireFightingSystemMapper fireFightingSystemMapper;

    @Autowired
    private IotFeign iotFeign;

    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @RequestMapping(value = "/panel/statistic", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "获取水池统计信息", notes = "获取水池统计信息")
    public ResponseModel getWaterPanelInfo( @RequestParam(required = false) String bizOrgCode) {
        List<Map<String, Object>> infoList = fireFightingSystemMapper.getWaterInfoBySuper(bizOrgCode);
        List<Map<String, Object>> poolList = new ArrayList<>();
        List<Map<String, Object>> industryPoolList = new ArrayList<>();
        if (!infoList.isEmpty()) {
            industryPoolList = infoList.stream().filter(x -> "industryPool".equalsIgnoreCase(String.valueOf(x.get("resource_type")))).collect(Collectors.toList());
            poolList = infoList.stream().filter(x -> "pool".equalsIgnoreCase(String.valueOf(x.get("resource_type")))).collect(Collectors.toList());
        }
        Map<String, Object> poolMap = new HashMap<>();
        Map<String, List<Map<String, Object>>> pool = getPoolInfo(poolList);
        poolMap.put("poolName", "消防水池");
        poolMap.put("poolTotal", poolList.size());
        poolMap.put("poolLow", pool.get("low").size());
        poolMap.put("poolHigh", pool.get("high").size());
        poolMap.put("poolNormal", pool.get("normal").size());
        poolMap.put("poolAbs", this.getPercent(new BigDecimal(pool.get("normal").size()), new BigDecimal(poolList.size())));
        Map<String, List<Map<String, Object>>> industry = getPoolInfo(industryPoolList);
        poolMap.put("industryName", "工业水池");
        poolMap.put("industryTotal", industryPoolList.size());
        poolMap.put("industryLow", industry.get("low").size());
        poolMap.put("industryHigh", industry.get("high").size());
        poolMap.put("industryNormal", industry.get("normal").size());
        poolMap.put("industryAbs", this.getPercent(new BigDecimal(industry.get("normal").size()), new BigDecimal(industryPoolList.size())));
        return CommonResponseUtil.success(poolMap);
    }

    private Map<String, List<Map<String, Object>>> getPoolInfo(List<Map<String, Object>> infoList) {
        Map<String, List<Map<String, Object>>> resMap = new HashMap<>();
        List<Map<String, Object>> highList = new ArrayList<>();
        List<Map<String, Object>> lowList = new ArrayList<>();
        List<Map<String, Object>> normalList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(infoList)) {
            for (Map<String, Object> m : infoList) {
                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"))))) {
                    if (IndexStatusEnum.LOW.getKey().equals(String.valueOf(transResult.get("status")))) {
                        lowList.add(m);
                    } else if (IndexStatusEnum.HIGH.getKey().equals(String.valueOf(transResult.get("status")))) {
                        highList.add(m);
                    } else {
                        normalList.add(m);
                    }
                    m.put("levelStatus", IndexStatusEnum.getEnumByKey(String.valueOf(transResult.get("status"))).getDescribe1());
                } else {
                    normalList.add(m);
                }
            }
        }
        resMap.put("low", lowList);
        resMap.put("high", highList);
        resMap.put("normal", normalList);
        return resMap;
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @RequestMapping(value = "/panel/station/statistic", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "获取水池统计信息", notes = "获取水池统计信息")
    public ResponseModel<List<Map<String, Object>>> getStationWaterPanelInfo( @RequestParam(required = false) String bizOrgCode) {
        List<Map<String, Object>> infoList = fireFightingSystemMapper.getWaterInfoBySuper(bizOrgCode);
        List<Map<String, Object>> normalList = new ArrayList<>();
        List<Map<String, Object>> abNormalList = new ArrayList<>();
        if (!infoList.isEmpty()) {
            for (Map<String, Object> m : infoList) {
                Map<String, Object> map = new HashMap<>();
                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, RoundingMode.HALF_UP);
                    m.put("volume", bigDecimal + "m³");
                    m.put("levelAbs",  transResult.get("abs") + "%");
                    // 预警使用以下字段
                    m.put("volumeBigDecimal", bigDecimal);
                } else if (String.valueOf(transResult.get("abs")).equals("100") && String.valueOf(transResult.get("status")).equals("1")) {
                    BigDecimal bigDecimal = new BigDecimal(String.valueOf(m.get("volume")));
                    m.put("volume", bigDecimal + "m³");
                    m.put("levelAbs",  transResult.get("abs") + "%");
                    // 预警使用以下字段
                    m.put("volumeBigDecimal", bigDecimal);
                } else {
                    m.put("levelAbs", transResult.get("abs"));
                }
            }
        }
        return CommonResponseUtil.success(infoList);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @RequestMapping(value = "/status/statistic", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "获取水池统计信息", notes = "获取水池统计信息")
    public ResponseModel getWaterInfo( @RequestParam(required = false) String bizOrgCode) {
        List<Map<String, Object>> infoList = fireFightingSystemMapper.getWaterInfoBySuper(bizOrgCode);
        List<Map<String, Object>> normalList = new ArrayList<>();
        List<Map<String, Object>> abNormalList = new ArrayList<>();
        if (!infoList.isEmpty()) {
            for (Map<String, Object> m : infoList) {
                if (StringUtil.isNotEmpty(IndexStatusEnum.getEnumByKey(String.valueOf(m.get("status"))))) {
                    if (IndexStatusEnum.LOW.getKey().equals(String.valueOf(m.get("status")))) {
                        abNormalList.add(m);
                    } else if (IndexStatusEnum.HIGH.getKey().equals(String.valueOf(m.get("status")))) {
                        abNormalList.add(m);
                    } else if (IndexStatusEnum.NORMAL.getKey().equals(String.valueOf(m.get("status")))) {
                        normalList.add(m);
                    }
                } else {
                    normalList.add(m);
                }
            }
        }
        Map<String, Object> normalMap = new HashMap<>();
        normalMap.put("key", "normal");
        normalMap.put("name", "液位正常");
        normalMap.put("value", normalList.size());
        Map<String, Object> abNormalMap = new HashMap<>();
        abNormalMap.put("key", "abnormal");
        abNormalMap.put("name", "液位异常");
        abNormalMap.put("value", abNormalList.size());
        List<Map<String, Object>> res = new ArrayList<>();
        res.add(normalMap);
        res.add(abNormalMap);
        return CommonResponseUtil.success(res);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @RequestMapping(value = "/station/statistic", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "获取换流站水池信息", notes = "获取换流站水池信息")
    public ResponseModel getStationWaterInfo( @RequestParam(required = false) String bizOrgCode) {
        List<Map<String, Object>> infoList = fireFightingSystemMapper.getWaterInfoByBizOrgName(bizOrgCode);
        List<Map<String, Object>> lt4000 = new ArrayList<>();
        List<Map<String, Object>> gt4000 = new ArrayList<>();
        if (!CollectionUtils.isEmpty(infoList)) {
            for (Map<String, Object> m : infoList) {
                int result = new BigDecimal(4000).compareTo(new BigDecimal(String.valueOf(m.get("allVolume"))));
                if (0 < result) {
                    lt4000.add(m);
                } else {
                    gt4000.add(m);
                }
            }
        }
        Map<String, Object> normalMap = new HashMap<>();
        normalMap.put("key", "lt");
        normalMap.put("name", "<4000m³换流站");
        normalMap.put("value", lt4000.size());
        Map<String, Object> abNormalMap = new HashMap<>();
        abNormalMap.put("key", "gt");
        abNormalMap.put("name", "≥4000m³换流站");
        abNormalMap.put("value", gt4000.size());
        List<Map<String, Object>> res = new ArrayList<>();
        res.add(normalMap);
        res.add(abNormalMap);
        return CommonResponseUtil.success(res);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @RequestMapping(value = "/page", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "获取水池信息", notes = "获取水池信息")
    public ResponseModel getWaterInfo(CommonPageable commonPageable, @RequestParam(required = false) String bizOrgCode,
                                      @RequestParam(required = false) String stationOrder,
                                      @RequestParam(required = false) String stateOrder,
                                      @RequestParam(required = false) String status,
                                      @RequestParam(value = "sorter", required = false) String sorter) {
        if (commonPageable.getPageNumber() == 0) {
            commonPageable.setPageNumber(1);
        }
        if ("normal".equalsIgnoreCase(status)) {
            status = "0";
        } else if ("abnormal".equalsIgnoreCase(status)) {
            status = "1";
        }
        Page page = new Page<>(commonPageable.getPageNumber(), commonPageable.getPageSize());
        String sortField = "", sortOrder = "";
        if (org.springframework.util.StringUtils.hasText(sorter)) {
            sortField = sorter.split("@")[0];
            sortOrder = sorter.split("@")[1];
        }
        String sortFlag = null;
        if (sortField.equalsIgnoreCase("bizOrgName")) {
            sortFlag = "1";
        } else if (sortField.equalsIgnoreCase("eligibility")) {
            sortFlag = "2";
        }
        Page<Map<String, Object>> page1 = fireFightingSystemMapper.getWaterInfoList(page, bizOrgCode, sortFlag, sortOrder, status);
        List<Map<String, Object>> res = page1.getRecords();
        if (!res.isEmpty()) {
            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"));
                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, RoundingMode.HALF_UP);
                    m.put("surplus", bigDecimal);
                    m.put("surplusPercent", transResult.get("abs") + "%");
                } else if (String.valueOf(transResult.get("abs")).equals("100") && String.valueOf(transResult.get("status")).equals("1")) {
                    BigDecimal bigDecimal = new BigDecimal(String.valueOf(m.get("volume")));
                    m.put("surplus", bigDecimal);
                    m.put("surplusPercent", transResult.get("abs") + "%");
                } else {
                    m.put("levelAbs", transResult.get("abs"));
                }
            }
            page1.setRecords(res);
        }
        return CommonResponseUtil.success(page1);
    }

    @RequestMapping(value = "/selectWaterLevelDetail", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @ApiOperation(httpMethod = "GET", value = "水池液位详情", produces = "application/json;charset=UTF-8", notes = "水池液位详情")
    public ResponseModel selectWaterLevelDetail(@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("92011100") != -1) {
            name = "水池液位";
            code = "scyw";
        } else {
            return CommonResponseUtil.failure("不是水池设备，请检查！");
        }
        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_FirePoolDevice_WaterLevel");
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<Map<String, String>> result = new ArrayList<>();
        if (mounthEntity!=null&&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)) {
                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);
        }
        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) {
        //进行转化时区
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.US);
        Date date1 = null;
        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);
    }

    private BigDecimal getPercent(BigDecimal num1, BigDecimal num2) {
        if (num2.compareTo(BigDecimal.ZERO) == 0) {
            return BigDecimal.ZERO;
        } else {
            return num1.divide(num2, 4, RoundingMode.HALF_UP).multiply(new BigDecimal(100)).setScale(2, RoundingMode.HALF_UP);
        }
    }
}

