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.MessageSateEnum;
import com.tofly.gpsboot.common.system.MessageTopicEnum;
import com.tofly.gpsboot.common.system.MessageTypeEnum;
import com.tofly.gpsboot.common.system.OrderStateEnum;
import com.tofly.gpsboot.mapper.maintain.RepairorderMapper;
import com.tofly.gpsboot.service.maintain.RepairorderService;
import com.tofly.gpsboot.service.maintain.RepairuserService;
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.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 RepairOrderTimeOutRemindHandler {

    @Autowired
    private RepairorderService repairorderService;
    @Autowired
    private RepairuserService repairuserService;
    @Autowired
    private RepairorderMapper repairorderMapper;
    @Value("${gps.plan.web.repairOrder}")
    private String planWebRepairOrderRouteIp;
    @Value("${gps.plan.app.repairOrder}")
    private String planAppRepairOrderRouteIp;


    @XxlJob("repairOrderTimeOutRemindHandler")
    public ReturnT<String> repairOrderTimeOutRemindHandler(String param) {
        // 判断当前抢维修计划状态处于 在 2:未开始 , 3:正在执行
        List<String> stateList = new ArrayList<>();
        stateList.add(OrderStateEnum.ORDER_STATE_NOT_START.getCode());
        stateList.add(OrderStateEnum.ORDER_STATE_BEING_PERFORMED.getCode());
        List<Repairorder> list = repairorderService.list(new QueryWrapper<Repairorder>().lambda()
                .eq(Repairorder::getTimeoutRemindFlag,"0")
                .in(Repairorder::getState,stateList));
        // 判断计划结束时间是否小于当前时间-1小时,若小于则提示当前工单 下对应的个人用户(个人任务未完成的) 消息
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime localDateTime = now.minusHours(1L);
        // 消息提示发送人
        Set<Long> remindUserId = new HashSet<>();
        list.forEach(info ->{
            LocalDateTime dateTime = DateTimeUtil.fromLong2LocalDateTime(info.getEndTime().getTime());
            if(!localDateTime.isBefore(dateTime)){
                // 判断当前 维修工单下 对应个人任务 是否完成,未完成 提醒
                List<Repairuser> repairuserList = repairuserService.list(new QueryWrapper<Repairuser>().lambda()
                        .eq(Repairuser::getRepairId, info.getId())
                        .ne(Repairuser::getState, OrderStateEnum.ORDER_STATE_PROCESSING_COMPLETE.getCode()));
                List<Long> collect = repairuserList.stream().map(Repairuser::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_MAINTENANCE_ORDER.getTopic());
            messagepush.setType(MessageTypeEnum.MESSAGE_TYPE_ROB_MAINTENANCE.getCode());
            messagepush.setTableName(MessageTopicEnum.TASK_PLAN_MAINTENANCE_ORDER.getTableName());
            messagepush.setMessage("抢维修任务超时提醒");
            messagepush.setTableId(0L);
            messagepush.setCreateUser(userId);
            messagepush.setCreateTime(DateTimeUtil.convertLDTToDate(now));
            // 跳转到工单页面
            messagepush.setRouteIp(planWebRepairOrderRouteIp);
            messagepush.setRouteIpApp(planAppRepairOrderRouteIp);
            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 = list.stream().map(Repairorder::getId).collect(Collectors.toList());
            repairorderService.update(new UpdateWrapper<Repairorder>().lambda()
                    .in(Repairorder::getId,collect)
                    .set(Repairorder::getTimeoutRemindFlag,"1"));
        }

        return ReturnT.SUCCESS;
    }

}
