package com.zcxk.charge.web.controller;

import com.zcxk.charge.api.dto.query.*;
import com.zcxk.charge.api.enums.ReportTypeEnum;
import com.zcxk.charge.api.vo.MonitorDataChartReportDeviceVo;
import com.zcxk.charge.web.service.MonitorDataReportService;
import com.zcxk.core.common.pojo.AjaxMessage;
import com.zcxk.core.common.util.BeanCopyUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @description
 * @author  wangli
 * @data 2020-12-02 8:19
 */
@RestController
@RequestMapping("/monitorDataReport")
@Api(tags = "统计分析")
public class MonitorDataReportController extends BaseController{

    @Autowired
    private MonitorDataReportService monitorDataReportService;

    @RequestMapping(value = "monitorDataChartReport",method = RequestMethod.POST)
    @ApiOperation(value = "统计分析——图表")
    public AjaxMessage monitorDataChartReport(@RequestBody @Valid MonitorDataQueryDto dto){
        ReportTypeEnum typeEnum = ReportTypeEnum.getReportTypeEnum(dto.getReportType());
        if (typeEnum == null) {
            return AjaxMessage.success();
        }
        LocalDate localDate = getLocalDate(dto.getReportDate(), dto.getReportType());
        List<MonitorDataChartReportDeviceVo> result = new ArrayList<>();
        ChartReportDto chartDto = new ChartReportDto();
        chartDto.setSceneId(dto.getSceneId());
        chartDto.setYear(localDate.getYear());
        chartDto.setMonth(localDate.getMonthValue());
        chartDto.setDay(localDate.getDayOfMonth());
        chartDto.setStartTime(dto.getStartTime());
        chartDto.setEndTime(dto.getEndTime());
        switch (typeEnum) {
            case DAY:
                result = monitorDataReportService.monitorDataChartReportByDay(chartDto);
                break;
            case MONTH:
                result = monitorDataReportService.monitorDataChartReportByMonth(chartDto);
                break;
            case YEAR:
                result = monitorDataReportService.monitorDataChartReportByYear(chartDto);
                break;
            case CUSTOM:
                if(StringUtils.isNotEmpty(dto.getStartTime()) && StringUtils.isNotEmpty(dto.getEndTime())) {
                    result = monitorDataReportService.monthMonitorData(chartDto);
                }
                break;
            default:
        }
        return AjaxMessage.success(result);
    }

    @RequestMapping(value = "monitorDataCompareReport",method = RequestMethod.POST)
    @ApiOperation(value = "统计分析——对比,按集合顺序取，能耗——水质——报警")
    public AjaxMessage monitorDataCompareReport(@RequestBody @Valid MonitorDataCompareDto dto){
        List<List<MonitorDataChartReportDeviceVo>> reportList = new ArrayList<>();
        if (CollectionUtils.isEmpty(dto.getSceneIds())){
            return AjaxMessage.success(reportList);
        }
        LocalDate localDate = getLocalDate(dto.getReportDate(), dto.getReportType());
        MonitorDataCompareQueryDto queryDto = new MonitorDataCompareQueryDto();
        BeanCopyUtils.copyProperties(dto, queryDto, MonitorDataCompareQueryDto.class);
        queryDto.setYear(localDate.getYear());
        queryDto.setMonth(localDate.getMonthValue());
        queryDto.setDay(localDate.getDayOfMonth());
        // 能耗（供水量3、耗电量5 ）（4取水量、5耗电量）
        List<MonitorDataChartReportDeviceVo> energy = monitorDataReportService.monitorDataEnergyReport(queryDto);
        // 水质（PH8、余氯11、浊度10）
        List<MonitorDataChartReportDeviceVo> quality = monitorDataReportService.monitorDataQualityReport(queryDto);
        // 水电耗
        List<MonitorDataChartReportDeviceVo> consumption = monitorDataReportService.monitorWaterPowerConsumptionReport(queryDto);
        // 报警（报警次数）
        List<MonitorDataChartReportDeviceVo> alarm = monitorDataReportService.deviceAlarmReport(queryDto);

        Map<String,MonitorDataChartReportDeviceVo> map = consumption.stream().collect(Collectors.toMap(MonitorDataChartReportDeviceVo::getDeviceName, a -> a,(k1, k2)->k1));
        for (MonitorDataChartReportDeviceVo energyDto: energy) {
            MonitorDataChartReportDeviceVo reportDeviceDto =  map.get(energyDto.getDeviceName());
            energyDto.getAttributeData().addAll(reportDeviceDto.getAttributeData());
        }
        reportList.add(energy);
        reportList.add(quality);
        reportList.add(alarm);
        return AjaxMessage.success(reportList);
    }

    @RequestMapping(value = "getLocalDate",method = RequestMethod.GET)
    @ApiOperation(value = "补充完整时间")
    private LocalDate getLocalDate(@RequestParam @ApiParam(value = "日期，格式：2020-12-12", required = true) String reportDate,
                                   @RequestParam @ApiParam(value = "类型,1年2月3日", required = true) Integer reportType) {
        int month = 2;
        LocalDate localDate = LocalDate.now();
        if (reportType != null && reportType == 1) {
            reportDate = reportDate + "-01-01";
        } else if (reportType != null && reportType == month) {
            reportDate = reportDate + "-01";
        }
        if (null != reportDate) {
            localDate = LocalDate.parse(reportDate, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        }
        return localDate;
    }


    @RequestMapping(value = "getDeviceBySceneTypeName",method = RequestMethod.GET)
    @ApiOperation(value = "按场景类型查询设备（压力、流量、水质等）")
    public AjaxMessage getDeviceBySceneTypeName(@ApiParam(value = "场景类型", required = true) @RequestParam String sceneTypeName){
        return AjaxMessage.success(monitorDataReportService.getDeviceBySceneTypeName(sceneTypeName));
    }

    @RequestMapping(value = "monitorDataChartReportByDevice",method = RequestMethod.POST)
    @ApiOperation(value = "统计分析——管网图表")
    public AjaxMessage monitorDataChartReportByDevice(@RequestBody @Valid MonitorDataChartDto dto){
        if(CollectionUtils.isEmpty(dto.getDeviceIds())){
            return AjaxMessage.success();
        }
        LocalDate localDate = getLocalDate(dto.getReportDate(), dto.getReportType());
        MonitorDataChartQueryDto queryDto = new MonitorDataChartQueryDto();
        BeanCopyUtils.copyProperties(dto, queryDto, MonitorDataChartQueryDto.class);
        queryDto.setYear(localDate.getYear());
        queryDto.setMonth(localDate.getMonthValue());
        queryDto.setDay(localDate.getDayOfMonth());
        return AjaxMessage.success(monitorDataReportService.monitorDataDeviceReport(queryDto));
    }

    @RequestMapping(value = "monitorDataGeneralView",method = RequestMethod.GET)
    @ApiOperation(value = "统计分析——管网图表")
    public AjaxMessage monitorDataGeneralView(){
        return AjaxMessage.success(monitorDataReportService.monitorDataGeneralView());
    }

    @RequestMapping(value = "getDeviceWaterSupplie",method = RequestMethod.GET)
    @ApiOperation(value = "概览首页——近15天水量")
    public AjaxMessage getDeviceWaterSupplie(){
        return AjaxMessage.success(monitorDataReportService.deviceWaterSupplie());
    }

    @RequestMapping(value = "deviceWaterAmount",method = RequestMethod.GET)
    @ApiOperation(value = "概览首页——供水详情数据")
    public AjaxMessage deviceWaterAmount(){
        return AjaxMessage.success(monitorDataReportService.deviceWaterAmount());
    }

    @RequestMapping(value = "sceneAlarms",method = RequestMethod.GET)
    @ApiOperation(value = "概览首页——供水实时报警信息")
    public AjaxMessage sceneAlarms(){
        return AjaxMessage.success(monitorDataReportService.sceneAlarms());
    }

    @RequestMapping(value = "sceneNormalRates",method = RequestMethod.GET)
    @ApiOperation(value = "概览首页——管网水质情况")
    public AjaxMessage sceneNormalRates(){
        return AjaxMessage.success(monitorDataReportService.sceneNormalRates());
    }

    @RequestMapping(value = "sceneWaterPressure",method = RequestMethod.GET)
    @ApiOperation(value = "概览首页——压力分布区间")
    public AjaxMessage sceneWaterPressure(){
        return AjaxMessage.success(monitorDataReportService.sceneWaterPressure(WATER_WORKS.getMessage()));
    }

    @RequestMapping(value = "sceneWaterAmounts",method = RequestMethod.GET)
    @ApiOperation(value = "概览首页——水量排行")
    public AjaxMessage sceneWaterAmounts(){
        return AjaxMessage.success(monitorDataReportService.sceneWaterAmounts());
    }

    @RequestMapping(value = "waterSupplyCharts",method = RequestMethod.GET)
    @ApiOperation(value = "概览首页——对比曲线图")
    public AjaxMessage waterSupplyCharts(){
        return AjaxMessage.success(monitorDataReportService.waterSupplyCharts(WATER_WORKS.getMessage()));
    }

}
