package com.njcn.prepare.harmonic.controller.dim;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.core.util.StrUtil;
import com.njcn.common.pojo.annotation.OperateInfo;
import com.njcn.common.pojo.enums.common.LogEnum;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.common.utils.HttpResultUtil;
import com.njcn.common.utils.LogUtil;
import com.njcn.device.biz.commApi.CommTerminalGeneralClient;
import com.njcn.device.biz.pojo.dto.DeptGetChildrenDTO;
import com.njcn.device.biz.pojo.dto.DeptGetChildrenMoreDTO;
import com.njcn.device.biz.pojo.param.DeptGetLineParam;
import com.njcn.harmonic.pojo.param.UploadParam;
import com.njcn.prepare.harmonic.api.liteflow.LiteFlowFeignClient;
import com.njcn.prepare.harmonic.pojo.bo.BaseParam;
import com.njcn.prepare.harmonic.pojo.bo.CalculatedParam;
import com.njcn.prepare.harmonic.pojo.param.DeviceAbnormaStatisticsParam;
import com.njcn.prepare.harmonic.service.mysql.dim.*;
import com.njcn.prepare.harmonic.service.mysql.upload.*;
import com.njcn.user.api.DeptFeignClient;
import com.njcn.user.pojo.po.Dept;
import com.njcn.web.controller.BaseController;
import com.njcn.web.pojo.annotation.DateTimeStrValid;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.time.LocalDate;
import java.util.*;

/**
 * pqs
 *
 * @author cdf
 * @date 2023/11/20
 */

@Slf4j
@Api(tags = "母线变电站每日运行情况统计")
@RestController
@RequestMapping("/dimGlobal")
@RequiredArgsConstructor
public class IRDimBusGlobalDController extends BaseController {

    private final IRDimBusGlobalDService irDimBusGlobalDService;

    private final IRDimMonitorRateDService irDimMonitorRateDService;

    private final IRDimMonitorRateMService irDimMonitorRateMService;

    private final IRDimObjRateDService irDimObjRateDService;

    private final IRDimObjRateMService irDimObjRateMService;

    private final IRDimObjRateYService irDimObjRateYService;

    private final IRDimMonitorRateYService irDimMonitorRateYService;

    private final CommTerminalGeneralClient commTerminalGeneralClient;

    private final DeptFeignClient deptFeignClient;

    private final LiteFlowFeignClient liteFlowFeignClient;


    private final IPmsRunStatisticService iPmsRunStatisticService;

    private final IPmsRunStatisticMService iPmsRunStatisticMService;

    private final IPmsRunStatisticYService iPmsRunStatisticYService;

    private final IRDimBusUpDService irDimBusUpDService;

    private final IRDimBusUpMService irDimBusUpMService;

    private final IRDimBusUpYService irDimBusUpYService;

    @OperateInfo(info = LogEnum.BUSINESS_COMMON)
    @PostMapping("/dayDimGlobal")
    @ApiOperation("母线变电站每日运行情况统计")
    @ApiImplicitParam(name = "calculatedParam", value = "参数", required = true)
    public HttpResult<Boolean> dayDimGlobal(@RequestBody CalculatedParam calculatedParam) {
        String methodDescribe = getMethodDescribe("dayDimGlobal");
        irDimBusGlobalDService.globalCalBusBarDay(calculatedParam);
        return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
    }



    @OperateInfo(info = LogEnum.BUSINESS_COMMON)
    @PostMapping("/monitorRate")
    @ApiOperation("母线变电站监测率统计")
    @ApiImplicitParam(name = "calculatedParam", value = "参数", required = true)
    public HttpResult<Boolean> monitorRate(@RequestBody CalculatedParam calculatedParam) {
        String methodDescribe = getMethodDescribe("monitorRate");

        Dept data = deptFeignClient.getRootDept().getData();
        DeptGetLineParam deptGetLineParam = new DeptGetLineParam();
        deptGetLineParam.setDeptId(data.getId());
        deptGetLineParam.setSystemType(0);
        List<DeptGetChildrenDTO> dept = commTerminalGeneralClient.deptGetLineList(deptGetLineParam).getData();
        calculatedParam.setIdList(dept);
        calculatedParam.setDataDate("2023-11-22");

        irDimMonitorRateDService.monitorRateDay(calculatedParam);


        irDimMonitorRateMService.monitorRateMonth(calculatedParam);


        irDimMonitorRateYService.monitorRateYear(calculatedParam);
        return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
    }


    @OperateInfo(info = LogEnum.BUSINESS_COMMON)
    @PostMapping("/objMonitorRate")
    @ApiOperation("源荷类型监测率统计")
    @ApiImplicitParam(name = "calculatedParam", value = "参数", required = true)
    public HttpResult<Boolean> objMonitorRate(@RequestBody CalculatedParam calculatedParam) {
        String methodDescribe = getMethodDescribe("objMonitorRate");

        Dept data = deptFeignClient.getRootDept().getData();
        DeptGetLineParam deptGetLineParam = new DeptGetLineParam();
        deptGetLineParam.setDeptId(data.getId());
        deptGetLineParam.setSystemType(0);
        List<DeptGetChildrenDTO> dept = commTerminalGeneralClient.deptGetLineList(deptGetLineParam).getData();
        calculatedParam.setIdList(dept);


        irDimObjRateDService.objMonitorRateDay(calculatedParam);


        irDimObjRateMService.objMonitorRateMonth(calculatedParam);


        irDimObjRateYService.objMonitorRateYear(calculatedParam);
        return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
    }



    /**
     * 重新计算四个算法
     * @author cdf
     * @date 2024/2/22
     */
    @OperateInfo(info = LogEnum.BUSINESS_COMMON)
    @GetMapping("/reCalUploadAlgorithm")
    @ApiOperation("重新计算四个算法")
    @ApiImplicitParam(name = "statisticDate", value = "重新计算的日期", required = true)
    public HttpResult<String> reCalUploadAlgorithm(@DateTimeStrValid @RequestParam("statisticDate") String statisticDate,@RequestParam("type") String type) {
        String methodDescribe = getMethodDescribe("reCalUploadAlgorithm");
        Set<String> set = new HashSet<>();
        if(StrUtil.isBlank(type)){
            BaseParam baseParam = new BaseParam();
            baseParam.setFullChain(true);
            baseParam.setRepair(false);
            baseParam.setDataDate(statisticDate);
            liteFlowFeignClient.uploadOrgExecutor(baseParam);

            baseParam.setFullChain(false);
            baseParam.setRepair(false);
            baseParam.setDataDate(statisticDate);

            set.add("r_upload_substation_statistical_data_m");
            set.add("r_upload_substation_statistical_data_y");
            baseParam.setTagNames(set);
            liteFlowFeignClient.substationExecutor(baseParam);
        }else if("0".equals(type)){
            //基准
            BaseParam baseParam = new BaseParam();
            baseParam.setFullChain(false);
            baseParam.setRepair(false);
            set.add("r_upload_evaluation_data_d");
            set.add("r_upload_evaluation_data_m");
            set.add("r_upload_evaluation_data_y");
            baseParam.setDataDate(statisticDate);
            baseParam.setTagNames(set);
            liteFlowFeignClient.uploadOrgExecutor(baseParam);
        }else if("1".equals(type)){
            //主配网
            BaseParam baseParam = new BaseParam();
            baseParam.setFullChain(false);
            baseParam.setRepair(false);
            set.add("r_upload_point_statistical_data_d");
            set.add("r_upload_point_statistical_data_m");
            set.add("r_upload_point_statistical_data_y");
            baseParam.setDataDate(statisticDate);
            baseParam.setTagNames(set);
            liteFlowFeignClient.uploadOrgExecutor(baseParam);
        }else if("2".equals(type)){
            //电站
            BaseParam baseParam = new BaseParam();
            baseParam.setFullChain(false);
            baseParam.setRepair(false);
            set.add("r_upload_substation_statistical_data_m");
            set.add("r_upload_substation_statistical_data_y");
            baseParam.setDataDate(statisticDate);
            baseParam.setTagNames(set);
            liteFlowFeignClient.substationExecutor(baseParam);
        }else if("3".equals(type)){
            //典型
            BaseParam baseParam = new BaseParam();
            baseParam.setFullChain(false);
            baseParam.setRepair(false);
            set.add("pq_typical_source_create_d");
            set.add("pq_typical_source_create_m");
            set.add("pq_typical_source_create_y");
            baseParam.setDataDate(statisticDate);
            baseParam.setTagNames(set);
            liteFlowFeignClient.uploadOrgExecutor(baseParam);
        }

        return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
    }



    /**
     * 选择月，会补招这个月每天的数据
     * @author cdf
     * @date 2024/3/22
     */
    @OperateInfo(info = LogEnum.BUSINESS_COMMON)
    @GetMapping("/reCalMonthUploadAlgorithm")
    @ApiOperation("补招月每天的数据")
    @ApiImplicitParam(name = "statisticDate", value = "重新计算的月份", required = true)
    public HttpResult<String> reCalUploadAlgorithmAllMonth(@DateTimeStrValid(format = "yyyy-MM") @RequestParam("statisticDate") String statisticDate,@RequestParam("type") String type) {
        String methodDescribe = getMethodDescribe("reCalUploadAlgorithmAllMonth");
        Set<String> set = new HashSet<>();

        String startDate = DateUtil.format(DateUtil.beginOfDay(DateUtil.parse(statisticDate,DatePattern.NORM_MONTH_PATTERN)),DatePattern.NORM_DATE_PATTERN);
        String endDate = DateUtil.format(new Date(),DatePattern.NORM_DATE_PATTERN);

        BaseParam baseParam = new BaseParam();
        baseParam.setFullChain(false);
        baseParam.setRepair(true);
        baseParam.setBeginTime(startDate);
        baseParam.setEndTime(endDate);

        if(StrUtil.isBlank(type)){
            throw new BusinessException("请选择需要重新计算的类型");
        }else if("0".equals(type)){
            //基准
            set.add("r_upload_evaluation_data_d");
            baseParam.setTagNames(set);
            liteFlowFeignClient.uploadOrgExecutor(baseParam);
        }else if("1".equals(type)){
            //主配网
            set.add("r_upload_point_statistical_data_d");
            baseParam.setTagNames(set);
            liteFlowFeignClient.uploadOrgExecutor(baseParam);
        }else if("2".equals(type)){
            //电站
            baseParam.setFullChain(false);
            baseParam.setRepair(false);
            baseParam.setDataDate(endDate);
//            set.add("r_upload_substation_statistical_data_m");
            set.add("r_upload_substation_statistical_data_y");
            baseParam.setTagNames(set);
            liteFlowFeignClient.substationExecutor(baseParam);
        }else if("3".equals(type)){
            //典型
            set.add("pq_typical_source_create_d");
            baseParam.setDataDate(statisticDate);
            baseParam.setTagNames(set);
            liteFlowFeignClient.uploadOrgExecutor(baseParam);
        }

        return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
    }


    /**
     * 统计每日运行测点装置详细信息
     * @author cdf
     * @date 2024/4/17
     */
    @GetMapping("runLedgerStatistic")
    @ApiOperation("统计每日运行测点装置详细信息")
    @Async("asyncExecutor")
    public void runLedgerStatistic(@RequestParam("date") String date) {
        TimeInterval timeInterval = new TimeInterval();
        iPmsRunStatisticService.statisticLedgerRunDay(date);

        iPmsRunStatisticMService.statisticLedgerRunMonth(date);

        iPmsRunStatisticYService.statisticLedgerRunYear(date);

        System.out.println(timeInterval.intervalSecond());
    }


    @GetMapping("dimBusUpEveryDay")
    @ApiOperation("统计每日母线稳态超标详情")
    @Async("asyncExecutor")
    public void dimBusUpEveryDay(@RequestParam("date") String date) {

        irDimBusUpDService.handBusDay(date);

        irDimBusUpMService.handMonth(date);

        irDimBusUpYService.handYear(date);

    }



}
