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.Constant;
import com.tofly.gpsboot.common.system.*;
import com.tofly.pojo.maintain.Dispatch;
import com.tofly.pojo.plan.dto.TaskMessageDto;
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.Usertask;
import com.tofly.pojo.plan.Plan;
import com.tofly.pojo.plan.PlanInspectUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
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.app.eventMange}")
    private String eventMangeAppRouteIp;
    @Value("${gps.plan.web.eventMange}")
    private String eventMangeWebRouteIp;

    @Value("${gps.plan.app.floodSeason}")
    private String floodSeasonAppRouteIp;
    @Value("${gps.plan.web.floodSeason}")
    private String floodSeasonRouteIp;


    @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;

    /**
     * 计划任务发送
     *
     * @param planList
     */
    @Override
    public void planSendMessage(List<Plan> planList) {

        // 代办事项处理
        planList.forEach(info -> {
            // 获取计划中的巡检人
            Set<Long> userList = planInspectUserService.list(new QueryWrapper<PlanInspectUser>().lambda().eq(PlanInspectUser::getPlanId, info.getId())).stream().map(PlanInspectUser::getUserId).collect(Collectors.toSet());
            userList.forEach(
                    aLong -> {
                        Messagepush messagepush = new Messagepush();
                        // 消息主题/消息类型/消息表名/消息表中id/路由地址跳转
                        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.setRouteIp(planWebInspectionRouteIp);
                        messagepush.setRouteIpApp(planAppInspectionRouteIp);
                        // 消息与接收人信息处理
                        messageRecipientService.setMessageRecipient(messagepush, aLong);
                        Usertask usertask = new Usertask();
                        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());
                        userTaskClient.save(usertask);
                    }
            );
            // 子计划生成
            planchildService.generatePlanChildList(userList,info.getId());
        });


    }


    /**
     * 隐患任务发送
     *
     * @param planList
     */
    @Override
    public void planSendMessageTrouble(List<Plan> planList) {
        // 代办事项处理
        planList.forEach(info -> {
            // 获取计划中的巡检人
            Set<Long> userList = planInspectUserService.list(new QueryWrapper<PlanInspectUser>().lambda().eq(PlanInspectUser::getPlanId, info.getId())).stream().map(PlanInspectUser::getUserId).collect(Collectors.toSet());


            userList.forEach(
                    aLong -> {
                        Messagepush messagepush = new Messagepush();
                        // 消息主题/消息类型/消息表名/消息表中id/路由地址跳转
                        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.setRouteIp(planWebHiddenTroubleRouteIp);
                        messagepush.setRouteIpApp(planAppHiddenTroubleRouteIp);
                        // 消息与接收人信息处理
                        messageRecipientService.setMessageRecipient(messagepush, aLong);
                        Usertask usertask = new Usertask();
                        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());
                        userTaskClient.save(usertask);
                    }
            );
            // 子计划生成
            planchildService.generatePlanChildList(userList,info.getId());
        });
    }

    /**
     * 工地监护任务发送
     *
     * @param planList
     */
    @Override
    public void planSendMessageBuild(List<Plan> planList) {

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


            userList.forEach(
                    aLong -> {
                        Messagepush messagepush = new Messagepush();
                        // 消息主题/消息类型/消息表名/消息表中id/路由地址跳转
                        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.setRouteIp(planWebConstructionSiteRouteIp);
                        messagepush.setRouteIpApp(planAppConstructionSiteRouteIp);
                        // 消息与接收人信息处理
                        messageRecipientService.setMessageRecipient(messagepush, aLong);
                        Usertask usertask = new Usertask();
                        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());
                        userTaskClient.save(usertask);
                    }
            );
            // 子计划生成
            planchildService.generatePlanChildList(userList,info.getId());
        });

    }

    @Override
    public void planSendMessageMaintain(List<Plan> planList) {

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

            userList.forEach(
                    aLong -> {
                        Messagepush messagepush = new Messagepush();
                        // 消息主题/消息类型/消息表名/消息表中id/路由地址跳转
                        messagepush.setTopic(MessageTopicEnum.TASK_CONSTRUCTION_MAINTAIN.getTopic());
                        messagepush.setType(MessageTypeEnum.MESSAGE_TYPE_MAINTAIN.getCode());
                        messagepush.setTableName(MessageTopicEnum.TASK_CONSTRUCTION_MAINTAIN.getTableName());
                        messagepush.setTableId(info.getId());
                        // 跳转到维护任务页面
                        messagepush.setRouteIp(planWebConstructionSiteRouteIp);
                        messagepush.setRouteIpApp(planAppConstructionSiteRouteIp);
                        // 消息与接收人信息处理
                        messageRecipientService.setMessageRecipient(messagepush, aLong);
                        Usertask usertask = new Usertask();
                        usertask.setEndTime(info.getPlanEnddate());
                        usertask.setStartTime(info.getPlanBegindate());
                        usertask.setTknm(MessageTopicEnum.TASK_CONSTRUCTION_MAINTAIN.getTopic());
                        usertask.setTkty(MessageTypeEnum.MESSAGE_TYPE_MAINTAIN.getCode());
                        usertask.setTableName(MessageTopicEnum.TASK_CONSTRUCTION_MAINTAIN.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());
                        userTaskClient.save(usertask);
                    }
            );
            // 子计划生成
            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);
                usertask.setCreateUser(SecurityUtils.getUserId());
                usertask.setCreateTime(new Date());
                usertask.setCreateUser(SecurityUtils.getUserId());
                usertask.setCreateTime(new Date());
                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());
        usertask.setCreateUser(SecurityUtils.getUserId());
        usertask.setCreateTime(new Date());
        userTaskClient.save(usertask);
    }

    @Override
    public void orderForwardingSendMessage(Repairorder repairOrder, Long forwardingUserId, String notes) {
        Messagepush messagepush = new Messagepush();
        // 消息主题/消息类型/消息表名/消息表中id/路由地址跳转/消息详情
        messagepush.setTopic(MessageTopicEnum.TASK_PLAN_FORWARDING_ORDER.getTopic());
        messagepush.setType(MessageTypeEnum.MESSAGE_TYPE_ROB_MAINTENANCE.getCode());
        messagepush.setTableName(MessageTopicEnum.TASK_PLAN_FORWARDING_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_FORWARDING_ORDER.getTopic());
        usertask.setTkty(MessageTypeEnum.MESSAGE_TYPE_ROB_MAINTENANCE.getCode());
        usertask.setTableName(MessageTopicEnum.TASK_PLAN_FORWARDING_ORDER.getTableName());
        usertask.setTableId(repairOrder.getId());
        usertask.setIshandle(UserTaskStateEnumEnum.IS_HANDLER_PENDING.getCode());
        usertask.setRouteIp(planWebRepairOrderRouteIp);
        usertask.setRouteAppIp(planAppRepairOrderRouteIp);
        usertask.setHandleUser(forwardingUserId);
        usertask.setCreateUser(SecurityUtils.getUserId());
        usertask.setCreateTime(new Date());
        userTaskClient.save(usertask);
    }

    @Override
    public void eventAnFloodSendMessage(Dispatch dispatch, String notes) {
        Messagepush messagepush = new Messagepush();
        // 消息主题/消息类型/消息表名/消息表中id/路由地址跳转/消息详情
        //事件上报
        if(DispatchEnum.EVENT_MANAGE.getCode().equals(dispatch.getType())){
            messagepush.setTopic(MessageTopicEnum.TASK_PLAN_EVENTMANAGE_SEND.getTopic());
            messagepush.setType(MessageTypeEnum.MESSAGE_TYPE_EVENT_MANAGE.getCode());
            messagepush.setTableName(MessageTopicEnum.TASK_PLAN_EVENTMANAGE_SEND.getTableName());
            messagepush.setRouteIp(eventMangeWebRouteIp);
            messagepush.setRouteIpApp(eventMangeAppRouteIp);
        }else if(DispatchEnum.FLOOD_SEASON.getCode().equals(dispatch.getType())){
            messagepush.setTopic(MessageTopicEnum.TASK_PLAN_EVENTMANAGE_SEND.getTopic());
            messagepush.setType(MessageTypeEnum.MESSAGE_TYPE_FLOOD_SEASON.getCode());
            messagepush.setTableName(MessageTopicEnum.TASK_PLAN_EVENTMANAGE_SEND.getTableName());
            messagepush.setRouteIp(floodSeasonRouteIp);
            messagepush.setRouteIpApp(floodSeasonAppRouteIp);
        }

        messagepush.setTableId(dispatch.getId());
        // 跳转到查询页面 TODO 处理跳转地址

        messagepush.setMessage(notes);
        // 消息与接收人信息处理
        messageRecipientService.setMessageRecipient(messagepush,Long.parseLong(dispatch.getMajorHandler()) );
    }

}
