package com.tofly.gpsboot.handler.plan;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.tofly.gpsboot.common.system.*;
import com.tofly.gpsboot.mapper.maintain.RepairorderMapper;
import com.tofly.gpsboot.service.paln.task.PlanService;
import com.tofly.gpsboot.service.paln.task.PlanchildService;
import com.tofly.gpsboot.util.DateTimeUtil;
import com.tofly.pojo.maintain.Repairorder;
import com.tofly.pojo.maintain.Repairuser;
import com.tofly.pojo.message.Messagepush;
import com.tofly.pojo.message.Messagerecipient;
import com.tofly.pojo.plan.Plan;
import com.tofly.pojo.plan.Planchild;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * 巡检超时提醒
 * @author BZ-DJJ
 */
@Component
public class PlanTimeoutRemindHandler {

    @Autowired
    private PlanService planService;
    @Autowired
    private PlanchildService planchildService;
    @Autowired
    private RepairorderMapper repairorderMapper;
    @Value("${gps.plan.web.inspection}")
    private String planWebInspectionRouteIp;
    @Value("${gps.plan.app.inspection}")
    private String planAppInspectionRouteIp;

    @XxlJob("planTimeoutRemindHandler")
    public ReturnT<String> planTimeoutRemindHandler(String param) {
        // 获取当前巡检计划状态为5已开始未执行 3 正在执行的数据 2未开始
        List<String> planStateList = new ArrayList<>();
        planStateList.add(PlanStateEnum.PLAN_STATE_BEING_PERFORMED.getCode());
        planStateList.add(PlanStateEnum.PLAN_STATE_EXECUTION_NOT_STARTED.getCode());
        planStateList.add(PlanStateEnum.PLAN_STATE_NOT_START.getCode());

        List<Plan> planList = planService.list(new QueryWrapper<Plan>().lambda()
                .eq(Plan::getTimeoutRemindFlag,"0")
                .in(Plan::getPlanState, planStateList));
        // 判断计划结束时间是否小于当前时间 -1,若小于 发送对应的个人用户(个人任务未完成的) 消息
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime localDateTime = now.minusHours(1L);
        // 消息提示发送人
        Set<Long> remindUserId = new HashSet<>();
        planList.forEach(info ->{
            LocalDateTime dateTime = DateTimeUtil.fromLong2LocalDateTime(info.getPlanEnddate().getTime());
            if(!localDateTime.isBefore(dateTime)){
                // 判断当前 维修工单下 对应个人任务 是否完成,未完成 提醒
                List<Planchild> repairuserList = planchildService.list(new QueryWrapper<Planchild>().lambda()
                        .eq(Planchild::getPlanId, info.getId())
                        .ne(Planchild::getPlanState, OrderStateEnum.ORDER_STATE_PROCESSING_COMPLETE.getCode()));
                List<Long> collect = repairuserList.stream().map(Planchild::getRespUser).collect(Collectors.toList());
                remindUserId.addAll(collect);
            }
        });

        AtomicReference<Long> messagePushId = new AtomicReference<>(repairorderMapper.getPlanTempMaxId("TF_YWPN_MESSAGEPUSH_W"));
        AtomicReference<Long> messageRecipientId = new AtomicReference<>(repairorderMapper.getPlanTempMaxId("TF_YWPN_MESSAGERECIPIENT_W"));

        List<Messagepush> messagePushList = new ArrayList<>();
        List<Messagerecipient> messageRecipientList = new ArrayList<>();
        remindUserId.forEach(userId->{
            Long message1 = messagePushId.get();
            Long recipient1 = messageRecipientId.get();
            Messagepush messagepush = new Messagepush();
            // 消息主题/消息类型/消息表名/消息表中id/路由地址跳转
            messagepush.setId(message1);
            messagepush.setTopic(MessageTopicEnum.TASK_PLAN_SEND.getTopic());
            messagepush.setType(MessageTypeEnum.MESSAGE_TYPE_INSPECTION.getCode());
            messagepush.setTableName(MessageTopicEnum.TASK_PLAN_SEND.getTableName());
            messagepush.setMessage("巡检计划任务超时提醒");
            messagepush.setTableId(0L);
            // 跳转到工单页面
            messagepush.setRouteIp(planWebInspectionRouteIp);
            messagepush.setRouteIpApp(planAppInspectionRouteIp);
            messagepush.setCreateUser(userId);
            messagepush.setCreateTime(DateTimeUtil.convertLDTToDate(now));
            // 消息与接收人信息处理
            Messagerecipient messagerecipient = new Messagerecipient();
            messagerecipient.setId(recipient1);
            messagerecipient.setMessageId(message1);
            messagerecipient.setRecipient(userId);
            messagerecipient.setFlag(MessageSateEnum.MESSAGE_SATE_NO.getCode());
            messagePushList.add(messagepush);
            messageRecipientList.add(messagerecipient);
            Long idAndSet = message1+1;
            Long andSet = recipient1+1;
            messagePushId.set(idAndSet);
            messageRecipientId.set(andSet);
        });
        if(messagePushList.size()>0){
            repairorderMapper.addMessageList(messagePushList);
            repairorderMapper.addMessageRecipientList(messageRecipientList);
            // 赋值已超时提醒
            List<Long> collect = planList.stream().map(Plan::getId).collect(Collectors.toList());
            planService.update(new UpdateWrapper<Plan>().lambda()
                    .in(Plan::getId,collect)
                    .set(Plan::getTimeoutRemindFlag,"1"));
        }
        return ReturnT.SUCCESS;
    }

}
