package com.tofly.water.controller;

/**
 * @author HaiQiu
 * @since 2022/11/22
 */

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.haiqiu.tools.common.utils.DateUtils;
import com.tofly.common.core.entity.ResultRespone;
import com.tofly.common.core.util.Date8Util;
import com.tofly.common.core.util.DateUtil;
import com.tofly.common.core.util.StringUtil;
import com.tofly.common.log.annotation.ToFlyAppLog;
import com.tofly.scada.service.ScadaService;
import com.tofly.water.config.CodeSetting;
import com.tofly.water.entity.dto.*;
import com.tofly.water.entity.vo.DeviceBusPumpsVo;
import com.tofly.water.entity.vo.MonitorPumpVo;
import com.tofly.water.service.OverviewService;
import io.swagger.annotations.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.util.ObjectUtils;
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.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Api(tags = "运营总览")
@RestController
@RequestMapping("overview")
@RefreshScope
public class OverviewController {

    /**
     * 主泵状态统计code
     */
    @Value("${comprehensive.codes:EG.SHABA.1#ZBZT}")
    private String comprehensives;

    /**
     * 水量code
     */
    @Value("${watersupply.codes:EG.SHABA.JLJ}")
    private String waterSupply;


    /**
     * 电量code
     */
    @Value("${powersupply.codes:EG.SHABA.JLJ}")
    private String powerSupply;

    @Resource
    private OverviewService overviewService;

    @Autowired
    private ScadaService monitorService;

    @Autowired
    private CodeSetting codeSetting;


    @Deprecated
    @ToFlyAppLog(title = "查询泵站和泵组历史scada数据和统计数据")
    @ApiOperation(value = "查询泵站和泵组历史scada数据和统计数据")
    @GetMapping("/whole")
    public ResultRespone<Page<DeviceBusPumpsVo>> whole(Page page, OverviewDto overviewDto) {
        return ResultRespone.success(overviewService.whole(page, overviewDto));
    }


    @Deprecated
    @ToFlyAppLog(title = "查询泵站和泵组历史报警数据")
    @ApiOperation(value = "查询泵站和泵组历史报警数据")
    @GetMapping("/alert")
    public ResultRespone<Page<DeviceBusPumpsVo>> alert(Page page, ReportDto reportDto) {
        return ResultRespone.success(overviewService.alert(page, reportDto));
    }

    @Deprecated
    @ToFlyAppLog(title = "查询泵站和泵组最新监控数据")
    @ApiOperation(value = "查询泵站和泵组最新监控数据")
    @GetMapping("/newest")
    public ResultRespone<Page<DeviceBusPumpsVo>> newest(Page page, NewestDto newestDto) {
        return ResultRespone.success(overviewService.newest(page, newestDto));
    }


    @ApiOperation(value = "查询泵站和统计运行停电停泵时长")
    @GetMapping("/comprehensive")
    public ResultRespone comprehensive(Page page, StatisticsRealDto dto,
                                       @ApiParam(value = "年份：2022", required = true) @RequestParam("year") String year) {
        dto.setCodes(Arrays.asList(comprehensives.split(",")));
        dto.setType(2);
        dto.setPage(false);
        String startTime = year + "-01-01 00:00:00";
        String endTime = year + "-12-31 23:59:59";
        dto.setStart(DateUtils.parseDate(startTime, "yyyy-MM-dd hh:mm:ss"));
        dto.setEnd(DateUtils.parseDate(endTime, "yyyy-MM-dd hh:mm:ss"));
        return ResultRespone.success(overviewService.statisticsReal(page, dto));
    }

    @ApiOperation(value = "供水报表")
    @GetMapping("/waterSupply")
    public ResultRespone waterSupply(Page page, StatisticsRealDto dto) {
        dto.setCodes(Arrays.asList(waterSupply.split(",")));
        Object o = overviewService.statisticsReal(page, dto);
        //查询泵站特殊处理
        if (dto.getIsGroup()) {
            if (!ObjectUtils.isEmpty(o) && !dto.getPage() && dto.getType().equals(2)) {
                return ResultRespone.success(overviewService.getMapResultRespone(dto, o, dto.getPumpStatisticsType()));
            }
        }
        return ResultRespone.success(o);
    }

    @ApiOperation(value = "app接口_水厂今日供水量")
    @GetMapping("/waterSupplyDay")
    public ResultRespone waterSupplyDay() {
        List<String> codes=Arrays.asList(waterSupply.split(","));
       return ResultRespone.success(overviewService.waterSupplyDay(codes));
    }

    @ApiOperation(value = "app接口_水厂今年供水量")
    @GetMapping("/waterSupplyYear")
    public ResultRespone waterSupplyYear() throws ParseException {
        List<String> codes=Arrays.asList(waterSupply.split(","));
        return ResultRespone.success(overviewService.waterSupplyYear(codes));
    }



    @ApiOperation(value = "app接口_泵站今日供水量")
    @GetMapping("/pumpSupplyDay")
    public ResultRespone pumpSupplyDay() {
        return ResultRespone.success(overviewService.pumpSupplyDay());
    }

    @ApiOperation(value = "app接口_泵站今年供水量")
    @GetMapping("/pumpSupplyYear")
    public ResultRespone pumpSupplyYear(){
        return ResultRespone.success(overviewService.pumpSupplyYear());
    }



    @ApiOperation(value = "供水报表_上月各水厂供水量,根据月份查询")
    @GetMapping("/waterSupplyLastMonth")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "startMonth",value = "开始月份yyyyMM",required = false,dataType = "String")
    })
    public ResultRespone waterSupplyLastMonth(String startMonth) {
        List<String> codes=Arrays.asList(waterSupply.split(","));
        Calendar calendar=Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.MONTH,-1);
        Date newTime=calendar.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
        String YearOrAndMonth = sdf.format(newTime);
        if(StringUtils.isNotEmpty(startMonth)){
            YearOrAndMonth=startMonth;
        }
        Object o = overviewService.waterSupplyOneMonth(YearOrAndMonth,codes);
        return ResultRespone.success(o);
    }

    @ApiOperation(value = "用电报表")
    @GetMapping("/powerSupply")
    public ResultRespone powerSupply(Page page, StatisticsRealDto dto) {
        dto.setCodes(Arrays.asList(powerSupply.split(",")));
        Object o = overviewService.statisticsReal(page, dto);
        //查询泵站特殊处理
        if (dto.getIsGroup()) {
            if (!ObjectUtils.isEmpty(o) && !dto.getPage() && dto.getType().equals(2)) {
                return ResultRespone.success(overviewService.getMapResultRespone(dto, o, dto.getPumpStatisticsType()));
            }
        }
        return ResultRespone.success(o);
    }


    @ApiOperation(value = "监测信息")
    @GetMapping("/monitor")
    public ResultRespone<Page<MonitorPumpVo>> monitor(Page page, MonitorDto overviewDto) {
        return ResultRespone.success(overviewService.monitor(page, overviewDto));
    }

    @ApiOperation(value = "监测信息(新)")
    @GetMapping("/monitorNew")
    public ResultRespone<Page<MonitorPumpVo>> monitorNew(Page page, MonitorDto overviewDto) {
        return ResultRespone.success(overviewService.monitorNew(page, overviewDto));
    }



    @ApiOperation(value = "监测信息(导出)")
    @GetMapping("/monitor/export")
    public void monitorExport(Page page, MonitorDto overviewDto, @ApiParam("是否导出全部") boolean exportAll) {
        overviewService.monitorExport(page, overviewDto, exportAll);
    }


    @ApiOperation(value = "根据水厂或泵站查询最新监控数据和报警")
    @GetMapping("/monitor/real")
    public ResultRespone monitorReal(Page page, MonitorRealDto dto) {
        return ResultRespone.success(overviewService.monitorReal(page, dto));
    }

    @ApiOperation(value = "根据水厂或泵站查询历史监控数据和报警")
    @GetMapping("/history/real")
    public ResultRespone historyReal(Page page, MonitorRealDto dto) {
        return ResultRespone.success(overviewService.historyReal(page, dto));
    }

    @ApiOperation(value = "根据水厂或泵站查询历史报警数据")
    @GetMapping("/report/real")
    public ResultRespone reportReal(Page page, MonitorRealDto dto) {
        return ResultRespone.success(overviewService.reportReal(page, dto));
    }

    @ApiOperation(value = "根据水厂或泵站查询历史统计数据")
    @GetMapping("/statistics/real")
    public ResultRespone statisticsReal(Page page, StatisticsRealDto dto) {
        return ResultRespone.success(overviewService.statisticsReal(page, dto));
    }

    @ApiOperation(value = "查询报警等级分组数量统计")
    @GetMapping("/report/count")
    public ResultRespone reportCount() {
        return ResultRespone.success(overviewService.reportCount());
    }

    @ApiOperation(value = "运行日志")
    @Deprecated
    @GetMapping("/run/log")
    public ResultRespone runLog(RunLogDto runLogDto, Page page) {
        return ResultRespone.success(overviewService.runLog(runLogDto, page));
    }

    @ApiOperation(value = "查询泵站或者泵组下面的指标配置")
    @GetMapping("/selectPumpByIndex")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "ids",value = "泵站或泵组ID",required = true,dataType = "array"),
            @ApiImplicitParam(name = "type",value = "查询类型：0泵站指标，1泵组指标",required = true)
    })
    public ResultRespone selectPumpByIndex(@RequestParam(required = false) List<Long> ids,
                                           @RequestParam(defaultValue = "0") Integer type){
        return ResultRespone.success(overviewService.selectPumpByIndex(ids, type));
    }




    @ApiOperation(value = "取水供水统计")
    @GetMapping("/waterIntake")
    public ResultRespone waterIntake(Page page, StatisticsRealDto dto) {
        dto.setCodes(Arrays.asList(codeSetting.getWaterIntake().split(",")));
        Object o = overviewService.statisticsReal(page, dto);
        //查询泵站特殊处理
        if (dto.getIsGroup()) {
            if (!ObjectUtils.isEmpty(o) && !dto.getPage() && dto.getType().equals(2)) {
                return ResultRespone.success(overviewService.getMapResultRespone(dto, o, dto.getPumpStatisticsType()));
            }
        }
        return ResultRespone.success(o);
    }




    @ApiOperation(value = "流失量历史曲线")
    @GetMapping("/amountOfLoss")
    public ResultRespone amountOfLoss(Page page, StatisticsRealDto dto) {
        dto.setCodes(Arrays.asList(codeSetting.getAmountOfLoss().split(",")));
        Object o = overviewService.statisticsReal(page, dto);
        //查询泵站特殊处理
        if (dto.getIsGroup()) {
            if (!ObjectUtils.isEmpty(o) && !dto.getPage() && dto.getType().equals(2)) {
                return ResultRespone.success(overviewService.getMapResultRespone(dto, o, dto.getPumpStatisticsType()));
            }
        }
        return ResultRespone.success(o);
    }

    @ApiOperation(value = "水压历史曲线")
    @GetMapping("/hydraulicPressure")
    public ResultRespone hydraulicPressure(Page page, StatisticsRealDto dto) {
        dto.setCodes(Arrays.asList(codeSetting.getHydraulicPressure().split(",")));
        Object o = overviewService.statisticsReal(page, dto);
        //查询泵站特殊处理
        if (dto.getIsGroup()) {
            if (!ObjectUtils.isEmpty(o) && !dto.getPage() && dto.getType().equals(2)) {
                return ResultRespone.success(overviewService.getMapResultRespone(dto, o, dto.getPumpStatisticsType()));
            }
        }
        return ResultRespone.success(o);
    }

    @ApiOperation(value = "出厂浊度历史曲线")
    @GetMapping("/factoryTurbidity")
    public ResultRespone factoryTurbidity(Page page, StatisticsRealDto dto) {
        dto.setCodes(Arrays.asList(codeSetting.getFactoryTurbidity().split(",")));
        Object o = overviewService.statisticsReal(page, dto);
        //查询泵站特殊处理
        if (dto.getIsGroup()) {
            if (!ObjectUtils.isEmpty(o) && !dto.getPage() && dto.getType().equals(2)) {
                return ResultRespone.success(overviewService.getMapResultRespone(dto, o, dto.getPumpStatisticsType()));
            }
        }
        return ResultRespone.success(o);
    }

    @ApiOperation(value = "出厂余氯历史曲线")
    @GetMapping("/exFactoryResidualChlorine")
    public ResultRespone exFactoryResidualChlorine(Page page, StatisticsRealDto dto) {
        dto.setCodes(Arrays.asList(codeSetting.getExFactoryResidualChlorine().split(",")));
        Object o = overviewService.statisticsReal(page, dto);
        //查询泵站特殊处理
        if (dto.getIsGroup()) {
            if (!ObjectUtils.isEmpty(o) && !dto.getPage() && dto.getType().equals(2)) {
                return ResultRespone.success(overviewService.getMapResultRespone(dto, o, dto.getPumpStatisticsType()));
            }
        }
        return ResultRespone.success(o);
    }


    @ApiOperation(value = "出厂PH历史曲线")
    @GetMapping("/exFactoryPh")
    public ResultRespone exFactoryPh(Page page, StatisticsRealDto dto) {
        dto.setCodes(Arrays.asList(codeSetting.getExFactoryPh().split(",")));
        Object o = overviewService.statisticsReal(page, dto);
        //查询泵站特殊处理
        if (dto.getIsGroup()) {
            if (!ObjectUtils.isEmpty(o) && !dto.getPage() && dto.getType().equals(2)) {
                return ResultRespone.success(overviewService.getMapResultRespone(dto, o, dto.getPumpStatisticsType()));
            }
        }
        return ResultRespone.success(o);
    }


    @ApiOperation(value = "流水历史曲线")
    @GetMapping("/flowingWater")
    public ResultRespone flowingWater(Page page, StatisticsRealDto dto) {
        dto.setCodes(Arrays.asList(codeSetting.getFlowingWater().split(",")));
        Object o = overviewService.statisticsReal(page, dto);
        //查询泵站特殊处理
        if (dto.getIsGroup()) {
            if (!ObjectUtils.isEmpty(o) && !dto.getPage() && dto.getType().equals(2)) {
                return ResultRespone.success(overviewService.getMapResultRespone(dto, o, dto.getPumpStatisticsType()));
            }
        }
        return ResultRespone.success(o);
    }

    @ApiOperation(value = "水质合格率")
    @GetMapping("/qualifiedRateOfWaterQuality")
    public ResultRespone qualifiedRateOfWaterQuality(Page page, StatisticsRealDto dto) {
        dto.setCodes(Arrays.asList(codeSetting.getQualifiedRateOfWaterQuality().split(",")));
        Object o = overviewService.statisticsReal(page, dto);
        //查询泵站特殊处理
        if (dto.getIsGroup()) {
            if (!ObjectUtils.isEmpty(o) && !dto.getPage() && dto.getType().equals(2)) {
                return ResultRespone.success(overviewService.getMapResultRespone(dto, o, dto.getPumpStatisticsType()));
            }
        }
        return ResultRespone.success(o);
    }

    @ApiOperation(value = "日供水吨")
    @GetMapping("/dailyWaterSupply")
    public ResultRespone dailyWaterSupply(Page page, StatisticsRealDto dto) {
        dto.setCodes(Arrays.asList(codeSetting.getDailyWaterSupply().split(",")));
        Object o = overviewService.statisticsReal(page, dto);
        //查询泵站特殊处理
        if (dto.getIsGroup()) {
            if (!ObjectUtils.isEmpty(o) && !dto.getPage() && dto.getType().equals(2)) {
                return ResultRespone.success(overviewService.getMapResultRespone(dto, o, dto.getPumpStatisticsType()));
            }
        }
        return ResultRespone.success(o);
    }

    @ApiOperation(value = "获取指标动态配置信息")
    @GetMapping("/codeSetting")
    public ResultRespone codeSetting() {
        return ResultRespone.success(JSONObject.toJSON(codeSetting));
    }

}
