/**
 * Copyright 2019 DH
 * All right reserved.
 * 项目名称: 运维系统
 * 创建日期:2022/8/27
 */
package org.springblade.modules.business.home.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springblade.constant.BusinessConstant;
import org.springblade.constant.DictBusinessConstant;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.ConcurrentDateFormat;
import org.springblade.core.tool.utils.Func;
import org.springblade.enums.OrderCloseEnum;
import org.springblade.enums.OrderConfirmEnum;
import org.springblade.enums.OrderStatusEnum;
import org.springblade.modules.baseinfo.dict.entity.DictInfoEntity;
import org.springblade.modules.baseinfo.dict.service.IBaseInfoDictService;
import org.springblade.modules.baseinfo.monitorpoint.dto.MonitorPointInfoDTO;
import org.springblade.modules.baseinfo.monitorpoint.entity.MonitorPointInfoEntity;
import org.springblade.modules.baseinfo.monitorpoint.service.IMonitorPointService;
import org.springblade.modules.baseinfo.monitorsite.entity.MonitorSiteInfoEntity;
import org.springblade.modules.baseinfo.monitorsite.service.IMonitorSiteService;
import org.springblade.modules.baseinfo.org.entity.DeptRegionEntity;
import org.springblade.modules.baseinfo.org.service.IDeptRegionService;
import org.springblade.modules.baseinfo.region.entity.RegionInfoEntity;
import org.springblade.modules.baseinfo.region.service.IBaseInfoRegionService;
import org.springblade.modules.baseinfo.rtu.dto.RtuInfoDTO;
import org.springblade.modules.baseinfo.rtu.service.IRtuBaseInfoService;
import org.springblade.modules.baseinfo.wateruseconsumer.entity.WaterUseConsumerInfoEntity;
import org.springblade.modules.baseinfo.wateruseconsumer.service.IWaterUseConsumerService;
import org.springblade.modules.business.check.order.dto.CheckOrderInfoDTO;
import org.springblade.modules.business.check.order.entity.CheckOrderInfoEntity;
import org.springblade.modules.business.check.order.entity.CheckOrderSettingEntity;
import org.springblade.modules.business.check.order.service.ICheckOrderSettingService;
import org.springblade.modules.business.check.order.service.IRtuCheckOrderService;
import org.springblade.modules.business.check.order.vo.CheckOrderInfoVO;
import org.springblade.modules.business.check.process.dto.OrderProcessInfoDTO;
import org.springblade.modules.business.check.process.service.IRtuOrderProcessService;
import org.springblade.modules.business.data.dto.RtuDataGroundDTO;
import org.springblade.modules.business.data.dto.RtuDataRainDTO;
import org.springblade.modules.business.data.dto.RtuDataWaterLevelDTO;
import org.springblade.modules.business.data.service.*;
import org.springblade.modules.business.equipment.inspection.plan.entity.EquipmentInspectionPlanEntity;
import org.springblade.modules.business.equipment.inspection.plan.service.IEquipmentInspectionPlanService;
import org.springblade.modules.business.equipment.inspection.report.dto.EquipmentInspectionReportDTO;
import org.springblade.modules.business.equipment.inspection.report.service.IEquipmentInspectionReportService;
import org.springblade.modules.business.home.VO.*;
import org.springblade.modules.business.monitor.dto.WaterFlowRateHistoryInfoDTO;
import org.springblade.modules.business.monitor.service.IWaterFlowRateHistoryService;
import org.springblade.modules.business.notice.dto.NoticeDTO;
import org.springblade.modules.business.notice.entity.NoticeViewEntity;
import org.springblade.modules.business.notice.service.INoticeService;
import org.springblade.modules.business.notice.service.INoticeViewService;
import org.springblade.modules.business.warning.dto.RtuWarningInfoDTO;
import org.springblade.modules.business.warning.service.IRtuWarningService;
import org.springblade.modules.system.entity.Dept;
import org.springblade.modules.system.service.IDeptService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.Duration;
import java.util.*;

/***
 * Date:2022/8/27
 * Title:首页模块接口
 * Description：对本文件的详细描述，原则上不能少于30字
 * @author dylan
 * @version 1.0
 * Remark：认为有必要的其他信息
 */
@RestController
@Slf4j
@RequestMapping("galaxy-business/home")
@AllArgsConstructor
@Api(value = "实时数据管理模块", tags = "实时数据管理模块")
public class HomeController {
    private final IRtuCheckOrderService checkOrderService;
    private final INoticeService noticeService;
    private final INoticeViewService noticeViewService;
    private final IRtuBaseInfoService rtuBaseInfoService;
    private final IRtuWarningService rtuWarningService;
    private final IDeptRegionService deptRegionService;
    private final IEquipmentInspectionReportService inspectionReportService;
    private final ICheckOrderSettingService checkOrderSettingService;
    private final IEquipmentInspectionPlanService planService;
    private final IRtuOrderProcessService rtuOrderProcessService;
    private final IEquipmentInspectionReportService equipmentInspectionReportService;
    private final IDeptService deptService;
    private final IBaseInfoRegionService regionService;
    private final IBaseInfoDictService dictService;
    private final IRtuDataRainStoreService rainStoreService;
    private final IRtuDataWaterLevelStoreService waterLevelStoreService;
    private final IRtuDataGroundStoreService groundStoreService;

    private final IWaterUseConsumerService waterUseConsumerService;
    private final IMonitorSiteService monitorSiteService;
    private final IMonitorPointService monitorPointService;
    private final IWaterFlowRateHistoryService waterFlowRateHistoryService;

    @GetMapping("/rtu/status/count/info")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "详情")
    public R<RtuStatusCountInfoVO> rtuStatusCountInfo() {
        RtuStatusCountInfoVO infoVO = new RtuStatusCountInfoVO();
        //测站数量
        LambdaQueryWrapper<WaterUseConsumerInfoEntity> wrapper = Wrappers.<WaterUseConsumerInfoEntity>query().lambda();
        wrapper.eq(WaterUseConsumerInfoEntity::getIsDeleted, 0);
        long count = waterUseConsumerService.count(wrapper);
        infoVO.setWaterUseConsumers(count);

        LambdaQueryWrapper<MonitorSiteInfoEntity> wrapper2 = Wrappers.<MonitorSiteInfoEntity>query().lambda();
        wrapper2.eq(MonitorSiteInfoEntity::getIsDeleted, 0);
        count = monitorSiteService.count(wrapper2);
        infoVO.setMonitorSites(count);

        LambdaQueryWrapper<MonitorPointInfoEntity> wrapper3 = Wrappers.<MonitorPointInfoEntity>query().lambda();
        wrapper3.eq(MonitorPointInfoEntity::getIsDeleted, 0);
        count = monitorPointService.count(wrapper3);
        infoVO.setMonitorPoints(count);

        //预警数量
        RtuWarningInfoDTO dto = new RtuWarningInfoDTO();
        long warningRtuCount = rtuWarningService.warningRtuCount(dto);
        infoVO.setWarnRtus(warningRtuCount);
        //离线数量
        count = rtuWarningService.warningOfflineRtuCount(dto);
        infoVO.setOfflineRtus(count);
        //其他异常
        infoVO.setOtherWarnRtus((warningRtuCount - count));

        return R.data(infoVO);
    }

    @GetMapping("/rtu/up/count/info")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "详情")
    public R<RtuUpDataCountInfoVO> rtuUpCountInfo() {

        RtuUpDataCountInfoVO infoVO = new RtuUpDataCountInfoVO();
        LambdaQueryWrapper<MonitorPointInfoEntity> wrapper3 = Wrappers.<MonitorPointInfoEntity>query().lambda();
        wrapper3.eq(MonitorPointInfoEntity::getIsDeleted, 0);
        long count = monitorPointService.count(wrapper3);
        infoVO.setMonitorPoints(count);

        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        Date endTime = calendar.getTime();
        calendar.add(Calendar.HOUR_OF_DAY, -1);
        Date beiganTime = calendar.getTime();
        //监测点小时上报统计
        WaterFlowRateHistoryInfoDTO dto = new WaterFlowRateHistoryInfoDTO();
        dto.setBeginTime(beiganTime);
        dto.setEndTime(endTime);
        count = waterFlowRateHistoryService.rtuUpDataCount(dto);
        infoVO.setHourUpDataCount(count);

        calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        endTime = calendar.getTime();
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        beiganTime = calendar.getTime();
        //监测点日上报统计
        dto = new WaterFlowRateHistoryInfoDTO();
        dto.setBeginTime(beiganTime);
        dto.setEndTime(endTime);
        count = waterFlowRateHistoryService.rtuUpDataCount(dto);
        infoVO.setDayUpDataCount(count);

        return R.data(infoVO);
    }

    @GetMapping("/warn/count/list")
    @ApiOperationSupport(order = 3)
    @ApiOperation(value = "预警统计列表", notes = "")
    public R<List<WarnCountInfoVO>> warnCountInfoList() {
        List<WarnCountInfoVO> list = new LinkedList<>();
        //盟市统计
        LambdaQueryWrapper<Dept> wrapper = Wrappers.<Dept>query().lambda();
        wrapper.eq(Dept::getParentId,BusinessConstant.DEPT_XAM_ID);
        List<Dept> deptList = this.deptService.list(wrapper);
        for (Dept dept : deptList) {
            WarnCountInfoVO vo = new WarnCountInfoVO();
            //盟市名称
            vo.setDeptId(dept.getId());
            vo.setAdCity(dept.getDeptName());
            //测站数量
            MonitorPointInfoDTO rtuInfoDTO = new MonitorPointInfoDTO();
            rtuInfoDTO.setOrgId(dept.getId());
            long count = monitorPointService.getMonitorPointCount(rtuInfoDTO);
            vo.setRtus(count);
            //预警数量
            RtuWarningInfoDTO dto = new RtuWarningInfoDTO();
            dto.setDeptId(dept.getId());
            long warningRtuCount = rtuWarningService.warningRtuCount(dto);
            vo.setWarnRtus(warningRtuCount);
            //离线数量
            count = rtuWarningService.warningOfflineRtuCount(dto);
            vo.setOfflineRtus(count);
            //其他异常
            vo.setOtherWarnRtus((warningRtuCount - count));
            list.add(vo);
        }
        return R.data(list);
    }

    @GetMapping("/rtu/warn/kind/count/info")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "详情")
    public R<WarnKindCountInfoVO> rtuWarnKindCountInfo() {
        BladeUser user = AuthUtil.getUser();
        String adCode = null;
        int excludeCode = 0;
        if (BusinessConstant.ROLE_SYS_ADMIN.equals(user.getRoleName())) {
            adCode = BusinessConstant.REGION_NM_ADCODE;
        } else if (BusinessConstant.ROLE_ORG_ADMIN.equals(user.getRoleName()) || BusinessConstant.ROLE_COMPANY_ADMIN.equals(user.getRoleName()) || BusinessConstant.ROLE_COMPANY_SERVICE_PERSON.equals(user.getRoleName())) {
            LambdaQueryWrapper<DeptRegionEntity> deptRegionEntityLambdaQueryWrapper = Wrappers.<DeptRegionEntity>query().lambda();
            deptRegionEntityLambdaQueryWrapper.eq(DeptRegionEntity::getIsDeleted, 0);
            deptRegionEntityLambdaQueryWrapper.eq(DeptRegionEntity::getDeptId, Func.toLong(user.getDeptId()));
            DeptRegionEntity deptRegionEntity = deptRegionService.getOne(deptRegionEntityLambdaQueryWrapper);
            if (deptRegionEntity != null) {
                adCode = deptRegionEntity.getAdcd();
                LambdaQueryWrapper<RegionInfoEntity> regionWrapper = Wrappers.<RegionInfoEntity>query().lambda();
                regionWrapper.eq(RegionInfoEntity::getAdcd, deptRegionEntity.getAdcd());
                RegionInfoEntity regionInfoEntity = this.regionService.getOne(regionWrapper);
                if (regionInfoEntity.getParentCode().equals(BusinessConstant.REGION_NM_ADCODE)) {
                    excludeCode = 1;
                }
            }
        }
        if (null == adCode) {
            return R.status(false);
        }
        WarnKindCountInfoVO infoVO = new WarnKindCountInfoVO();
        RtuWarningInfoDTO dto = new RtuWarningInfoDTO();
        dto.setAdCode(adCode);
        dto.setExcludeCode(excludeCode);
        //异常测站总数
        Long count = rtuWarningService.warningRtuCount(dto);
        infoVO.setWarnRtus(count.intValue());
        //时钟异常数量
        count = rtuWarningService.warningClockRtuCount(dto);
        infoVO.setClockWarn(count.intValue());
        //离线数量
        count = rtuWarningService.warningOfflineRtuCount(dto);
        infoVO.setOfflineRtus(count.intValue());
        //雨量站小时漏报
        count = rtuWarningService.warningRainHourMissOutRtuCount(dto);
        infoVO.setRainUpMissOut(count.intValue());
        //水位站小时漏报
        count = rtuWarningService.warningRiverHourMissOutRtuCount(dto);
        infoVO.setRiverUpMissOut(count.intValue());
        //5分钟延时
        count = rtuWarningService.warningMinUpDelayRtuCount(dto);
        infoVO.setMinUpDelay(count.intValue());
        //雨量站小时延时
        count = rtuWarningService.warningRainHourUpDelayRtuCount(dto);
        infoVO.setRainHourUpDelay(count.intValue());
        //水位站小时延时
        count = rtuWarningService.warningRiverHourUpDelayRtuCount(dto);
        infoVO.setRiverHourUpDelay(count.intValue());
        //异常值
        count = rtuWarningService.warningOutlierValueRtuCount(dto);
        infoVO.setOutlierValue(count.intValue());
        return R.data(infoVO);
    }
}
