package com.tofly.gpsboot.service.mq.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tofly.api.UserTaskClient;
import com.tofly.common.oauth.util.SecurityUtils;
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.UserTaskStateEnumEnum;
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.service.mq.IMessageRecipientService;
import com.tofly.gpsboot.service.mq.IPlanMessageService;
import com.tofly.gpsboot.service.paln.task.PlanInspectUserService;
import com.tofly.gpsboot.service.paln.task.PlanchildService;
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.message.Usertask;
import com.tofly.pojo.plan.Plan;
import com.tofly.pojo.plan.PlanInspectUser;
import com.tofly.pojo.plan.dto.TaskMessageDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * @author Zev
 */
@Service("PLAN_MESSAGE")
public class PlanMessageServiceImpl implements IPlanMessageService {

    @Autowired
    private PlanInspectUserService planInspectUserService;

    @Autowired
    private UserTaskClient userTaskClient;

    @Autowired
    private IMessageRecipientService messageRecipientService;

    @Value("${gps.plan.web.inspection}")
    private String planWebInspectionRouteIp;
    @Value("${gps.plan.app.inspection}")
    private String planAppInspectionRouteIp;

    @Value("${gps.plan.web.repairOrder}")
    private String planWebRepairOrderRouteIp;
    @Value("${gps.plan.app.repairOrder}")
    private String planAppRepairOrderRouteIp;

    @Value("${gps.plan.web.constructionSite}")
    private String planWebConstructionSiteRouteIp;
    @Value("${gps.plan.app.constructionSite}")
    private String planAppConstructionSiteRouteIp;

    @Value("${gps.plan.web.hiddenTrouble}")
    private String planWebHiddenTroubleRouteIp;
    @Value("${gps.plan.app.hiddenTrouble}")
    private String planAppHiddenTroubleRouteIp;

    @Autowired
    private RepairuserService repairuserService;
    @Autowired
    private PlanchildService planchildService;
    @Autowired
    private RepairorderService repairorderService;
    @Autowired
    private RepairorderMapper repairorderMapper;

    /**
     * 计划任务发送
     *
     * @param planList
     */
    @Override
    public void planSendMessage(List<Plan> planList) {
        AtomicReference<Long> messagePushId = new AtomicReference<>(repairorderMapper.getPlanTempMaxId("TF_XRTY_NEW_UDB.TF_YWPN_MESSAGEPUSH_W"));
        AtomicReference<Long> messageRecipientId = new AtomicReference<>(repairorderMapper.getPlanTempMaxId("TF_XRTY_NEW_UDB.TF_YWPN_MESSAGERECIPIENT_W"));
        AtomicReference<Long> userTaskId = new AtomicReference<>(repairorderMapper.getPlanTempMaxId("TF_XRTY_NEW_UDB.TF_YWPN_USERTASK_W"));


        // 代办事项处理
        planList.forEach(info -> {
            // 获取计划中的巡检人
            Set<Long> userList = planInspectUserService.list(new QueryWrapper<PlanInspectUser>().lambda().eq(PlanInspectUser::getPlanId, info.getId())).stream().map(PlanInspectUser::getUserId).collect(Collectors.toSet());
            List<Messagepush> messagePushList = new ArrayList<>();
            List<Messagerecipient> messageRecipientList = new ArrayList<>();
            List<Usertask> userTaskList = new ArrayList<>();

            userList.forEach(
                    aLong -> {
                        Messagepush messagepush = new Messagepush();
                        // 消息主题/消息类型/消息表名/消息表中id/路由地址跳转
                        Long message1 = messagePushId.get();
                        Long recipient1 = messageRecipientId.get();
                        Long userTask1 = userTaskId.get();
                        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.setTableId(info.getId());
                        messagepush.setCreateTime(new Date());
                        messagepush.setCreateUser(SecurityUtils.getUserId());
                        messagepush.setMessage("");
                        // 跳转到计划任务页面
                        messagepush.setRouteIp(planWebInspectionRouteIp);
                        messagepush.setRouteIpApp(planAppInspectionRouteIp);
                        // 消息与接收人信息处理
//                        messageRecipientService.setMessageRecipient(messagepush, aLong);
                        // 消息与接收人信息处理
                        Messagerecipient messagerecipient = new Messagerecipient();
                        messagerecipient.setId(recipient1);
                        messagerecipient.setMessageId(message1);
                        messagerecipient.setRecipient(aLong);
                        messagerecipient.setFlag(MessageSateEnum.MESSAGE_SATE_NO.getCode());
                        Usertask usertask = new Usertask();
                        usertask.setId(userTask1);
                        usertask.setEndTime(info.getPlanEnddate());
                        usertask.setStartTime(info.getPlanBegindate());
                        usertask.setTknm(MessageTopicEnum.TASK_PLAN_SEND.getTopic());
                        usertask.setTkty(MessageTypeEnum.MESSAGE_TYPE_INSPECTION.getCode());
                        usertask.setTableName(MessageTopicEnum.TASK_PLAN_SEND.getTableName());
                        usertask.setTableId(info.getId());
                        usertask.setIshandle(UserTaskStateEnumEnum.IS_HANDLER_NOT_STARTED.getCode());
                        usertask.setRouteIp(planWebInspectionRouteIp);
                        usertask.setRouteAppIp(planAppInspectionRouteIp);
                        usertask.setHandleUser(aLong);
                        usertask.setCreateUser(SecurityUtils.getUserId());
                        usertask.setCreateTime(new Date());
                        messagePushList.add(messagepush);
                        messageRecipientList.add(messagerecipient);
                        userTaskList.add(usertask);
                        Long idAndSet = message1+1;
                        Long andSet = recipient1+1;
                        Long task = userTask1+1;
                        messagePushId.set(idAndSet);
                        messageRecipientId.set(andSet);
                        userTaskId.set(task);
                    }
            );
            // 消息存入
            repairorderMapper.addMessageList(messagePushList);
            repairorderMapper.addMessageRecipientList(messageRecipientList);
            repairorderMapper.addUserTaskList(userTaskList);
            // 子计划生成
            planchildService.generatePlanChildList(userList,info.getId());
        });

    }


    /**
     * 隐患任务发送
     *
     * @param planList
     */
    @Override
    public void planSendMessageTrouble(List<Plan> planList) {
        AtomicReference<Long> messagePushId = new AtomicReference<>(repairorderMapper.getPlanTempMaxId("TF_XRTY_NEW_UDB.TF_YWPN_MESSAGEPUSH_W"));
        AtomicReference<Long> messageRecipientId = new AtomicReference<>(repairorderMapper.getPlanTempMaxId("TF_XRTY_NEW_UDB.TF_YWPN_MESSAGERECIPIENT_W"));
        AtomicReference<Long> userTaskId = new AtomicReference<>(repairorderMapper.getPlanTempMaxId("TF_XRTY_NEW_UDB.TF_YWPN_USERTASK_W"));

        // 代办事项处理
        planList.forEach(info -> {
            // 获取计划中的巡检人
            Set<Long> userList = planInspectUserService.list(new QueryWrapper<PlanInspectUser>().lambda().eq(PlanInspectUser::getPlanId, info.getId())).stream().map(PlanInspectUser::getUserId).collect(Collectors.toSet());

            List<Messagepush> messagePushList = new ArrayList<>();
            List<Messagerecipient> messageRecipientList = new ArrayList<>();
            List<Usertask> userTaskList = new ArrayList<>();
            userList.forEach(
                    aLong -> {
                        Long message1 = messagePushId.get();
                        Long recipient1 = messageRecipientId.get();
                        Long userTask1 = userTaskId.get();
                        Messagepush messagepush = new Messagepush();
                        // 消息主题/消息类型/消息表名/消息表中id/路由地址跳转
                        messagepush.setId(message1);
                        messagepush.setTopic(MessageTopicEnum.TASK_PLAN_HIDDEN_TROUBLE_SEND.getTopic());
                        messagepush.setType(MessageTypeEnum.MESSAGE_TYPE_TROUBLE.getCode());
                        messagepush.setTableName(MessageTopicEnum.TASK_PLAN_HIDDEN_TROUBLE_SEND.getTableName());
                        messagepush.setTableId(info.getId());
                        messagepush.setMessage("");
                        messagepush.setCreateUser(SecurityUtils.getUserId());
                        messagepush.setCreateTime(new Date());
                        // 跳转到隐患任务页面
                        messagepush.setRouteIp(planWebHiddenTroubleRouteIp);
                        messagepush.setRouteIpApp(planAppHiddenTroubleRouteIp);

                        // 消息与接收人信息处理
//                        messageRecipientService.setMessageRecipient(messagepush, aLong);
                        // 消息与接收人信息处理
                        Messagerecipient messagerecipient = new Messagerecipient();
                        messagerecipient.setId(recipient1);
                        messagerecipient.setMessageId(message1);
                        messagerecipient.setRecipient(aLong);
                        messagerecipient.setFlag(MessageSateEnum.MESSAGE_SATE_NO.getCode());
                        Usertask usertask = new Usertask();
                        usertask.setId(userTask1);
                        usertask.setEndTime(info.getPlanEnddate());
                        usertask.setStartTime(info.getPlanBegindate());
                        usertask.setTknm(MessageTopicEnum.TASK_PLAN_HIDDEN_TROUBLE_SEND.getTopic());
                        usertask.setTkty(MessageTypeEnum.MESSAGE_TYPE_TROUBLE.getCode());
                        usertask.setTableName(MessageTopicEnum.TASK_PLAN_HIDDEN_TROUBLE_SEND.getTableName());
                        usertask.setTableId(info.getId());
                        usertask.setIshandle(UserTaskStateEnumEnum.IS_HANDLER_NOT_STARTED.getCode());
                        usertask.setRouteIp(planWebHiddenTroubleRouteIp);
                        usertask.setRouteAppIp(planAppHiddenTroubleRouteIp);
                        usertask.setHandleUser(aLong);
                        usertask.setCreateUser(SecurityUtils.getUserId());
                        usertask.setCreateTime(new Date());
                        messagePushList.add(messagepush);
                        messageRecipientList.add(messagerecipient);
                        userTaskList.add(usertask);
                        Long idAndSet = message1+1;
                        Long andSet = recipient1+1;
                        Long task = userTask1+1;
                        messagePushId.set(idAndSet);
                        messageRecipientId.set(andSet);
                        userTaskId.set(task);
                    }
            );
            // 消息存入
            repairorderMapper.addMessageList(messagePushList);
            repairorderMapper.addMessageRecipientList(messageRecipientList);
            repairorderMapper.addUserTaskList(userTaskList);
            // 子计划生成
            planchildService.generatePlanChildList(userList,info.getId());
        });
    }

    /**
     * 工地监护任务发送
     *
     * @param planList
     */
    @Override
    public void planSendMessageBuild(List<Plan> planList) {
        AtomicReference<Long> messagePushId = new AtomicReference<>(repairorderMapper.getPlanTempMaxId("TF_XRTY_NEW_UDB.TF_YWPN_MESSAGEPUSH_W"));
        AtomicReference<Long> messageRecipientId = new AtomicReference<>(repairorderMapper.getPlanTempMaxId("TF_XRTY_NEW_UDB.TF_YWPN_MESSAGERECIPIENT_W"));
        AtomicReference<Long> userTaskId = new AtomicReference<>(repairorderMapper.getPlanTempMaxId("TF_XRTY_NEW_UDB.TF_YWPN_USERTASK_W"));


        // 代办事项处理
        planList.forEach(info -> {
            // 获取计划中的巡检人
            Set<Long> userList = planInspectUserService.list(new QueryWrapper<PlanInspectUser>().lambda().eq(PlanInspectUser::getPlanId, info.getId())).stream().map(PlanInspectUser::getUserId).collect(Collectors.toSet());
            List<Messagepush> messagePushList = new ArrayList<>();
            List<Messagerecipient> messageRecipientList = new ArrayList<>();
            List<Usertask> userTaskList = new ArrayList<>();

            userList.forEach(
                    aLong -> {
                        Long message1 = messagePushId.get();
                        Long recipient1 = messageRecipientId.get();
                        Long userTask1 = userTaskId.get();
                        Messagepush messagepush = new Messagepush();
                        // 消息主题/消息类型/消息表名/消息表中id/路由地址跳转
                        messagepush.setId(message1);
                        messagepush.setTopic(MessageTopicEnum.TASK_CONSTRUCTION_SITE_SEND.getTopic());
                        messagepush.setType(MessageTypeEnum.MESSAGE_TYPE_CONSTRUCTION_SITE.getCode());
                        messagepush.setTableName(MessageTopicEnum.TASK_CONSTRUCTION_SITE_SEND.getTableName());
                        messagepush.setTableId(info.getId());
                        messagepush.setCreateTime(new Date());
                        messagepush.setCreateUser(SecurityUtils.getUserId());
                        messagepush.setMessage("");
                        // 跳转到计划任务页面
                        messagepush.setRouteIp(planWebInspectionRouteIp);
                        messagepush.setRouteIpApp(planAppInspectionRouteIp);
                        // 消息与接收人信息处理
//                        messageRecipientService.setMessageRecipient(messagepush, aLong);
                        // 消息与接收人信息处理
                        Messagerecipient messagerecipient = new Messagerecipient();
                        messagerecipient.setId(recipient1);
                        messagerecipient.setMessageId(message1);
                        messagerecipient.setRecipient(aLong);
                        messagerecipient.setFlag(MessageSateEnum.MESSAGE_SATE_NO.getCode());
                        Usertask usertask = new Usertask();
                        usertask.setId(userTask1);
                        usertask.setEndTime(info.getPlanEnddate());
                        usertask.setStartTime(info.getPlanBegindate());
                        usertask.setTknm(MessageTopicEnum.TASK_CONSTRUCTION_SITE_SEND.getTopic());
                        usertask.setTkty(MessageTypeEnum.MESSAGE_TYPE_CONSTRUCTION_SITE.getCode());
                        usertask.setTableName(MessageTopicEnum.TASK_CONSTRUCTION_SITE_SEND.getTableName());
                        usertask.setTableId(info.getId());
                        usertask.setIshandle(UserTaskStateEnumEnum.IS_HANDLER_NOT_STARTED.getCode());
                        usertask.setRouteIp(planWebConstructionSiteRouteIp);
                        usertask.setRouteAppIp(planAppConstructionSiteRouteIp);
                        usertask.setHandleUser(aLong);
                        usertask.setCreateUser(SecurityUtils.getUserId());
                        usertask.setCreateTime(new Date());
                        messagePushList.add(messagepush);
                        messageRecipientList.add(messagerecipient);
                        userTaskList.add(usertask);
                        Long idAndSet = message1+1;
                        Long andSet = recipient1+1;
                        Long task = userTask1+1;
                        messagePushId.set(idAndSet);
                        messageRecipientId.set(andSet);
                        userTaskId.set(task);
                    }
            );
            // 消息存入
            repairorderMapper.addMessageList(messagePushList);
            repairorderMapper.addMessageRecipientList(messageRecipientList);
            repairorderMapper.addUserTaskList(userTaskList);
            // 子计划生成
            planchildService.generatePlanChildList(userList,info.getId());
        });

    }

    /**
     * 抢维修年计划任务发送
     *
     * @param data
     */
    @Override
    public void orderSendMessage(String data) {
        TaskMessageDto taskMessageDto = JSONObject.parseObject(data, TaskMessageDto.class);
        // 获取需要发送的计划抢修列表
        List<Repairorder> repairOrderList = taskMessageDto.getRepairOrderList();

        // 抢维修年计划任务发送
        repairOrderList.forEach(info -> {
            // 根据工单id获取需要抢修的用户列表
            List<Repairuser> repairuser = repairuserService.list(new QueryWrapper<Repairuser>().lambda().eq(Repairuser::getRepairId, info.getId()));
            Set<Long> userList = new HashSet<>();
            Set<Long> respUserIdList = new HashSet<>();
           if(null != repairuser && repairuser.size()>0){
               repairuser.forEach(user->{
//                   String teamUser = user.getTeamUser();
//                   if (!StringUtils.isEmpty(teamUser)) {
//                       userList.addAll(Arrays.stream(teamUser.split(Constant.CSV)).map(s -> Long.parseLong(s.trim()))
//                               .collect(Collectors.toList()));
//                   }
                   // 加入主要负责人
                   Long respUser = user.getRespUser();
                   userList.add(respUser);
                   // 待办任务只发送给主要负责人
                   respUserIdList.add(respUser);
               });

           }

            userList.forEach(userId -> {
                Messagepush messagepush = new Messagepush();
                // 消息主题/消息类型/消息表名/消息表中id/路由地址跳转
                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.setTableId(info.getId());
                // 跳转到工单页面
                messagepush.setRouteIp(planWebRepairOrderRouteIp);
                messagepush.setRouteIpApp(planAppRepairOrderRouteIp);
                // 消息与接收人信息处理
                messageRecipientService.setMessageRecipient(messagepush, userId);
            });
           // 代办任务处理
            respUserIdList.forEach(userId->{
                Usertask usertask = new Usertask();
                usertask.setEndTime(info.getEndTime());
                usertask.setStartTime(info.getStartTime());
                usertask.setTknm(MessageTopicEnum.TASK_PLAN_MAINTENANCE_ORDER.getTopic());
                usertask.setTkty(MessageTypeEnum.MESSAGE_TYPE_ROB_MAINTENANCE.getCode());
                usertask.setTableName(MessageTopicEnum.TASK_PLAN_MAINTENANCE_ORDER.getTableName());
                usertask.setTableId(info.getId());
                usertask.setIshandle(UserTaskStateEnumEnum.IS_HANDLER_NOT_STARTED.getCode());
                usertask.setRouteIp(planWebRepairOrderRouteIp);
                usertask.setRouteAppIp(planAppRepairOrderRouteIp);
                usertask.setHandleUser(userId);
                userTaskClient.save(usertask);
            });


        });


    }

    @Override
    public void orderRejectedSendMessage(Repairorder repairOrder,String notes) {

        Messagepush messagepush = new Messagepush();
        // 消息主题/消息类型/消息表名/消息表中id/路由地址跳转/消息详情
        messagepush.setTopic(MessageTopicEnum.TASK_PLAN_REJECTED_ORDER.getTopic());
        messagepush.setType(MessageTypeEnum.MESSAGE_TYPE_ROB_MAINTENANCE.getCode());
        messagepush.setTableName(MessageTopicEnum.TASK_PLAN_REJECTED_ORDER.getTableName());
        messagepush.setTableId(repairOrder.getId());
        // 跳转到查询页面
        messagepush.setRouteIp(planWebRepairOrderRouteIp);
        messagepush.setRouteIpApp(planAppRepairOrderRouteIp);
        messagepush.setMessage(notes);
        // 消息与接收人信息处理(审核人为热线传过来的工单创建人)
        messageRecipientService.setMessageRecipient(messagepush, repairOrder.getCreateUser());

//        // 新增代办任务
//        Usertask usertask = new Usertask();
//        usertask.setStartTime(new Date());
//        usertask.setTknm(MessageTopicEnum.TASK_PLAN_REJECTED_ORDER.getTopic());
//        usertask.setTkty(MessageTypeEnum.MESSAGE_TYPE_ROB_MAINTENANCE.getCode());
//        usertask.setTableName(MessageTopicEnum.TASK_PLAN_REJECTED_ORDER.getTableName());
//        usertask.setTableId(repairOrder.getId());
//        usertask.setIshandle(UserTaskStateEnumEnum.IS_HANDLER_PENDING.getCode());
//        usertask.setRouteIp(planWebRepairOrderRouteIp);
//        usertask.setRouteAppIp(planAppRepairOrderRouteIp);
//        usertask.setHandleUser(repairOrder.getCreateUser());
//        userTaskClient.save(usertask);
    }

    @Override
    public void orderForwardingSendMessage(Repairorder repairOrder, Long forwardingUserId, String notes) {
        Messagepush messagepush = new Messagepush();
        // 消息主题/消息类型/消息表名/消息表中id/路由地址跳转/消息详情
        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.setTableId(repairOrder.getId());
        // 跳转到查询页面
        messagepush.setRouteIp(planWebRepairOrderRouteIp);
        messagepush.setRouteIpApp(planAppRepairOrderRouteIp);
        messagepush.setMessage(notes);
        // 消息与接收人信息处理
        messageRecipientService.setMessageRecipient(messagepush, forwardingUserId);

        // 新增代办任务
        Usertask usertask = new Usertask();
        usertask.setStartTime(new Date());
        usertask.setTknm(MessageTopicEnum.TASK_PLAN_MAINTENANCE_ORDER.getTopic());
        usertask.setTkty(MessageTypeEnum.MESSAGE_TYPE_ROB_MAINTENANCE.getCode());
        usertask.setTableName(MessageTopicEnum.TASK_PLAN_MAINTENANCE_ORDER.getTableName());
        usertask.setTableId(repairOrder.getId());
        usertask.setIshandle(UserTaskStateEnumEnum.IS_HANDLER_PENDING.getCode());
        usertask.setRouteIp(planWebRepairOrderRouteIp);
        usertask.setRouteAppIp(planAppRepairOrderRouteIp);
        usertask.setHandleUser(forwardingUserId);
        userTaskClient.save(usertask);
    }

}
