package com.yeejoin.amos.boot.module.elevator.biz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.module.elevator.api.dto.AlertMaintenanceUnitStatisticsDto;
import com.yeejoin.amos.boot.module.elevator.api.entity.AlertMaintenanceUnitStatistics;
import com.yeejoin.amos.boot.module.elevator.api.entity.AlertRescueStatistics;
import com.yeejoin.amos.boot.module.elevator.api.mapper.AlertMaintenanceUnitStatisticsMapper;
import com.yeejoin.amos.boot.module.elevator.api.service.IAlertMaintenanceUnitStatisticsService;
import net.javacrumbs.shedlock.spring.annotation.SchedulerLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.typroject.tyboot.core.rdbms.service.BaseService;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 服务实现类
 *
 * @author system_generator
 * @date 2023-11-09
 */
@Service
public class AlertMaintenanceUnitStatisticsServiceImpl extends BaseService<AlertMaintenanceUnitStatisticsDto, AlertMaintenanceUnitStatistics, AlertMaintenanceUnitStatisticsMapper> implements IAlertMaintenanceUnitStatisticsService {

    @Autowired
    private AlertStatisticsServiceImpl alertStatisticsService;

    @Scheduled(cron = "0 0 0 1 * ?")
    @SchedulerLock(name = "AlertMaintenanceUnitStatisticsServiceImpl", lockAtMostFor = "PT10M", lockAtLeastFor = "PT10M")
    public void statisticalGenerationTask(){
        statisticalGeneration(null);
    }


    @Override
    public void statisticalGeneration(String type) {
        DecimalFormat decimalFormat = new DecimalFormat("0.00");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        ArrayList<AlertMaintenanceUnitStatistics> list = new ArrayList<>();
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        if (ObjectUtils.isEmpty(type)){
            cal.add(Calendar.MONTH, -1);
        }
        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMinimum(Calendar.DAY_OF_MONTH));
        Date firstDayOfMonth = cal.getTime();
        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
        Date lastDayOfMonth = cal.getTime();
        List<LinkedHashMap> supervisionList = alertStatisticsService.getSupervisionList();
        if (!ObjectUtils.isEmpty(supervisionList)) {
            List<Map<String, String>> message = this.baseMapper.getMessage(format.format(firstDayOfMonth) + " 00:00:00", format.format(lastDayOfMonth) + " 23:59:59");
            supervisionList.forEach(item -> {
                List<Map<String, String>> collect = message.stream().filter(maintenance -> maintenance.get("orgBranchCode").startsWith(String.valueOf(item.get("orgCode")))).collect(Collectors.toList());
                if (!ObjectUtils.isEmpty(collect)) {
                    collect.forEach(data -> {
                        AlertMaintenanceUnitStatistics alertMaintenanceStatistics = this.baseMapper.countMessage(data.get("maintenanceCode"), data.get("equipmentId"));
                        alertMaintenanceStatistics.setSupervisoryUnitName(String.valueOf(item.get("companyName")));
                        alertMaintenanceStatistics.setSupervisoryUnitOrgCode(String.valueOf(item.get("orgCode")));
                        alertMaintenanceStatistics.setSupervisoryUnitId(String.valueOf(item.get("sequenceNbr")));
                        alertMaintenanceStatistics.setAlertNum(alertMaintenanceStatistics.getTrappedNum() + alertMaintenanceStatistics.getFaultNum());
                        if (alertMaintenanceStatistics.getAlertNum() != 0 && alertMaintenanceStatistics.getEquipNum() != 0) {
                            BigDecimal bigDecimal = new BigDecimal(alertMaintenanceStatistics.getAlertNum());
                            BigDecimal bigDecimal1 = new BigDecimal(alertMaintenanceStatistics.getEquipNum());
                            BigDecimal divide = bigDecimal.divide(bigDecimal1, 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100));
                            alertMaintenanceStatistics.setRate(decimalFormat.format(divide) + "%");
                        } else {
                            alertMaintenanceStatistics.setRate("0%");
                        }
                        alertMaintenanceStatistics.setStartDate(format.format(firstDayOfMonth));
                        alertMaintenanceStatistics.setEndDate(format.format(lastDayOfMonth));
                        alertMaintenanceStatistics.setStatisticsDate(format.format(lastDayOfMonth).substring(0, 7));
                        list.add(alertMaintenanceStatistics);
                    });
                }
            });
            if (!ObjectUtils.isEmpty(list)) {
                this.saveBatch(list);
            }
        }

    }

    @Override
    public List<AlertMaintenanceUnitStatistics> getList(String date) {
        LambdaQueryWrapper<AlertMaintenanceUnitStatistics> lambda = new QueryWrapper<AlertMaintenanceUnitStatistics>().lambda();
        lambda.eq(AlertMaintenanceUnitStatistics::getStatisticsDate, date);
        return this.baseMapper.selectList(lambda);
    }
}