package com.ruoyi.framework.task;

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.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.mapper.TbAgentMapper;
import com.ruoyi.project.business.mapper.TcFollowMapper;
import com.ruoyi.project.business.service.ITcProjectService;
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.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;

    /**
     * 项目跟进提醒定时任务
     */
    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.selectTbAgentByAgentId(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.selectTbAgentByAgentId(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);
            }
        }
    }

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