package com.ruoyi.framework.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.project.business.domain.TbAgent;
import com.ruoyi.project.business.domain.TcProject;
import com.ruoyi.project.business.domain.train.TtTrain;
import com.ruoyi.project.business.domain.vo.reminder.AreaSalesDirectorVO;
import com.ruoyi.project.business.domain.vo.reminder.CheckAreaSalesDirectorVO;
import com.ruoyi.project.business.domain.vo.reminder.ProjectInfoVOForSendMessage;
import com.ruoyi.project.business.enums.MessageTypeEnum;
import com.ruoyi.project.business.enums.train.TrainStatusEnum;
import com.ruoyi.project.business.mapper.TbAgentMapper;
import com.ruoyi.project.business.mapper.TcFollowMapper;
import com.ruoyi.project.business.mapper.TtTrainMapper;
import com.ruoyi.project.business.service.ITbAgentService;
import com.ruoyi.project.business.service.ITcProjectService;
import com.ruoyi.project.business.service.ITtTrainService;
import com.ruoyi.project.common.domain.Message;
import com.ruoyi.project.common.service.ICommonService;
import com.ruoyi.project.common.service.ISseEmitterService;
import com.ruoyi.project.system.domain.SysConfig;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.service.ISysConfigService;
import lombok.extern.java.Log;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 定时任务调度测试
 * 
 * @author ruoyi
 */
@Component("crmTask")
@Log
public class CrmTask
{
    @Resource
    private ISysConfigService sysConfigService;

    @Resource
    private ITcProjectService tcProjectService;

    @Resource
    private TcFollowMapper tcFollowMapper;

    @Resource
    private TbAgentMapper tbAgentMapper;

    @Resource
    private ISseEmitterService sseEmitterService;
    @Resource
    private ICommonService commonService;

    @Resource
    private ITtTrainService ttTrainService;

    /**
     * 项目跟进提醒定时任务
     */
    public void reminderNotFollowingProjectTask()
    {
        System.out.println("项目跟进提醒定时任务开始！");
        String configValue;
        Long cycle;
        Map<Long, List<ProjectInfoVOForSendMessage>> sendMessageMap = new IdentityHashMap<Long, List<ProjectInfoVOForSendMessage>>();


        List<TcProject> projects = new ArrayList<TcProject>();
        try{
            // 获取系统参数（项目跟踪周期）
            configValue = sysConfigService.selectConfigByKey("project.tracking.cycle");
            if(StringUtils.isNotEmpty(configValue)){
                System.out.println("系统参数（项目跟踪周期）："+configValue);
                cycle = Long.parseLong(configValue);
                // 抽出所有需要提醒的项目
                projects = tcProjectService.selectProjectListByCycle(cycle);
            }else{
                log.info("系统参数（项目跟踪周期）为空，请确认！");
            }

            // 推送提醒站内信

            for (TcProject project: projects) {
                System.out.println("project：" + project.toString());
                List<Long>  targetUserId = new ArrayList<Long>();
                // 获取该项目的代理商的Id
                Long ownerAgentId = project.getOwnerAgent();

                // 代理商的userId
                Long agentUserId;
                // 上级代理商的userId
                Long parentAgentUserId;
                // 上级销售经理的userId
                Long parentSalerUserId;
                TbAgent agentInfo = new TbAgent();
                List <SysUser> userinfo = new ArrayList<SysUser>();
                if(ownerAgentId != 0){
                    // 获取项目所属代理商的userId
                    userinfo = tcFollowMapper.selectUserInfoByAgentId(ownerAgentId);
                    if(userinfo != null && userinfo.size() > 0){
                        agentUserId = userinfo.get(0).getUserId();
                        targetUserId.add(agentUserId);
                    }
                }else{
                    // 所属销售经理userId
                    targetUserId.add(project.getOwner());
                }

                // 获取该项目的上级代理商、上级销售的userId
                if(ownerAgentId != 0){
                     agentInfo = tbAgentMapper.selectById(ownerAgentId);
//                    System.out.println("agentInfo 1：" + agentInfo.toString());
                     if(agentInfo != null){
                         if (agentInfo.getParentAgentId() != null){
                             // 获取上级代理商的userId
                             userinfo = tcFollowMapper.selectUserInfoByAgentId(agentInfo.getParentAgentId());
                             if(userinfo != null && userinfo.size() > 0){
                                 parentAgentUserId = userinfo.get(0).getUserId();
                                 targetUserId.add(parentAgentUserId);
                             }


                             // 获取上级代理商信息
                             agentInfo = tbAgentMapper.selectById(agentInfo.getParentAgentId());
//                             System.out.println("agentInfo 2：" + agentInfo.toString());
                         }

                         // 获取上级销售经理的userId
                         if(agentInfo != null && agentInfo.getParentSalerId() != null){
                             parentSalerUserId = agentInfo.getParentSalerId();
                             targetUserId.add(parentSalerUserId);
                         }
                     }
                }

                // 获取该项目所属区域的区总的userId
                List<AreaSalesDirectorVO> areaSalesDirectors =  tcFollowMapper.selectAreaSalesDirector();
                for (AreaSalesDirectorVO director:areaSalesDirectors) {
                    // 判断是否为该代理商的销售区域总监
                    CheckAreaSalesDirectorVO checkVO =new CheckAreaSalesDirectorVO();
                    checkVO.setAgentPermissionChar(project.getPermissionChar());
                    checkVO.setDirectorPermissionChar(director.getPermissionChar());
                    Long selectCount = tcFollowMapper.getCountByAgentPermissionChar(checkVO);
                    if(selectCount > 0){
                        targetUserId.add(director.getUserId());
                        break;
                    }
                }

                // 存进Map
                saveIntoMap(sendMessageMap, targetUserId, project);
            }

            //  发站内信
            MessageSource messageSource = SpringUtils.getBean(MessageSource.class);
            for(Long userId : sendMessageMap.keySet()){
                System.out.println("推送对象：" + userId);
                List<ProjectInfoVOForSendMessage> newMessageList = sendMessageMap.get(userId);
                Message message = new Message();
                Object[] args = new String[3];
                args[0] = newMessageList.size() + "";
                args[1] = configValue;
                String projectNos = newMessageList.stream().map(ProjectInfoVOForSendMessage::getProjectNo).collect(Collectors.joining(","));
                System.out.println("项目：" + projectNos);
                args[2] = projectNos;

                String messageContent = messageSource.getMessage("message.reminderNotFollowingProject", args, new Locale("zh","CN"));
                String messageContentUS = messageSource.getMessage("message.reminderNotFollowingProject", args,new Locale("en","US"));
                String messageContentRU = messageSource.getMessage("message.reminderNotFollowingProject", args,new Locale("ru","RU"));
                String messageContentES = messageSource.getMessage("message.reminderNotFollowingProject", args,new Locale("es","ES"));

//                System.out.println("messageContent：" + messageContent);
//                System.out.println("messageContentUS：" + messageContentUS);
//                System.out.println("messageContentRU：" + messageContentRU);
//                System.out.println("messageContentES：" + messageContentES);
                message.setMessageType(MessageTypeEnum.PROJECT_UN_FOLLOW.getValue());
                message.setMessageContent(messageContent);
                message.setMessageContentUS(messageContentUS);
                message.setMessageContentRU(messageContentRU);
                message.setMessageContentES(messageContentES);
                message.setCreateBy("1");
                sseEmitterService.sendSaveMessage(Collections.singletonList(userId), message);
            }

        } catch (Exception e){
            log.info("项目跟进提醒定时任务异常："+e.getLocalizedMessage());
            throw (e);
        } finally {

        }

        System.out.println("项目跟进提醒定时任务结束！");


    }

    public void saveIntoMap(Map<Long, List<ProjectInfoVOForSendMessage>> sendMessageMap,List<Long> targetUserId,TcProject project){
        ProjectInfoVOForSendMessage projectInfo = new ProjectInfoVOForSendMessage();
        projectInfo.setProjectId(project.getProjectId());
        projectInfo.setProjectNo(project.getProjectNo());
        projectInfo.setProjectName(project.getProjectName());
        for(int i=0;i<targetUserId.size();i++){
            if(sendMessageMap.containsKey(targetUserId.get(i))){
                List<ProjectInfoVOForSendMessage> oldMessageList = sendMessageMap.get(targetUserId.get(i));
                oldMessageList.add(projectInfo);
                sendMessageMap.put(targetUserId.get(i), oldMessageList);
            }else{
                List<ProjectInfoVOForSendMessage> newMessageList = new ArrayList<ProjectInfoVOForSendMessage>();
                newMessageList.add(projectInfo);
                sendMessageMap.put(targetUserId.get(i), newMessageList);
            }
        }
    }


    /**
     * 培训状态更新 定时任务
     *
     * @author zhouy
     */
    public void updateTrainStatus() {
        ttTrainService.updateTrainStatus();
    }


    public void test(){
        commonService.test();
    }

    /**
     * 决定日期提醒功能 PROJECT_DEAL_DAY
     */
    public void projectDealAlarm(){
        //决定日期提醒功能
        // 超过【客户决定日期】这个日期时，提醒项目负责人【您好，您负责的项目:【xxxx,xxxxx】已过客户决定日期，请确认进度】
        Date now = new Date();
        log.info("决定日期提醒功能开始！");
        // 抽出所有需要提醒的项目(客户决定日期小于今天的)
        List<TcProject> projects = new ArrayList<TcProject>();
        projects = tcProjectService.selectProjectListJDRQ();

        if(ObjectUtils.isEmpty(projects)){
            return;
        }
        //处理owner，同负责人的放在一起
        Map<Long,List<TcProject>> proMap = projects.stream().collect
                (Collectors.groupingBy(it ->
                        it.getOwner()));


        //  发站内信
        MessageSource messageSource = SpringUtils.getBean(MessageSource.class);
        for(Long ownId : proMap.keySet()){
            System.out.println("推送对象：" + ownId);
            List<TcProject> projectList = proMap.get(ownId);
            Message message = new Message();
            Object[] args = new String[1];
            String projectNos = projectList.stream().map(TcProject::getProjectNo).collect(Collectors.joining(","));
            System.out.println("项目：" + projectNos);
            args[0] = projectNos;

            String messageContent = messageSource.getMessage("message.projectDealDay", args, new Locale("zh","CN"));
            String messageContentUS = messageSource.getMessage("message.projectDealDay", args,new Locale("en","US"));
            String messageContentRU = messageSource.getMessage("message.projectDealDay", args,new Locale("ru","RU"));
            String messageContentES = messageSource.getMessage("message.projectDealDay", args,new Locale("es","ES"));

            message.setMessageType(MessageTypeEnum.PROJECT_DEAL_DAY.getValue());
            message.setMessageContent(messageContent);
            message.setMessageContentUS(messageContentUS);
            message.setMessageContentRU(messageContentRU);
            message.setMessageContentES(messageContentES);
            message.setCreateBy("1");
            sseEmitterService.sendSaveMessage(Collections.singletonList(ownId), message);
        }


    }

    /**
     * 	签约到期提醒功能 AGENT_CONTRACT_DAY
     */
    public void agentContractAlarm(){
        // 获取系统参数（到期期限）
        String configValueMin = sysConfigService.selectConfigByKey("agent.contract.alarm_min");
        String configValueMid = sysConfigService.selectConfigByKey("agent.contract.alarm_mid");
        String configValueMax = sysConfigService.selectConfigByKey("agent.contract.alarm_max");


        //签约到期提醒功能  代理商签约到期日期前30天，发送提醒到代理商上级销售。【您好，您负责的代理商【xx,xx,xx】签约即将到期，请确认】

        log.info("签约到期提醒功能开始！");
        // 抽出所有快要到期的代理商
        List<TbAgent> agents = new ArrayList<TbAgent>();
        agents = tbAgentMapper.selectAgentDealLine(Integer.parseInt(configValueMin));

        agents.addAll(tbAgentMapper.selectAgentDealLine(Integer.parseInt(configValueMid)));

        agents.addAll(tbAgentMapper.selectAgentDealLine(Integer.parseInt(configValueMax)));
        if(ObjectUtils.isEmpty(agents)){
            return;
        }
        //处理owner，同上级销售的放在一起
        Map<Long,List<TbAgent>> ageMap = agents.stream().collect
                (Collectors.groupingBy(it ->
                        it.getParentSalerId()));

        MessageSource messageSource = SpringUtils.getBean(MessageSource.class);
        for(Long salerId : ageMap.keySet()){
            System.out.println("推送对象：" + salerId);
            List<TbAgent> agentList = ageMap.get(salerId);
            Message messageA = new Message();
            Object[] argsA = new String[2];
            String projectNos = agentList.stream().map(TbAgent::getAgentNo).collect(Collectors.joining(","));
            System.out.println("代理商：" + projectNos);
            argsA[0] = projectNos;
            TbAgent agent = agentList.get(0);
            argsA[1] = agent.getConfigValue()+"";
            String messageContentA = messageSource.getMessage("message.agentContractDay", argsA, new Locale("zh","CN"));
            String messageContentUSA = messageSource.getMessage("message.agentContractDay", argsA,new Locale("en","US"));
            String messageContentRUA = messageSource.getMessage("message.agentContractDay", argsA,new Locale("ru","RU"));
            String messageContentESA = messageSource.getMessage("message.agentContractDay", argsA,new Locale("es","ES"));

            messageA.setMessageType(MessageTypeEnum.AGENT_CONTRACT_DAY.getValue());
            messageA.setMessageContent(messageContentA);
            messageA.setMessageContentUS(messageContentUSA);
            messageA.setMessageContentRU(messageContentRUA);
            messageA.setMessageContentES(messageContentESA);
            messageA.setCreateBy("1");
            sseEmitterService.sendSaveMessage(Collections.singletonList(salerId), messageA);
        }
    }
}
