package com.sckw.slope.detection.service.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sckw.core.model.constant.NumberConstant;
import com.sckw.core.model.enums.DictItemEnum;
import com.sckw.core.model.enums.ReportTypeEnum;
import com.sckw.core.utils.IdWorker;
import com.sckw.excel.annotation.ExcelContext;
import com.sckw.excel.utils.ExcelUtil;
import com.sckw.slope.detection.dao.mysql.KwsDeviceIntegrationMapper;
import com.sckw.slope.detection.dao.mysql.KwsProjectMapper;
import com.sckw.slope.detection.dao.mysql.KwsReportDataMapper;
import com.sckw.slope.detection.dao.mysql.KwsReportTemplateMapper;
import com.sckw.slope.detection.dao.tdengine.SlopeDataMapper;
import com.sckw.slope.detection.model.dos.mysql.KwsDeviceReference;
import com.sckw.slope.detection.model.dos.mysql.KwsProject;
import com.sckw.slope.detection.model.dos.mysql.KwsReportData;
import com.sckw.slope.detection.model.dos.mysql.KwsReportTemplate;
import com.sckw.slope.detection.model.dos.tdengine.SlopeData;
import com.sckw.slope.detection.model.vo.DeviceVo;
import com.sckw.slope.detection.model.vo.excel.TaskReportExportVO;
import com.sckw.slope.detection.service.CommonService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lfdc
 * @description 报表任务
 * @date 2023-11-10 11:11:25
 */

@Slf4j
@Component
@EnableScheduling
public class ReportTemplateTaskService {

    @Value("${scheduled.template.enable}")
    private String templateEnable;

    @Resource
    KwsReportTemplateMapper reportTemplateMapper;

    @Autowired
    KwsReportDataMapper kwsReportDataMapper;

    @Autowired
    SlopeDataMapper slopeDataMapper;

    @Autowired
    KwsDeviceIntegrationMapper deviceIntegrationMapper;

    @Autowired
    KwsProjectMapper kwsProjectMapper;

    @Autowired
    CommonService commonService;

    public void report(KwsReportTemplate kwsReportTemplate, String date1, String date2) throws NoSuchAlgorithmException, IOException {

        String[] title = "推送时间".split(",");
        String[] part = kwsReportTemplate.getPartNames().split(",");
        String[] intergrationName = kwsReportTemplate.getIntergrationNames().split(",");

        //List<Map<String,String>> intergration = DictItemEnum.getAll();//获取系统中的全部基础要素
        List<String> list = new ArrayList<>();
        list.addAll(Arrays.asList(title));
        list.addAll(Arrays.asList(part));
        //list.addAll(Arrays.asList(intergration));
        String projectId = kwsReportTemplate.getProjectId();
        //首先查询模板中的要素关联的设备-项目中的设备
        List<DeviceVo> devices = reportTemplateMapper.selectDeviceByProjectId(projectId, list);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //List<Object> deviceName = new ArrayList<>();
        List<Map<String, Object>> deviceData = new ArrayList<>();
        Map<String, List<Object>> map1 = new HashMap<>();
        for (DeviceVo vo : devices) {
            List<SlopeData> selectedData = slopeDataMapper.selectLineListByList(vo.getSnCode(), list, "2022-1-1 00:00:00", date2);
            /*List<Object> listm = new ArrayList<Object>();
            if(Objects.nonNull(kwsReportTemplate.getIntergrationNames())){//集成要素不为空时
                List<DeviceIntegrationVo> intergData = deviceIntegrationMapper.selectListParamsAndInterNameByDeviceId(vo.getId());
                for (DeviceIntegrationVo listvo : intergData){
                    listm = commonService.returnIntegrationDataArray(vo.getSnCode(),"2022-1-1 00:00:00",date2,listvo,"time","offset");
                }
            }*/

            if (Objects.nonNull(selectedData)) {
                Map<String, List<SlopeData>> map = selectedData.stream().collect(Collectors.groupingBy(SlopeData::getMsgId));

                List<Object> list1 = new ArrayList<>();
                for (List<SlopeData> value : map.values()) {
                    List<Object> listObject = new ArrayList<>();
                    listObject.add(sdf.format(value.get(0).getRawId()));

                    for (int i = 1; i < list.size(); i++) {
                        for (SlopeData slopeData : value) {
                            if (slopeData.getLine().equals(list.get(i))) {
                                listObject.add(slopeData.getVal());
                            }
                        }
                    }
                    /*if(listm.size()>0){
                        for(Object obj:listm){
                            Map<String,String> map2 = new HashMap<>();
                            map2 = (Map<String ,String>) obj;
                            if(map2.get("time").equals(sdf.format(value.get(0).getRawId()))){
                                listObject.add(map2.get("offset"));
                            }
                        }
                    }*/
                    list1.add(listObject);
                }
                map1.put(vo.getName(), list1);
            }

        }
        ExcelContext excelContext = TaskReportExportVO.class.getAnnotation(ExcelContext.class);
        if (devices.size() > 0) {
            String md5 = returnMd5();
            String filePath = ExcelUtil.taskExportByExcelUploadingToOss(map1, devices, md5 + ".xlsx", TaskReportExportVO.class, list);
            //生成的日报新增到kws_report_data
            URL url = new URL(filePath);
            URLConnection connection = url.openConnection();
            int fileSize = connection.getContentLength();
            KwsReportData report = new KwsReportData();
            LocalDateTime now = LocalDateTime.now();
            long id = new IdWorker(NumberConstant.ONE).nextId();
            report.setMountainId(kwsReportTemplate.getCompanyId());
            report.setCompanyId(kwsReportTemplate.getCompanyId());
            report.setTemplateId(kwsReportTemplate.getId());
            KwsProject project = kwsProjectMapper.selectOne(new LambdaQueryWrapper<KwsProject>()
                    .eq(KwsProject::getId, kwsReportTemplate.getProjectId())
            );
            report.setProjectId(Long.parseLong(kwsReportTemplate.getProjectId()));
            report.setProjectName(project.getName());
            report.setFileSize(new BigDecimal(fileSize));
            report.setFileUrl(filePath);
            report.setId(id);
            report.setCreateTime(now);
            report.setDelFlag(NumberConstant.ZERO);
            kwsReportDataMapper.insert(report);
        }
    }

    /**
     * 报表生成定时任务-天
     */
    @Scheduled(cron = "0 0 * * * *")
    public void templateTaskDay() throws IOException, NoSuchAlgorithmException {
        List<KwsReportTemplate> kwsReportTemplates = reportTemplateMapper.selectList(new LambdaQueryWrapper<KwsReportTemplate>()
                .eq(KwsReportTemplate::getStatus, 0)
                .eq(KwsReportTemplate::getDelFlag, 0));
        if (!CollectionUtils.isEmpty(kwsReportTemplates)) {
            for (KwsReportTemplate kwsReportTemplate : kwsReportTemplates) {
                Integer type = kwsReportTemplate.getType();
                if (ReportTypeEnum.DAY.getCode() == type) {
                    LocalDateTime localDateTime = LocalDateTime.now().minusDays(1);
                    LocalDateTime dateEnd = com.sckw.excel.utils.DateUtil.localDateToLocalDateTimeEnd(localDateTime.toLocalDate());
                    LocalDateTime dateStart = com.sckw.excel.utils.DateUtil.localDateToLocalDateTimeStart(localDateTime.toLocalDate());
                    String date1 = dateStart.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                    String date2 = dateEnd.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                    report(kwsReportTemplate, date1, date2);
                }
            }
        }
    }

    public String returnMd5() throws NoSuchAlgorithmException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String currentTime = sdf.format(new Date());

        // 将当前时间转换为字节数组
        byte[] bytes = currentTime.getBytes();

        // 创建 MD5 对象
        MessageDigest md = MessageDigest.getInstance("MD5");

        // 计算 MD5 值
        byte[] md5Bytes = md.digest(bytes);

        // 将 MD5 值转换为十六进制字符串
        StringBuilder sb = new StringBuilder();
        for (byte b : md5Bytes) {
            String hex = Integer.toHexString(b & 0xFF);
            if (hex.length() == 1) {
                sb.append('0');
            }
            sb.append(hex);
        }
        return sb.toString();
    }

    /**
     * 报表生成定时任务-周
     */
    //    @Scheduled(cron = "0 0 0 ? * *")
    public void templateTaskWeek() throws NoSuchAlgorithmException, IOException {
        List<KwsReportTemplate> kwsReportTemplates = reportTemplateMapper.selectList(new LambdaQueryWrapper<KwsReportTemplate>()
                .eq(KwsReportTemplate::getStatus, 0)
                .eq(KwsReportTemplate::getDelFlag, 0));
        if (!CollectionUtils.isEmpty(kwsReportTemplates)) {
            for (KwsReportTemplate kwsReportTemplate : kwsReportTemplates) {
                Integer type = kwsReportTemplate.getType();
                if (ReportTypeEnum.WEEK.getCode() == type) {
                    LocalDateTime localDateTime = LocalDateTime.now().minusDays(7);
                    LocalDateTime dateEnd = com.sckw.excel.utils.DateUtil.localDateToLocalDateTimeEnd(localDateTime.toLocalDate());
                    LocalDateTime dateStart = com.sckw.excel.utils.DateUtil.localDateToLocalDateTimeStart(localDateTime.toLocalDate());
                    String date1 = dateStart.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                    String date2 = dateEnd.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                    report(kwsReportTemplate, date1, date2);
                }
            }
        }
    }

    /**
     * 报表生成定时任务-月
     */
    //    @Scheduled(cron = "0 0 0 ? * *")
    public void templateTaskMonth() throws NoSuchAlgorithmException, IOException {
        List<KwsReportTemplate> kwsReportTemplates = reportTemplateMapper.selectList(new LambdaQueryWrapper<KwsReportTemplate>()
                .eq(KwsReportTemplate::getStatus, 0)
                .eq(KwsReportTemplate::getDelFlag, 0));
        if (!CollectionUtils.isEmpty(kwsReportTemplates)) {
            for (KwsReportTemplate kwsReportTemplate : kwsReportTemplates) {
                Integer type = kwsReportTemplate.getType();
                if (ReportTypeEnum.MONTH.getCode() == type) {
                    LocalDateTime localDateTime = LocalDateTime.now().minusDays(30);
                    LocalDateTime dateEnd = com.sckw.excel.utils.DateUtil.localDateToLocalDateTimeEnd(localDateTime.toLocalDate());
                    LocalDateTime dateStart = com.sckw.excel.utils.DateUtil.localDateToLocalDateTimeStart(localDateTime.toLocalDate());
                    String date1 = dateStart.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                    String date2 = dateEnd.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                    report(kwsReportTemplate, date1, date2);
                }
            }
        }
    }
}