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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yeejoin.amos.boot.biz.common.utils.DateUtils;
import com.yeejoin.amos.boot.module.jyjc.api.enums.BizTypeEnum;
import com.yeejoin.amos.boot.module.ymt.api.common.StringUtil;
import com.yeejoin.amos.boot.module.ymt.api.dto.UseInfoModel;
import com.yeejoin.amos.boot.module.ymt.api.entity.TzsUserInfo;
import com.yeejoin.amos.boot.module.ymt.api.mapper.TzsUserInfoMapper;
import com.yeejoin.amos.boot.module.ymt.api.mapper.UseInfoMapper;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import com.yeejoin.amos.feign.systemctl.model.MessageModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.text.ParseException;

import java.util.*;
import java.util.stream.Collectors;

@EnableScheduling
@Service
@Slf4j
public class EquipRegularlyRemindServicelmpl {
@Autowired
private UseInfoMapper useInfoMapper;
@Autowired
private TzsUserInfoMapper tzsUserInfoMapper;
@Autowired
CommonserviceImpl commonservice;

@Scheduled(cron = "${equip-hint:0 0 8 * * ?}")
public void sendReminderMessage(){
    //获取当前日期
    String currentDate = DateUtils.getDateNowShortStr();
    Date curDate = null;
    try {
        curDate = DateUtils.dateParse(currentDate, null);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    Date date = DateUtils.dateAddDays(curDate, 31);
    List<String> types = new ArrayList<>();
    List<String> status = new ArrayList<>();
    types.add("DTJC");
    types.add("DQJY");
    //查询需要发送消息的设备
//    LambdaQueryWrapper<UseInfo> query = new LambdaQueryWrapper<>();
//    query.in(UseInfo::getLastInspectType,types);
//    query.in(UseInfo::getStatus,status);
//    query.le(UseInfo::getNextInspectDate,date).or().ge(UseInfo::getNextInspectDate,currentDate);
//    List<UseInfo> equips = useInfoMapper.selectList(query);
//
    List<UseInfoModel> equips = useInfoMapper.selecEquipInfotList(types, status, date, curDate);
    //超期设备
    List<UseInfoModel> cqEquip = new ArrayList<>();
    //临期设备
    List<UseInfoModel> lqEquip = new ArrayList<>();

    for (UseInfoModel equip : equips) {
            //下次检验时间小于当前时间为超期 反之为临期
        if (DateUtils.dateCompare(equip.getNextInspectDate(),curDate) < 0 ){
            cqEquip.add(equip);
        }else {
            lqEquip.add(equip);
        }
    }
    Map<String, List<UseInfoModel>> cqEquips = cqEquip.stream().collect(Collectors.groupingBy(UseInfoModel::getUseUnitCreditCode));
    Map<String, List<UseInfoModel>> lqEquips = lqEquip.stream().collect(Collectors.groupingBy(UseInfoModel::getUseUnitCreditCode));
    for (String s : cqEquips.keySet()) {
        //查询单位下共有多少超期及临期装备
        List<UseInfoModel> useInfos = cqEquips.get(s);
        int cq = useInfos.size();
        int lq = lqEquips.containsKey(s)?lqEquips.get(s).size():0;

        //查询符合发送规则的人员电话
        LambdaQueryWrapper<TzsUserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(TzsUserInfo::getPost,"6552");
        queryWrapper.isNotNull(TzsUserInfo::getPhone);
        List<TzsUserInfo> tzsUserInfos = tzsUserInfoMapper.selectList(queryWrapper);
        List<String> phones = tzsUserInfos.stream().filter(e-> StringUtil.isNotEmpty(e.getPhone())).map(TzsUserInfo::getPhone).collect(Collectors.toList());
        List<String> userIds = tzsUserInfos.stream().filter(e-> StringUtil.isNotEmpty(e.getAmosUserId())).map(TzsUserInfo::getAmosUserId).collect(Collectors.toList());
        // 组装短信内容  发送短信
        HashMap<String,String> smsParams = new HashMap<>();
        smsParams.put("smsCode","EQU_TZS_001");
        smsParams.put("lq", String.valueOf(lq));
        smsParams.put("cq", String.valueOf(cq));

        commonservice.sendMessage(smsParams,phones);

        //发送平台消息
        if ( lqEquips.containsKey(s)){
         useInfos.addAll(lqEquips.get(s));
        }
        for (UseInfoModel useInfo : useInfos) {

            Date nextInspectDate = useInfo.getNextInspectDate();
            try {
                MessageModel messageModel = new MessageModel();
                messageModel.setCategory(1); //1 :消息通知
                messageModel.setRelationId(useInfo.getRecord());
                int day = DateUtils.dateBetween(nextInspectDate, curDate);
                int day1 = DateUtils.dateBetween(nextInspectDate, date);
                if (day > 0) {
                    messageModel.setTitle("设备超期提醒");
                    messageModel.setBody(useInfo.getProductName()+"("+(useInfo.getSupervisoryCode()==null?"":useInfo.getSupervisoryCode()+") 已超期"+ Math.abs(day)+"天"));
                }else if (day1 > 0){
                    messageModel.setTitle("设备临期提醒");
                    messageModel.setBody(useInfo.getProductName()+"("+(useInfo.getSupervisoryCode()==null?"":useInfo.getSupervisoryCode()+") 还有"+ Math.abs(day1)+"天将到期"));
                }
                messageModel.setRecivers(userIds);
                messageModel.setIsSendWeb(true);
                messageModel.setMsgType("EQUIP_HINT");
                messageModel.setMsgTypeLabel("设备检验");
                Systemctl.messageClient.create(messageModel);
                log.info("信息发送完成");
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
    }

}


}
