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

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.yeejoin.amos.boot.biz.common.utils.DateUtils;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.jxiop.api.Enum.QrcodeColorEnum;
import com.yeejoin.amos.boot.module.jxiop.api.dto.BizMessage;
import com.yeejoin.amos.boot.module.jxiop.api.dto.RiskBizInfoVo;
import com.yeejoin.amos.boot.module.jxiop.api.dto.StationBasicDto;
import com.yeejoin.amos.boot.module.jxiop.api.entity.PersonAccount;
import com.yeejoin.amos.boot.module.jxiop.api.entity.PersonBasic;
import com.yeejoin.amos.boot.module.jxiop.api.entity.PersonCertificate;
import com.yeejoin.amos.boot.module.jxiop.api.entity.StationQrCodeStatistics;
import com.yeejoin.amos.boot.module.jxiop.api.mapper.*;
import com.yeejoin.amos.boot.module.jxiop.api.util.Constants;
import com.yeejoin.amos.boot.module.jxiop.biz.mapper2.SjglZsjZsbtzMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.typroject.tyboot.component.emq.EmqKeeper;

import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Component
public class PersonYardTimeTask {

    @Autowired
    PersonBasicMapper personBasicMapper;

    @Autowired
    PersonBasicServiceImpl personBasicService;

    //人员资质信息service
    @Autowired
    PersonCertificateMapper personCertificateMapper;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private PersonAccountMapper personAccountMapper;

    @Autowired
    protected EmqKeeper emqKeeper;

    @Autowired
    private StationQrCodeStatisticsMapper stationQrCodeStatisticsMapper;

    @Autowired
    private StationQrCodeStatisticsServiceImpl stationQrCodeStatisticsService;

    @Autowired
    private SjglZsjZsbtzMapper sjglZsjZsbtzMapper;

    @Autowired
    private StationBasicMapper stationBasicMapper;


    @Scheduled(cron = "${person.yard.cron:0 0 0 1/1 * ?}")
    public void timeYardTimeTask() {
        if (!redisUtils.hasKey(Constants.JXIOP_DICT_POST) || !redisUtils.hasKey(Constants.JXIOP_DICT_CERTIFICATES)) {
            personBasicService.addRedisPostAndCerInfo();
        }
        // 岗位所需证书信息
        Map<String, String> postNameMap = (Map<String, String>) redisUtils.get(Constants.JXIOP_DICT_POST);
        // 证书临期信息
        Map<String, String> certificatesMap = (Map<String, String>) redisUtils.get(Constants.JXIOP_DICT_CERTIFICATES);
        List<PersonBasic> personBasicList = personBasicMapper.selectList(null);

        List<PersonCertificate> personCertificates = personCertificateMapper.selectList(null);

        List<PersonAccount> personAccounts = personAccountMapper.selectList(null);
        Map<Long, PersonAccount> personAccountMap = personAccounts.stream().collect(Collectors.toMap(PersonAccount::getPersonId, t -> t));
        Map<Long, List<PersonCertificate>> perCertificateMap = personCertificates.stream().filter(item -> ObjectUtils.isNotEmpty(item.getPersonId())).collect(Collectors.groupingBy(PersonCertificate::getPersonId));

        List<PersonBasic> personBasics = new ArrayList<>();
        personBasicList.forEach(personBasic -> {
            PersonAccount personAccount = personAccountMap.get(personBasic.getSequenceNbr());

            List<PersonCertificate> personCertificateList = perCertificateMap.get(personBasic.getSequenceNbr());
            //默认红码
            personBasic.setQrcodeColor(QrcodeColorEnum.RED.getCode());
            // 该岗位应获得的证书
            List<String> list2 = new ArrayList<>();
            if (StringUtils.isNotEmpty(personBasic.getPostName())) {
                String certificates = String.valueOf(postNameMap.get(personBasic.getPostName()));
                if (!StringUtils.isEmpty(certificates)) {
                    list2 = Arrays.asList(certificates.split(","));
                }
            }
            List<String> list = new ArrayList(list2);
            //人员资质信息
            Integer isInMonth = 0;
            Integer isOver = 0;
            // 过期的证书
            List<String> overCertificateList = new ArrayList<>();
            // 临期证书
            List<String> inMonthCertificateList = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(personCertificateList)) {
                for (PersonCertificate item : personCertificateList) {
                    int validPeriod = StringUtils.isEmpty(item.getValidPeriod()) ? 3 : Integer.parseInt(item.getValidPeriod());
                    Date date = DateUtils.dateAddYears(item.getCertificateTime(), validPeriod);
                    if (list.contains(item.getCertificateName()) &&
                            DateUtils.dateCompare(date, new Date()) == -1) {
                        isOver = 1;
                        overCertificateList.add(item.getCertificateName());
                    }
                    try {
                        if (list.contains(item.getCertificateName()) &&
                                DateUtils.dateBetweenIncludeToday(new Date(), date) < Integer.valueOf(certificatesMap.get(item.getCertificateName())) &&
                                DateUtils.dateCompare(date, new Date()) == 1) {
                            isInMonth = 1;
                            inMonthCertificateList.add(item.getCertificateName());
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    list.remove(item.getCertificateName());
                }
            }

            // 缺证
            List<String> noCertificateList = new ArrayList<>(list);

            List<String> strings = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(overCertificateList)) {
                strings.add("过期证书：" + String.join("，" , overCertificateList));
            }
            if (CollectionUtils.isNotEmpty(inMonthCertificateList)) {
                strings.add("临期证书：" + String.join("，" , inMonthCertificateList));
            }
            if (CollectionUtils.isNotEmpty(noCertificateList)) {
                strings.add("缺少证书：" + String.join("，" , noCertificateList));
            }
            String join = "";
            if (CollectionUtils.isNotEmpty(strings)) {
                join = String.join("；", strings);
            }
            String missingCertificateOld = personBasic.getMissingCertificate();
            personBasic.setMissingCertificate(join);

            String qrcodeColorOld = personBasic.getQrcodeColor();
            if (CollectionUtils.isEmpty(list) && isInMonth == 0 && isOver == 0) {
                personBasic.setQrcodeColor(QrcodeColorEnum.GREEN.getCode());
                personBasic.setQrcodeDesc("证书齐全");
                personBasic.setQrcodeDate(new Date());
            } else if ((CollectionUtils.isEmpty(list) && isOver == 1) || (CollectionUtils.isNotEmpty(list))) {
                personBasic.setQrcodeColor(QrcodeColorEnum.RED.getCode());
                personBasic.setQrcodeDesc("证书不全");
                personBasic.setQrcodeDate(new Date());
            } else if (CollectionUtils.isEmpty(list) && isOver == 0 && isInMonth == 1) {
                personBasic.setQrcodeColor(QrcodeColorEnum.YELLOW.getCode());
                personBasic.setQrcodeDesc("证书临期");
                personBasic.setQrcodeDate(new Date());
            }

            if (!join.equals(missingCertificateOld)) {
                personBasic.setRecDate(new Date());
                this.personBasicMapper.updateById(personBasic);
                if (("证书不全".equals(personBasic.getQrcodeDesc()) ||
                        "证书临期".equals(personBasic.getQrcodeDesc()))) {
                    BizMessage bizMessage = new BizMessage();
                    bizMessage.setIndexKey("RYFM");
                    bizMessage.setIndexValue(personBasic.getPostName() + personBasic.getQrcodeDesc());
                    RiskBizInfoVo riskBizInfoVo = personBasicService.fetchData(personBasic, personAccount, join);
                    bizMessage.setBizInfo(riskBizInfoVo);
                    bizMessage.setDataSource("人员赋码");
                    try {
                        emqKeeper.getMqttClient().publish(PersonBasicServiceImpl.RYFM_DATA_MQTT_TOPIC, JSON.toJSONString(bizMessage).getBytes(StandardCharsets.UTF_8), 2, false);
                    } catch (MqttException e) {
                        e.printStackTrace();
                    }
                } else if ("证书齐全".equals(personBasic.getQrcodeDesc())) {
                    HashMap<String, String> personMap = new HashMap<>();
                    personMap.put("objectId", String.valueOf(personBasic.getSequenceNbr()));
                    personMap.put("qrCodeColor", qrcodeColorOld);
                    personMap.put("warningObjectType", "RYFM");
                    personMap.put("sourceAttribution", personBasic.getProjectOrgCode());
                    personMap.put("sourceAttributionDesc", personAccount.getProjectName());
                    personMap.put("warningSourceType", "人员赋码");
                    try {
                        emqKeeper.getMqttClient().publish(PersonBasicServiceImpl.RYFM_GREEN, JSON.toJSONString(personMap).getBytes(StandardCharsets.UTF_8), 2, false);
                    } catch (MqttException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }


    @Scheduled(cron = "0 0/30 * * * ?")
    public void stationQrCodeStatisticsData() {
        // 1.先删除数据
        String now = DateUtils.getDateNowShortStr();
        LambdaQueryWrapper<StationQrCodeStatistics> qw = new LambdaQueryWrapper<>();
        qw.eq(StationQrCodeStatistics::getRecordDate, now);
        stationQrCodeStatisticsService.remove(qw);
        // 2.当天统计数据组装
        List<StationBasicDto> stationBasicListAll = stationBasicMapper.getStationBasicListAll();
        // 2.1人员赋码数据
        List<StationQrCodeStatistics> personStatistics = personBasicMapper.getPersonStatistics();
        // 2.2设备赋码数据
        List<StationQrCodeStatistics> equipQrcodeInfo = sjglZsjZsbtzMapper.getEquipQrcodeInfo();
        Map<String, String> collect = stationBasicListAll.stream().filter(t -> StringUtils.isNotEmpty(t.getStationNumber())).filter(t -> StringUtils.isNotEmpty(t.getProjectOrgCode())).collect(Collectors.toMap(StationBasicDto::getStationNumber, StationBasicDto::getProjectOrgCode));
        equipQrcodeInfo.stream().filter(t -> collect.containsKey(t.getCode())).forEach( item -> item.setCode(collect.get(item.getCode())));
        // 2.3任务赋码数据
        List<StationQrCodeStatistics> taskQrcodeInfo = sjglZsjZsbtzMapper.getTaskQrcodeInfo();
        taskQrcodeInfo.stream().filter(t -> collect.containsKey(t.getCode())).forEach( item -> item.setCode(collect.get(item.getCode())));
        // 3.人员、任务、设备整合且过滤只有场站的才统计（原因评估这边是显示的场站下的数据）
        personStatistics.addAll(equipQrcodeInfo);
        personStatistics.addAll(taskQrcodeInfo);
        List<StationQrCodeStatistics> withStationStatistics = personStatistics.stream().filter(p->StringUtils.isNotEmpty(p.getCode()) && stationBasicListAll.stream().anyMatch(s->s.getProjectOrgCode().equals(p.getCode()))).collect(Collectors.toList());
        stationQrCodeStatisticsService.saveBatch(withStationStatistics);

    }


}
