package com.ruoyi.web.controller.gas;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.ElasticConstants;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.AggsType;
import com.ruoyi.framework.config.ElasticSearchClient;
import com.ruoyi.system.domain.GuapAlert;
import com.ruoyi.system.domain.GuapMonitorPoint;
import com.ruoyi.system.domain.IllegalShip;
import com.ruoyi.system.domain.XiuTanIllegalShip;
import com.ruoyi.system.domain.XiuTanSemInstrument;
import com.ruoyi.system.service.IAisDatabase;
import com.ruoyi.system.service.IHeiYanService;
import com.ruoyi.system.service.ISo2Service;
import com.ruoyi.system.service.ISysDictTypeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramInterval;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 硫含量
 * @Author: huangcheng
 * @Date: 2021/8/26
 * @Version V1.0
 */
@RestController
@RequestMapping("/so2")
@Api(tags = "硫含量接口")
public class So2Controller extends BaseController {

    @Autowired
    private ElasticSearchClient client;
    @Autowired
    private IAisDatabase aisDatabase;
    @Autowired
    private ISo2Service so2Service;
    @Autowired
    private IHeiYanService heiYanService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private ISysDictTypeService dictTypeService;

    @GetMapping("/guangpu/list")
    @ApiOperation("光谱-硫嫌疑船舶列表数据")
    public TableDataInfo GpList(GuapAlert guapAlert) {
        // 传来的参数
        Map<String, Object> params = guapAlert.getParams();
        Map<String, Object> equalsCondition = new HashMap<>();
        // 组装查询条件
        equalsCondition.put("mmsi", ObjectUtil.isEmpty(guapAlert.getMmsi()) ? null : StrUtil.concat(true, "*", Convert.toStr(guapAlert.getMmsi()), "*"));
        equalsCondition.put("shipName", StrUtil.isBlank(guapAlert.getShipName()) ? null : StrUtil.concat(true, "*", guapAlert.getShipName(), "*"));
        equalsCondition.put("shipRegionType", guapAlert.getShipRegionType());
        equalsCondition.put("destination", StrUtil.isBlank(guapAlert.getDestination()) ? null : StrUtil.concat(true, "*", guapAlert.getDestination(), "*"));
        equalsCondition.put("orgName", guapAlert.getOrgName());
        equalsCondition.put("illegalStatus", guapAlert.getIllegalStatus());
        equalsCondition.put("dealResult", guapAlert.getDealResult());
        equalsCondition.put("fastResult", guapAlert.getFastResult());
        equalsCondition.put("uploadResult", guapAlert.getUploadResult());
        equalsCondition.put("monitorPointName", guapAlert.getMonitorPointName());
        // 组装范围查询条件
        Map<String, Object> rangeCondition = new HashMap<>();
        if (ObjectUtil.isNotEmpty(params.get("beginTime"))) {
            params.put("beginTime", params.get("beginTime") + " 00:00:00");
        }
        if (ObjectUtil.isNotEmpty(params.get("endTime"))) {
            params.put("endTime", params.get("endTime") + " 23:59:59");
        }
        rangeCondition.put("createTime", StrUtil.concat(true, "[", Convert.toStr(params.get("beginTime")), ",", Convert.toStr(params.get("endTime")), "]"));
        List<String> orderBy = new ArrayList<>();
        orderBy.add("-createTime");
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Map<String, Object> maps = client.searchDocument(equalsCondition, rangeCondition, orderBy, pageDomain.getPageNum(), pageDomain.getPageSize(), ElasticConstants.SO2_ALERT);

        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(Convert.toList(GuapAlert.class, maps.get("pageList")));
        rspData.setTotal(Convert.toLong(maps.get("totalNum")));
        return rspData;
    }

    @GetMapping("/xiutan/list")
    @ApiOperation("嗅探-硫嫌疑船舶列表数据")
    public TableDataInfo XtList(XiuTanIllegalShip illegalShip) {
        // 传来的参数
        Map<String, Object> params = illegalShip.getParams();
        Map<String, Object> equalsCondition = new HashMap<>();
        // 组装查询条件
        equalsCondition.put("mmsi", ObjectUtil.isEmpty(illegalShip.getMmsi()) ? null : StrUtil.concat(true, "*", Convert.toStr(illegalShip.getMmsi()), "*"));
        equalsCondition.put("shipName", StrUtil.isBlank(illegalShip.getShipName()) ? null : StrUtil.concat(true, "*", illegalShip.getShipName(), "*"));
        equalsCondition.put("shipRegionType", illegalShip.getShipRegionType());
        equalsCondition.put("destination", StrUtil.isBlank(illegalShip.getDestination()) ? null : StrUtil.concat(true, "*", illegalShip.getDestination(), "*"));
        equalsCondition.put("orgName", illegalShip.getOrgName());
        equalsCondition.put("illegalStatus", illegalShip.getIllegalStatus());
        equalsCondition.put("dealResult", illegalShip.getDealResult());
        equalsCondition.put("fastResult", illegalShip.getFastResult());
        equalsCondition.put("uploadResult", illegalShip.getUploadResult());
        equalsCondition.put("monitorPointName", illegalShip.getMonitorPointName());
        // 组装范围查询条件
        Map<String, Object> rangeCondition = new HashMap<>();
        if (ObjectUtil.isNotEmpty(params.get("beginTime"))) {
            params.put("beginTime", params.get("beginTime") + " 00:00:00");
        }
        if (ObjectUtil.isNotEmpty(params.get("endTime"))) {
            params.put("endTime", params.get("endTime") + " 23:59:59");
        }
        rangeCondition.put("peakTime", StrUtil.concat(true, "[", Convert.toStr(params.get("beginTime")), ",", Convert.toStr(params.get("endTime")), "]"));
        List<String> orderBy = new ArrayList<>();
        orderBy.add("-peakTime");
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Map<String, Object> maps = client.searchDocument(equalsCondition, rangeCondition, orderBy, pageDomain.getPageNum(), pageDomain.getPageSize(), ElasticConstants.AIS_ILLEGAL_SHIP);

        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(Convert.toList(GuapAlert.class, maps.get("pageList")));
        rspData.setTotal(Convert.toLong(maps.get("totalNum")));
        return rspData;
    }

    @GetMapping("/list")
    @ApiOperation("硫嫌疑船舶列表数据")
    public TableDataInfo list(IllegalShip illegalShip) {
        // 传来的参数
        Map<String, Object> params = illegalShip.getParams();
        Map<String, Object> equalsCondition = new HashMap<>();
        // 组装查询条件
        equalsCondition.put("mmsi", ObjectUtil.isEmpty(illegalShip.getMmsi()) ? null : StrUtil.concat(true, "*", Convert.toStr(illegalShip.getMmsi()), "*"));
        equalsCondition.put("shipName", StrUtil.isBlank(illegalShip.getShipName()) ? null : StrUtil.concat(true, "*", illegalShip.getShipName(), "*"));
        equalsCondition.put("shipRegionType", illegalShip.getShipRegionType());
        equalsCondition.put("destination", StrUtil.isBlank(illegalShip.getDestination()) ? null : StrUtil.concat(true, "*", illegalShip.getDestination(), "*"));
        equalsCondition.put("orgName", illegalShip.getOrgName());
        equalsCondition.put("illegalStatus", illegalShip.getIllegalStatus());
        equalsCondition.put("dealResult", illegalShip.getDealResult());
        equalsCondition.put("fastResult", illegalShip.getFastResult());
        equalsCondition.put("uploadResult", illegalShip.getUploadResult());
        equalsCondition.put("monitorPointName", illegalShip.getMonitorPointName());
        // 组装范围查询条件
        Map<String, Object> rangeCondition = new HashMap<>();
        if (ObjectUtil.isNotEmpty(params.get("beginTime"))) {
            params.put("beginTime", params.get("beginTime") + " 00:00:00");
        }
        if (ObjectUtil.isNotEmpty(params.get("endTime"))) {
            params.put("endTime", params.get("endTime") + " 23:59:59");
        }
        rangeCondition.put("createTime", StrUtil.concat(true, "[", Convert.toStr(params.get("beginTime")), ",", Convert.toStr(params.get("endTime")), "]"));
        List<String> orderBy = new ArrayList<>();
        orderBy.add("-createTime");
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Map<String, Object> maps = client.searchDocument(equalsCondition, rangeCondition, orderBy, pageDomain.getPageNum(), pageDomain.getPageSize(), ElasticConstants.SO2_ALERT, ElasticConstants.AIS_ILLEGAL_SHIP);

        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(Convert.toList(IllegalShip.class, maps.get("pageList")));
        rspData.setTotal(Convert.toLong(maps.get("totalNum")));
        return rspData;
    }

    @GetMapping("/guangpu/monitorPoint")
    @ApiOperation("光谱-检测点数据")
    public AjaxResult monitorPoint(GuapMonitorPoint monitorPoint) {
        // 传来的参数
        Map<String, Object> equalsCondition = new HashMap<>();
        // 组装查询条件
        equalsCondition.put("name", StrUtil.isBlank(monitorPoint.getName()) ? null : StrUtil.concat(true, "*", monitorPoint.getName(), "*"));
        Map<String, Object> maps = client.searchDocument(equalsCondition, null, null, 1, 10000, ElasticConstants.SO2_MONITOR_POINT);
        return AjaxResult.success(Convert.toList(GuapMonitorPoint.class, maps.get("pageList")));
    }

    @GetMapping("/xiutan/semInstrument")
    @ApiOperation("嗅探-设备数据")
    public AjaxResult semInstrument(XiuTanSemInstrument semInstrument) {
        // 传来的参数
        Map<String, Object> equalsCondition = new HashMap<>();
        // 组装查询条件
        equalsCondition.put("name", StrUtil.isBlank(semInstrument.getName()) ? null : StrUtil.concat(true, "*", semInstrument.getName(), "*"));
        Map<String, Object> maps = client.searchDocument(equalsCondition, null, null, 1, 10000, ElasticConstants.AIS_SEM_INSTRUMENT);
        return AjaxResult.success(Convert.toList(XiuTanSemInstrument.class, maps.get("pageList")));
    }

    @GetMapping("/static/device")
    @ApiOperation("设备安装位置统计")
    public AjaxResult deviceStatic() {
        if (redisCache.hasKey(CacheConstants.DEVICE_STATIC)) {
            return AjaxResult.success(redisCache.getCacheMap(CacheConstants.DEVICE_STATIC));
        }
        List<Map<String, Object>> aisDevice = aisDatabase.queryDeviceStatic();
        List<Map<String, Object>> so2Device = so2Service.queryDeviceStatic();
        List<Map<String, Object>> heiyanDevice = heiYanService.queryDeviceStatic();
        // 两个结果合并
        Map<String, Integer> result = new HashMap<>(8);
        for (Map<String, Object> stringIntegerMap : aisDevice) {
            result.put(Convert.toStr(stringIntegerMap.get("point")), Convert.toInt(stringIntegerMap.get("count")));
        }
        for (Map<String, Object> stringIntegerMap : so2Device) {
            result.put(Convert.toStr(stringIntegerMap.get("point")), Convert.toInt(NumberUtil.add(result.get(Convert.toStr(stringIntegerMap.get("point"))), Convert.toInt(stringIntegerMap.get("count")))));
        }
        for (Map<String, Object> stringObjectMap : heiyanDevice) {
            result.put(Convert.toStr(stringObjectMap.get("point")), Convert.toInt(NumberUtil.add(result.get(Convert.toStr(stringObjectMap.get("point"))), Convert.toInt(stringObjectMap.get("count")))));
        }
        redisCache.setCacheMap(CacheConstants.DEVICE_STATIC, result);
        return AjaxResult.success(result);
    }

    @GetMapping("/static/deviceType")
    @ApiOperation("设备类型统计")
    public AjaxResult deviceTypeStatic() {
        if (redisCache.hasKey(CacheConstants.DEVICE_TYPE_STATIC)) {
            return AjaxResult.success(redisCache.getCacheMap(CacheConstants.DEVICE_TYPE_STATIC));
        }
        int aisDevice = aisDatabase.queryDeviceCount();
        int so2Device = so2Service.queryDeviceCount();
        int heiyanDevice = heiYanService.queryDeviceCount();
        // 两个结果合并
        Map<String, Integer> result = new HashMap<>(4);
        result.put("光谱", so2Device);
        result.put("嗅探", aisDevice);
        result.put("黑烟", heiyanDevice);
        redisCache.setCacheMap(CacheConstants.DEVICE_TYPE_STATIC, result);
        return AjaxResult.success(result);
    }

    @GetMapping("/snapPos/static")
    @ApiOperation("硫含量超标船舶分布统计")
    public AjaxResult so2SnapPosStatic(@RequestParam(required = false) String month) {
        String beginTime = "";
        String endTime = "";
        if (StrUtil.isBlank(month)) {
            beginTime = DateUtil.formatDate(DateUtil.beginOfMonth(new Date())) + " 00:00:00";
            endTime = DateUtil.formatDate(DateUtil.endOfMonth(new Date())) + " 23:59:59";
        } else {
            beginTime = month + "-01 00:00:00";
            endTime = DateUtil.formatDate(DateUtil.endOfMonth(DateUtil.parseDate(beginTime))) + " 23:59:59";
        }
        Map<String, Object> aisRangeCondition = new HashMap<>();
        aisRangeCondition.put("peakTime", StrUtil.concat(true, "[", beginTime, ",", endTime, "]"));
        Map<Object, Object> aisAggs = client.aggs(ElasticConstants.AIS_ILLEGAL_SHIP, AggsType.count, "monitorPointName", "id", null, aisRangeCondition);
        Map<String, Object> so2RangeCondition = new HashMap<>();
        so2RangeCondition.put("createTime", StrUtil.concat(true, "[", beginTime, ",", endTime, "]"));
        Map<Object, Object> so2Aggs = client.aggs(ElasticConstants.SO2_ALERT, AggsType.count, "monitorPointName", "id", null, so2RangeCondition);
        // 构造硫的数据
        List<SysDictData> so2_snap_pos = dictTypeService.selectDictDataByType("so2_snap_pos");
        Map<String, Object> result = new HashMap<>();
        for (SysDictData so2_snap_po : so2_snap_pos) {
            result.put(so2_snap_po.getDictLabel(),
                    (ObjectUtil.isEmpty(aisAggs.get(so2_snap_po.getDictLabel())) ? 0 : Convert.toInt(aisAggs.get(so2_snap_po.getDictLabel())))
                            + (ObjectUtil.isEmpty(so2Aggs.get(so2_snap_po.getDictLabel())) ? 0 : Convert.toInt(so2Aggs.get(so2_snap_po.getDictLabel()))));
        }
        return AjaxResult.success(result);
    }

    @GetMapping("/timeStatic")
    @ApiOperation("超标船舶统计-按时间")
    public AjaxResult monthStatic(@RequestParam(required = false) String interval) {
        if (StrUtil.isBlank(interval)) {
            // 默认值为1个月
            interval = "1M";
        }
        Map<Object, Object> aisAggs = client.dateHistogramAggs(ElasticConstants.AIS_ILLEGAL_SHIP, AggsType.count, "peakTime", "id", null, null, new DateHistogramInterval(interval));
        Map<Object, Object> so2Aggs = client.dateHistogramAggs(ElasticConstants.SO2_ALERT, AggsType.count, "createTime", "id", null, null, new DateHistogramInterval(interval));
        Map<Object, Object> heiyanAggs = client.dateHistogramAggs(ElasticConstants.HEIYAN_SHIP_RECOGNITION, AggsType.count, "snapTimeFmt", "id", null, null, new DateHistogramInterval(interval));
        Map<String, Map<Object, Object>> result = new HashMap<>();
        result.put("ais", aisAggs);
        result.put("so2", so2Aggs);
        result.put("black", heiyanAggs);
        return AjaxResult.success(result);
    }

    /*@DeleteMapping("/del")
    @ApiOperation("删除数据")
    public AjaxResult del() {
        if (StrUtil.isBlank(interval)) {
            // 默认值为1个月
            interval = "1M";
        }
        Map<Object, Object> aisAggs = client.dateHistogramAggs(ElasticConstants.AIS_ILLEGAL_SHIP, AggsType.count, "peakTime", "id", null, null, new DateHistogramInterval(interval));
        Map<Object, Object> so2Aggs = client.dateHistogramAggs(ElasticConstants.SO2_ALERT, AggsType.count, "createTime", "id", null, null, new DateHistogramInterval(interval));
        Map<Object, Object> heiyanAggs = client.dateHistogramAggs(ElasticConstants.HEIYAN_SHIP_RECOGNITION, AggsType.count, "snapTimeFmt", "id", null, null, new DateHistogramInterval(interval));
        Map<String, Map<Object, Object>> result = new HashMap<>();
        result.put("ais", aisAggs);
        result.put("so2", so2Aggs);
        result.put("black", heiyanAggs);
        return AjaxResult.success(result);
    }*/

}
