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

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yeejoin.amos.boot.module.elevator.api.dto.AlertDispatchStatisticsDto;
import com.yeejoin.amos.boot.module.elevator.api.entity.AlertDispatchStatistics;
import com.yeejoin.amos.boot.module.elevator.api.mapper.AlertDispatchStatisticsMapper;
import com.yeejoin.amos.boot.module.elevator.api.service.IAlertDispatchStatisticsService;
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.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 服务实现类
 *
 * @author system_generator
 * @date 2023-11-10
 */
@Service
public class AlertDispatchStatisticsServiceImpl extends BaseService<AlertDispatchStatisticsDto, AlertDispatchStatistics, AlertDispatchStatisticsMapper> implements IAlertDispatchStatisticsService {

    @Autowired
    private AlertStatisticsServiceImpl alertStatisticsService;

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


    @Override
    public void statisticalGeneration(String type) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat formatTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        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();
        List<Map<String, String>> message = this.baseMapper.getMessage(format.format(firstDayOfMonth) + " 00:00:00", format.format(lastDayOfMonth) + " 23:59:59");
        ArrayList<AlertDispatchStatistics> list = new ArrayList<>();
        if (!ObjectUtils.isEmpty(supervisionList)) {
            supervisionList.forEach(item -> {
                List<Map<String, String>> collect = message.stream().filter(detail -> detail.get("orgCode").startsWith(String.valueOf(item.get("orgCode")))).collect(Collectors.toList());
                if (!ObjectUtils.isEmpty(collect)) {
                    collect.forEach(data -> {
                        AlertDispatchStatistics alertDispatchStatistics = new AlertDispatchStatistics();
                        BeanUtil.copyProperties(data, alertDispatchStatistics);
                        alertDispatchStatistics.setSupervisoryUnitName(String.valueOf(item.get("companyName")));
                        alertDispatchStatistics.setSupervisoryUnitOrgCode(String.valueOf(item.get("orgCode")));
                        alertDispatchStatistics.setSupervisoryUnitId(String.valueOf(item.get("sequenceNbr")));
                        alertDispatchStatistics.setStartDate(format.format(firstDayOfMonth));
                        alertDispatchStatistics.setEndDate(format.format(lastDayOfMonth));
                        alertDispatchStatistics.setStatisticsDate(format.format(lastDayOfMonth).substring(0, 7));
                        if (data.containsKey("ddTime") && data.containsKey("pqTime")){
                            try {
                                Date ddTime = formatTime.parse(String.valueOf(data.get("ddTime")));
                                Date pqTime = formatTime.parse(String.valueOf(data.get("pqTime")));
                                BigDecimal bigDecimal = new BigDecimal(String.valueOf(ddTime.getTime() - pqTime.getTime()));

                                BigDecimal divide = bigDecimal.divide(new BigDecimal(60000), 2, BigDecimal.ROUND_HALF_UP);
                                alertDispatchStatistics.setArriveTime(divide+"分钟");
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                        }
                        list.add(alertDispatchStatistics);
                    });
                }
            });
            if (!ObjectUtils.isEmpty(list)) {
                this.saveBatch(list);
            }
        }
    }

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