package com.ruoyi.web.controller.gas;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.annotation.Log;
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.enums.AggsType;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.config.ElasticSearchClient;
import com.ruoyi.system.domain.ShipRecognition;
import com.ruoyi.system.service.ISysDictTypeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
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/24
 * @Version V1.0
 */
@RestController
@RequestMapping("/black")
@Api(tags = "黑烟接口")
public class BlackGasController extends BaseController {

    @Autowired
    private ElasticSearchClient client;
    @Autowired
    private ISysDictTypeService dictTypeService;

    @GetMapping("/list")
    @ApiOperation("列表数据")
    public TableDataInfo list(ShipRecognition shipRecognition) {
        // 传来的参数
        Map<String, Object> params = shipRecognition.getParams();
        Map<String, Object> equalsCondition = new HashMap<>();
        // 组装查询条件
        equalsCondition.put("aisMmsi", ObjectUtil.isEmpty(shipRecognition.getAisMmsi()) ? null : StrUtil.concat(true, "*", Convert.toStr(shipRecognition.getAisMmsi()), "*"));
        equalsCondition.put("aisShipName", StrUtil.isBlank(shipRecognition.getAisShipName()) ? null : StrUtil.concat(true, "*", shipRecognition.getAisShipName(), "*"));
        equalsCondition.put("snapPos", StrUtil.isBlank(shipRecognition.getSnapPos()) ? null : StrUtil.concat(true, "*", shipRecognition.getSnapPos(), "*"));
        equalsCondition.put("shipRegionType", shipRecognition.getShipRegionType());
        equalsCondition.put("rcgSoot", shipRecognition.getRcgSoot());
        equalsCondition.put("illegalStatus", shipRecognition.getIllegalStatus());
        // 组装范围查询条件
        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("snapTimeFmt", StrUtil.concat(true, "[", Convert.toStr(params.get("beginTime")), ",", Convert.toStr(params.get("endTime")), "]"));
        List<String> orderBy = new ArrayList<>();
        orderBy.add("-snapTime");
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Map<String, Object> maps = client.searchDocument(equalsCondition, rangeCondition, orderBy, pageDomain.getPageNum(), pageDomain.getPageSize(), ElasticConstants.HEIYAN_SHIP_RECOGNITION);

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

    @SneakyThrows
    @Log(title = "黑烟记录导出", businessType = BusinessType.EXPORT)
//    @PreAuthorize("@ss.hasPermi('system:black:export')")
    @GetMapping("/export")
    public void export(ShipRecognition shipRecognition, HttpServletRequest request, HttpServletResponse response) {
        // 传来的参数
        Map<String, Object> params = shipRecognition.getParams();
        Map<String, Object> equalsCondition = new HashMap<>();
        // 组装查询条件
        equalsCondition.put("aisMmsi", ObjectUtil.isEmpty(shipRecognition.getAisMmsi()) ? null : StrUtil.concat(true, "*", Convert.toStr(shipRecognition.getAisMmsi()), "*"));
        equalsCondition.put("aisShipName", StrUtil.isBlank(shipRecognition.getAisShipName()) ? null : StrUtil.concat(true, "*", shipRecognition.getAisShipName(), "*"));
        equalsCondition.put("snapPos", StrUtil.isBlank(shipRecognition.getSnapPos()) ? null : StrUtil.concat(true, "*", shipRecognition.getSnapPos(), "*"));
        equalsCondition.put("aisDst", StrUtil.isBlank(shipRecognition.getAisDst()) ? null : StrUtil.concat(true, "*", shipRecognition.getAisDst(), "*"));
        equalsCondition.put("aisShipType", StrUtil.isBlank(shipRecognition.getAisShipType()) ? null : StrUtil.concat(true, "*", shipRecognition.getAisShipType(), "*"));
        equalsCondition.put("rcgSoot", shipRecognition.getRcgSoot());
        // 组装范围查询条件
        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("snapTimeFmt", StrUtil.concat(true, "[", Convert.toStr(params.get("beginTime")), ",", Convert.toStr(params.get("endTime")), "]"));
        List<String> orderBy = new ArrayList<>();
        orderBy.add("-snapTime");
        Map<String, Object> maps = client.searchDocument(equalsCondition, rangeCondition, orderBy, 0, 10000, ElasticConstants.HEIYAN_SHIP_RECOGNITION);
        ExcelUtil<ShipRecognition> util = new ExcelUtil<>(ShipRecognition.class);
        util.exportExcelByEasyPoi("黑烟违规数据_" + DateUtil.today(),
                "黑烟违规数据",
                "黑烟违规数据",
                ShipRecognition.class,
                Convert.toList(ShipRecognition.class, maps.get("pageList")),
                request, response);
    }

    @GetMapping("/snapPos/static")
    @ApiOperation("黑烟抓拍分布统计")
    public AjaxResult snapPosStatic(@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> rangeCondition = new HashMap<>();
        rangeCondition.put("snapTimeFmt", StrUtil.concat(true, "[", beginTime, ",", endTime, "]"));
        Map<Object, Object> aggs = client.aggs(ElasticConstants.HEIYAN_SHIP_RECOGNITION, AggsType.count, "snapPos", "id", null, rangeCondition);
        // 构造黑烟的数据
        List<SysDictData> heiyan_snap_pos = dictTypeService.selectDictDataByType("heiyan_snap_pos");
        Map<String, Object> result = new HashMap<>();
        for (SysDictData heiyan_snap_po : heiyan_snap_pos) {
            result.put(heiyan_snap_po.getDictLabel(), ObjectUtil.isEmpty(aggs.get(heiyan_snap_po.getDictLabel())) ? 0 : aggs.get(heiyan_snap_po.getDictLabel()));
        }
        return AjaxResult.success(result);
    }

}
