package com.lutao.cloud.oil.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lutao.cloud.common.core.util.MessageInfo;
import com.lutao.cloud.common.core.util.StringUtil;
import com.lutao.cloud.oil.mapper.*;
import com.lutao.cloud.oil.pojo.param.*;
import com.lutao.cloud.oil.pojo.vo.*;
import com.lutao.cloud.oil.service.*;
import com.lutao.cloud.oil.util.DateUtils;
import com.lutao.entity.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@Service
@Slf4j
public class IBusinessSecurityRiskControlServiceImpl implements IBusinessSecurityRiskControlService {

    @Resource
    private PlatformInfoService platformInfoService;

    @Resource
    private HighRiskOperationService highRiskOperationService;

    @Resource
    private EmergencyRecordService emergencyRecordService;

    @Resource
    private RecordManageService recordManageService;

    @Resource
    private ChangeInfoService changeInfoService;

    @Resource
    private MattersManagerService mattersManagerService;

    @Resource
    private GiveupMineReportService giveupMineReportService;

    @Resource
    private HighRiskOperationMapper highRiskOperationMapper;

    @Resource
    private ContractorManageMapper contractorManageMapper;

    @Resource
    private CriticalAreaMapper criticalAreaMapper;

    @Resource
    private MattersManagerMapper mattersManagerMapper;

    @Resource
    private PlatformInfoMapper platformInfoMapper;

    @Resource
    private EmergencyRecordMapper emergencyRecordMapper;

    @Resource
    private ChangeInfoMapper changeInfoMapper;

    @Resource
    private RecordManageMapper recordManageMapper;

    @Resource
    private GiveupMineReportMapper giveupMineReportMapper;


    @Override
    public MessageInfo<SeaPlatformPersonAndEquipmentVO> querySeaPlatformPersonAndEquipment(BaseParam baseParam) {
        SeaPlatformPersonAndEquipmentVO seaPlatformPersonAndEquipmentVO = platformInfoMapper.getSeaPlatformPersonAndEquipmentVO(baseParam);
        return MessageInfo.ok(seaPlatformPersonAndEquipmentVO);
    }

    @Override
    public MessageInfo<IPage<SeaPlatformEquipmentInfoVO>> querySeaPlatformEquipmentInfo(Page page,BaseParam param) {
        IPage<SeaPlatformEquipmentInfoVO> seaPlatformEquipmentInfoVOS = platformInfoMapper.selectPlatformEquipInfo(page, param);
        return MessageInfo.ok(seaPlatformEquipmentInfoVOS);
    }


    @Override
    public MessageInfo<HighRiskModelVO> queryHighRiskModel(Page page, BaseParam param) {

        //高风险作业次数---人数
        List<HighRiskOperation> riskOperations = highRiskOperationMapper.getHighRiskOperationListToday(param);

        //高风险作业人数
        int highRiskPersonNumber = riskOperations.stream().filter(item->item.getTaskNumber() != null).mapToInt(HighRiskOperation::getTaskNumber).sum();
        //高风险作业次数
        int highRiskNumber = riskOperations.size();

        //高风险作业类型统计List -- highRiskWorkVOIPage
        IPage<HighRiskWorkVO> highRiskWorkVOIPage = highRiskOperationMapper.getHighRiskWork(page, param);

        //高风险作业类型统计 --- 类型个数 highRiskTypeNumber
        long highRiskTypeNumber = highRiskWorkVOIPage.getTotal();

        //高风险作业区域统计 -- highRiskAreaVOIPage
        //IPage<HighRiskAreaVO> highRiskAreaVOIPage = highRiskOperationMapper.getHighRiskArea(page, param);

        //承包商统计 -- contractorStatisticVOIPage
        //IPage<ContractorStatisticVO> contractorStatisticVOIPage = contractorManageMapper.getContractorStatistic(page, param);

        HighRiskModelVO highRiskModelVO = new HighRiskModelVO()
                .setHighRiskNumber(highRiskNumber)
                .setHighRiskTypeNumber(highRiskTypeNumber)
                .setHighRiskWorkVOIPage(highRiskWorkVOIPage);


        return MessageInfo.ok(highRiskModelVO);
    }

    @Override
    public MessageInfo<IPage<HighRiskAreaVO>> queryHighRiskArea(Page page, BaseParam param) {
        IPage<HighRiskAreaVO> highRiskAreaVOIPage = highRiskOperationMapper.getHighRiskArea(page, param);
        return MessageInfo.ok(highRiskAreaVOIPage);
    }

    @Override
    public MessageInfo<ContractorListVO> queryContractorList(Page page, BaseParam param) {
//        Integer contractorNumber = contractorManageMapper.selectCount(Wrappers.lambdaQuery(ContractorManage.class)
//                .isNotNull(ContractorManage::getContractorUnitName)
//                .eq(StringUtil.isNotBlank(param.getAppId()), ContractorManage::getAppId, param.getAppId()));

        IPage<ContractorStatisticVO> contractorStatisticVOIPage = contractorManageMapper.getContractorStatistic(page, param);
        long contractorNumber = contractorStatisticVOIPage.getTotal();
        return MessageInfo.ok(new ContractorListVO().setContractorStatisticVOIPage(contractorStatisticVOIPage).setContractorNumber((int) contractorNumber));
    }

    @Override
    public MessageInfo<HighRiskModelVO> queryScreenHighRiskModel(Page page, BaseParam param) {

        //高风险作业次数---人数
        List<HighRiskOperation> riskOperations = highRiskOperationMapper.getHighRiskOperationListToday(param);


        //高风险作业人数
        int highRiskPersonNumber = riskOperations.stream().mapToInt(HighRiskOperation::getTaskNumber).sum();
        //高风险作业次数
        int highRiskNumber = riskOperations.size();

        //高风险作业类型统计List -- highRiskWorkVOIPage
        IPage<HighRiskWorkVO> highRiskWorkVOIPage = highRiskOperationMapper.getHighRiskWork(page, param);

        //高风险作业类型统计 --- 类型个数 highRiskTypeNumber
        long highRiskTypeNumber = highRiskWorkVOIPage.getTotal();

        HighRiskModelVO highRiskModelVO = new HighRiskModelVO()
                .setHighRiskNumber(highRiskNumber)
                .setHighRiskTypeNumber(highRiskTypeNumber)
                .setHighRiskWorkVOIPage(highRiskWorkVOIPage);


        return MessageInfo.ok(highRiskModelVO);
    }

    @Override
    public MessageInfo<IPage<SeaPlatformVideoMonitorVO>> querySeaPlatformVideoMonitor(Page page, BaseParam param) {

        IPage<SeaPlatformVideoMonitorVO> seaPlatformVideoMonitor = criticalAreaMapper.getSeaPlatformVideoMonitor(page, param);

        return MessageInfo.ok(seaPlatformVideoMonitor);
    }

    @Override
    public MessageInfo<RiskControlSituationVO> queryRiskControlSituation(Page page, BaseParam param) {

        EmergencyPlanParam emergencyPlanParam = new EmergencyPlanParam();
        BeanUtil.copyProperties(param, emergencyPlanParam);
        //应急预案--emergencyPlan
        int emergencyPlan = (int) emergencyRecordMapper.getEmergencyPlanList(page, emergencyPlanParam).getTotal();


        //变更信息--changeSituation
        ChangeSituationParam changeSituationParam = new ChangeSituationParam();
        BeanUtil.copyProperties(param,changeSituationParam);
        int changeSituation = (int) changeInfoMapper.getChangeSituationList(page, changeSituationParam).getTotal();

        //备案情况--filingSituation
        FilingSituationParam filingSituationParam = new FilingSituationParam();
        BeanUtil.copyProperties(param,filingSituationParam);
        int filingSituation = (int) recordManageMapper.getRecordManageList(page, filingSituationParam).getTotal();

        //弃井信息--reportInformation
        ReportInformationParam reportInformationParam = new ReportInformationParam();
        BeanUtil.copyProperties(param,reportInformationParam);
        int reportInformation = (int) giveupMineReportMapper.getGiveupMineReportList(page, reportInformationParam).getTotal();

        return MessageInfo.ok(
                new RiskControlSituationVO()
                        .setChangeSituation(changeSituation)
                        .setFilingSituation(filingSituation)
                        .setEmergencyPlan(emergencyPlan)
                        .setReportInformation(reportInformation)
        );
    }

    @Override
    public MessageInfo<IPage<ScreenDisplayMattersVO>> queryMattersManagers(Page page, BaseParam param) {
        IPage<ScreenDisplayMattersVO> mattersManagers = mattersManagerMapper.getMattersManagers(page, param);
        return MessageInfo.ok(mattersManagers);
    }

    @Override
    public MessageInfo<IPage<EmergencyPlanVO>> queryEmergencyPlanList(Page page, EmergencyPlanParam param) {
        IPage<EmergencyPlanVO> emergencyPlanList = emergencyRecordMapper.getEmergencyPlanList(page, param);
        return MessageInfo.ok(emergencyPlanList);
    }

    @Override
    public MessageInfo<IPage<ChangeInfoVO>> queryChangeSituationList(Page page, ChangeSituationParam param) {
        return MessageInfo.ok(changeInfoMapper.getChangeSituationList(page, param));
    }

    @Override
    public MessageInfo<IPage<RecordManageVO>> queryRecordManageList(Page page, FilingSituationParam param) {
        return MessageInfo.ok(recordManageMapper.getRecordManageList(page, param));
    }

    @Override
    public MessageInfo<IPage<GiveupMineReportVO>> queryGiveupMineReportList(Page page, ReportInformationParam param) {
        return MessageInfo.ok(giveupMineReportMapper.getGiveupMineReportList(page, param));
    }

    @Override
    public MessageInfo<HighRiskCountStatisticsVO> queryHighRiskCountStatistics(HighRiskCountParam param) {
        String cycleType = param.getCycleType();
        if (StringUtil.isBlank(cycleType)){
            return MessageInfo.failed("周期类型不能为空");
        }

        LocalDateTime startPeriod, endPeriod;

        startPeriod = DateUtils.getStartPeriod(cycleType);
        endPeriod = DateUtils.getEndPeriod(cycleType);

        param.setStartDate(startPeriod);
        param.setEndDate(endPeriod);

        List<HighRiskCountByTypeVO> highRiskCountByTypeVOS = highRiskOperationMapper.getHighRiskCountByType(param);


        HighRiskCountStatisticsVO highRiskCountStatisticsVO = new HighRiskCountStatisticsVO();
        long sum = highRiskCountByTypeVOS.stream().mapToLong(HighRiskCountByTypeVO::getWorkNumber).sum();
        highRiskCountStatisticsVO.setHighRiskCountByTypeVOS(highRiskCountByTypeVOS)
                .setWorkTotal(sum);

        return MessageInfo.ok(highRiskCountStatisticsVO);
    }

    @Override
    public MessageInfo<HighRiskCountStatisticsByPlatformVO> highRiskWorkTypeByPlatformBar(HighRiskCountParam param) {

        String cycleType = param.getCycleType();
        if (StringUtil.isBlank(cycleType)){
            return MessageInfo.failed("周期类型不能为空");
        }

        LocalDateTime startPeriod, endPeriod;

        startPeriod = DateUtils.getStartPeriod(cycleType);
        endPeriod = DateUtils.getEndPeriod(cycleType);

        param.setStartDate(startPeriod);
        param.setEndDate(endPeriod);

        if (Objects.isNull(param.getLimit())){
            param.setLimit(3);
        }

        HighRiskCountStatisticsByPlatformVO highRiskCountStatisticsByPlatformVO = new HighRiskCountStatisticsByPlatformVO();
        List<HighRiskCountByPlatformVO> highRiskCountByPlatformVOS = highRiskOperationMapper.highRiskWorkTypeByPlatformBar(param);
        highRiskCountStatisticsByPlatformVO.setHighRiskCountByPlatformVOS(highRiskCountByPlatformVOS)
                .setWorkTotal(highRiskCountByPlatformVOS.stream().mapToLong(HighRiskCountByPlatformVO::getWorkNumber).sum());
        return MessageInfo.ok(highRiskCountStatisticsByPlatformVO);
    }

    @Override
    public MessageInfo<List<HighRiskOperationsTrendVO>> queryHighRiskOperationsTrend(HighRiskOperationsTrendParam param) {

        List<HighRiskOperationsTrendVO> highRiskOperationsTrendVOS = new ArrayList<>();

        if (Objects.isNull(param.getTrendDays())){
            param.setTrendDays(7);
        }

        //获取近七天的日期
        LocalDate now = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        List<String> dates = IntStream.rangeClosed(1 - param.getTrendDays(), 0)
                .mapToObj(now::plusDays)
                .map(formatter::format)
                .collect(Collectors.toList());



        //查询近七天的工作数量
        for (String date : dates) {
            HighRiskOperationsTrendVO highRiskOperationsTrendVO = new HighRiskOperationsTrendVO();
            highRiskOperationsTrendVO.setDate(date)
                    .setCount((long) highRiskOperationService.count(
                            Wrappers.lambdaQuery(HighRiskOperation.class)
                                    .eq(StringUtil.isNotBlank(param.getAppId()), HighRiskOperation::getAppId, param.getAppId())
                                    .eq(StringUtil.isNotBlank(param.getPlatformId()), HighRiskOperation::getPlatformCode, param.getPlatformId())
                                    .le(HighRiskOperation::getTaskBeginTime, date+" 23:59:59")
                                    .ge(HighRiskOperation::getTaskEndTime, date+" 00:00:00")
                    ));
            highRiskOperationsTrendVOS.add(highRiskOperationsTrendVO);
        }

        return MessageInfo.ok(highRiskOperationsTrendVOS);
    }

    @Override
    public MessageInfo<IPage<HighRiskOperationsDetailVO>> queryHighRiskOperationsDetail(Page page, WorkDetailParam param) {

        return MessageInfo.ok(highRiskOperationMapper.getHighRiskOperationsDetail(page, param));
    }


}
