package com.ruoyi.system.service;


import cn.hutool.core.io.FileUtil;
import cn.hutool.extra.mail.MailUtil;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.KeyPeopleInfo;
import com.ruoyi.system.domain.OdsQssHsjcxx;
import com.ruoyi.system.domain.UserInfo;
import com.ruoyi.system.domain.UserNucleicTime;
import com.ruoyi.system.mapper.KeyPeopleInfoMapper;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.utils.ExcelUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Component
public class Task {

    @Resource
    private OdsQssHsjcxxService qdsQssHsjcxxService;
    @Resource
    private SysDeptMapper deptMapper;
    @Resource
    private KeyPeopleInfoMapper keyPeopleInfoMapper;

    /***
     * 邮件发送（定时比对数据后发送邮件）
     */
    @Scheduled(cron = "0 0 * * * ? ")
    public void thirdNucleicAcid() {
        try {
            SysDept dept = new SysDept();
            dept.setDeptName("定时任务");
            List<SysDept> depts = deptMapper.selectDeptList(dept);
            if(depts==null && depts.size()<=0){
                System.out.println("定时任务: 部门名字错误");
                return;
            }
            //获取人员信息
            KeyPeopleInfo keyPeopleInfo = new KeyPeopleInfo();
            keyPeopleInfo.setDeptId(depts.get(0).getDeptId().toString());
            List<KeyPeopleInfo> keyPeopleInfoList = keyPeopleInfoMapper.selectKeyPeopleInfoList(keyPeopleInfo);

            //获取当前时间
            Date data = DateUtils.getNowDate();
            String endTime = DateUtils.formatString(data);
            //往前推1个小时
            String startTime = DateUtils.plusSeconds(endTime, -60);

            //SysUser user = SecurityUtils.getLoginUser().getUser();
            //UserInfo userInfo = new UserInfo();
            // startTime = "2022-09-20 00:00:00";
            //String endTime = "2022-09-27 00:00:00";
            String detectionNumber = "1";

            //计算开始时间结束时间相隔天数
            String detectionScope = "1H";

            List<String> idCardList = keyPeopleInfoList.stream().map(KeyPeopleInfo::getIdCard).collect(Collectors.toList());
            //从第三方数据库查询人员核酸计录
            List<OdsQssHsjcxx> OdsQssHsjcxxList = qdsQssHsjcxxService.thirdNucleicAcid(startTime, endTime, idCardList);
            if(OdsQssHsjcxxList == null || OdsQssHsjcxxList.size() <= 0){
                return;
            }
            /*Map<String, List<OdsQssHsjcxx>> OdsQssHsjcxxMapSorted = new HashMap<>();
            if (OdsQssHsjcxxList != null && OdsQssHsjcxxList.size() > 0) {
                OdsQssHsjcxxMapSorted = OdsQssHsjcxxList.stream().sorted(Comparator.comparing(OdsQssHsjcxx::getCjsj).reversed()).collect(Collectors.groupingBy(OdsQssHsjcxx::getSfzhm));
            }


            int index = 0;
            int count = 0;
            List<UserInfo> userList = new ArrayList<>();

            for (KeyPeopleInfo peopleInfo : keyPeopleInfoList) {
                UserInfo userInfo = new UserInfo();
                userInfo.setDeptId(depts.get(0).getDeptId().toString());
                userInfo.setPhoneNum(peopleInfo.getPhoneNum());
                userInfo.setName(peopleInfo.getName());
                userInfo.setIdCard(peopleInfo.getIdCard());

                //采集地点
                StringBuilder collectPlace = new StringBuilder();
                //核酸采集时间
                StringBuilder nucleicCollectTime = new StringBuilder();
                //核酸结果时间
                StringBuilder nucleicResultsTime = new StringBuilder();
                //核酸结果
                StringBuilder nucleicResults = new StringBuilder();


                userInfo.setJobStyle("重点人群");
                userInfo.setFocusCrowdStyle("重点人群");
                userInfo.setDetectionFrequency(detectionNumber + "/" + detectionScope);
                userInfo.setDetectionNumber(detectionNumber);
                userInfo.setDetectionScope(detectionScope);
                userInfo.setStartTime(startTime);
                userInfo.setEndTime(endTime);
                //判断结果是否合格,默认合格
                Boolean bl = true;

                index = 0;
                count = 0;
                if (OdsQssHsjcxxMapSorted.size() > 0) {
                    //身份证号码
                    String idCard = userInfo.getIdCard();
                    List<OdsQssHsjcxx> odsQssHsjcxxes = OdsQssHsjcxxMapSorted.get(idCard);
                    if (odsQssHsjcxxes != null && odsQssHsjcxxes.size() > 0) {
                        //String time = null;

                        for (OdsQssHsjcxx odsQssHsjcxx : odsQssHsjcxxes) {

                            if (StringUtils.isNotEmpty(collectPlace.toString())) {
                                collectPlace.append("<br>");
                            }
                            collectPlace.append(odsQssHsjcxx.getJcdd());

                            if (StringUtils.isNotEmpty(nucleicCollectTime.toString())) {
                                nucleicCollectTime.append("<br>");
                            }
                            nucleicCollectTime.append(odsQssHsjcxx.getCjsj());

                            if (StringUtils.isNotEmpty(nucleicResultsTime.toString())) {
                                nucleicResultsTime.append("<br>");
                            }
                            nucleicResultsTime.append(odsQssHsjcxx.getJgcjss());

                            if (StringUtils.isNotEmpty(nucleicResults.toString())) {
                                nucleicResults.append("<br>");
                            }
                            if(StringUtils.isEmpty(odsQssHsjcxx.getJcjg())){
                                nucleicResults.append(odsQssHsjcxx.getJcjg());
                            }else if("0".equals(odsQssHsjcxx.getJcjg()) || "negative".equals(odsQssHsjcxx.getJcjg())){
                                nucleicResults.append("阴性");
                            }else if("1".equals(odsQssHsjcxx.getJcjg()) || "positive".equals(odsQssHsjcxx.getJcjg())){
                                nucleicResults.append("阳性");
                            }else{
                                nucleicResults.append(odsQssHsjcxx.getJcjg());
                            }

                        }
                        index = odsQssHsjcxxes.size();
                    }


                }
                if (index < Integer.parseInt(detectionNumber)) {
                    bl = false;
                }
                userInfo.setCollectPlace(collectPlace.toString());
                userInfo.setNucleicCollectTime(nucleicCollectTime.toString());
                userInfo.setNucleicResultsTime(nucleicResultsTime.toString());
                userInfo.setNucleicResults(nucleicResults.toString());
                userInfo.setDetectionProgress(index + "/" + detectionNumber);

                if (bl) {
                    userInfo.setDetectionResult("正常");
                } else {
                    userInfo.setDetectionResult("异常");
                }

                userList.add(userInfo);
            }*/

            /*if (OdsQssHsjcxxList != null && OdsQssHsjcxxList.size() > 0) {
                for (OdsQssHsjcxx odsQssHsjcxx : OdsQssHsjcxxList) {
                    for (UserInfo userInfo : userList) {
                        if (userInfo.getIdCard().equals(odsQssHsjcxx.getSfzhm())) {
                            UserNucleicTime userNucleicTime = new UserNucleicTime();
                            userNucleicTime.setInfoId(userInfo.getId());
                            userNucleicTime.setIdCard(odsQssHsjcxx.getSfzhm());
                            userNucleicTime.setCollectPlace(odsQssHsjcxx.getJcdd());
                            userNucleicTime.setNucleicCollectTime(odsQssHsjcxx.getCjsj());
                            userNucleicTime.setNucleicResultsTime(odsQssHsjcxx.getJgcjss());
                            userNucleicTime.setJobStyle(jobStyle);
                            userNucleicTime.setFocusCrowdStyle(focusCrowdStyle);
                            userNucleicTime.setName(userInfo.getName());
                            userNucleicTime.setPhoneNum(userInfo.getPhoneNum());
                            userNucleicTime.setDeptId(user.getDeptId().toString());
                            UserNucleicTimeList.add(userNucleicTime);
                            userNucleicTime.setDateSource("批量导入");
                        }
                    }
                }
            }*/

            List<Map<String, Object>> mapList = new ArrayList<>();

            for (OdsQssHsjcxx odsQssHsjcxx : OdsQssHsjcxxList) {
                Map<String, Object> map = new HashMap<>();
                map.put("姓名", odsQssHsjcxx.getXm());
                map.put("身份证号码", odsQssHsjcxx.getSfzhm());
                map.put("联系号码", odsQssHsjcxx.getSjhm());
                map.put("核酸采集时间", odsQssHsjcxx.getCjsj());
                map.put("核酸结果时间", odsQssHsjcxx.getJgcjss());
                map.put("采集地点", odsQssHsjcxx.getJcdd());
                if(StringUtils.isEmpty(odsQssHsjcxx.getJcjg())){
                    map.put("采集结果", odsQssHsjcxx.getJcjg());
                }else if("0".equals(odsQssHsjcxx.getJcjg()) || "negative".equals(odsQssHsjcxx.getJcjg())){
                    map.put("采集结果", "阴性");
                }else if("1".equals(odsQssHsjcxx.getJcjg()) || "positive".equals(odsQssHsjcxx.getJcjg())){
                    map.put("采集结果", "阳性");
                }
                map.put("采集结果", "");
                map.put("比对开始时间", startTime);
                map.put("比对结束时间", endTime);
                mapList.add(map);
            }


            String path = ExcelUtils.getInstance().createExcel(mapList, "核酸对比数据", "对比数据");
            MailUtil.send("qsxzhb@126.com", "重点人群定时对比数据", "时间："+startTime+"--"+endTime, true,
                    FileUtil.file(path));
            MailUtil.send("731020@qq.com", "重点人群定时对比数据", "时间："+startTime+"--"+endTime, true,
                    FileUtil.file(path));
            //删除系统文件
            File file = new File(path);
            file.delete();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
