package com.storlead.message.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.ttl.TtlRunnable;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.storlead.framework.common.util.HtmlUtils;
import com.storlead.framework.common.util.encryptor.AccessKeyEncryptor;
import com.storlead.framework.util.LoginUserUtil;
import com.storlead.framework.mybatis.service.impl.MyBaseServiceImpl;
import com.storlead.framework.common.thread.ThreadPoolUtil;
import com.storlead.message.pojo.entity.MessageTemplateEventDetailEntity;
import com.storlead.message.mapper.MessageTemplateEventDetailMapper;
import com.storlead.message.pojo.entity.MessageTemplateEventGroupEntity;
import com.storlead.message.service.InsideMessageRecordService;
import com.storlead.message.service.MessageTemplateEventDetailService;
import com.storlead.message.service.UserMessageNoticeConfigService;
import com.storlead.message.service.WechatMessageService;
import com.storlead.mail.pojo.entity.SmtpPopSettingsEntity;
import com.storlead.mail.pojo.SendMailDTO;
import com.storlead.mail.service.EmailsService;
import com.storlead.mail.service.SmtpPopSettingsService;
import com.storlead.user.pojo.entity.DeptEntity;
import com.storlead.user.pojo.entity.UserEntity;
import com.storlead.user.service.IDepartService;
import com.storlead.user.service.IUserService;
import javax.annotation.Resource;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 消息模板 服务实现类
 * </p>
 *
 * @author chenkq
 * @since 2024-04-19
 */
@Log4j2
@Service
public class MessageTemplateEventDetailServiceImpl extends MyBaseServiceImpl<MessageTemplateEventDetailMapper, MessageTemplateEventDetailEntity> implements MessageTemplateEventDetailService {

    @Value("${domainname}")
    private  String domainname;

    @Resource
    private InsideMessageRecordService insideMessageRecordService;

    @Resource
    private SmtpPopSettingsService smtpPopSettingsService;

    @Resource
    private EmailsService emailsService;

    @Resource
    private WechatMessageService  wechatMessageService;

    @Resource
    private IUserService userService;

    @Resource
    private IDepartService departService;

    @Resource
    private UserMessageNoticeConfigService userMessageNoticeConfigService;


    @Override
    public void asynSendMessage(MessageTemplateEventGroupEntity eventGroup, Map messageMap) {
        asynSendMessage(eventGroup,messageMap,"site","wecom","sms","mail");
    }
    @Override
    public void asynSendMessage(MessageTemplateEventGroupEntity eventGroup, Map messageMap, String... args) {
        asynSendMessage(eventGroup,messageMap,null,args);
    }

    @Override
    public void asynSendMessage(MessageTemplateEventGroupEntity eventGroup, Map messageMap,Set<Long> toUserIds,String... rmindArgs) {

        String domain = this.domainname;
        Long senderUserId = LoginUserUtil.getCurrentUserId();
        if (Objects.isNull(senderUserId)) {
            senderUserId = 1L;
        }
        Set<Long> receiverUserIds = new HashSet<>();
        if (!CollectionUtils.isEmpty(toUserIds)) {
            receiverUserIds.addAll(toUserIds);
        }
       log.error("asynSendWechatMessage - senderUserId1 ----------- " +LoginUserUtil.getCurrentUserId());



        // 当前用户
        // 创建人 createBy
        // 归属人 ownerBy
        // 部门负责人 deptManagerId
        // 部门负责人 deptManagerId
        String noticeAppCode = eventGroup.getNoticeAppCode();
        log.error("asynSendWechatMessage - getNoticeAppCode ----------- " +noticeAppCode);

        String receiverKey =  eventGroup.getReceiverKey();
        if (StrUtil.isNotBlank(receiverKey)) {
            List<String> receiverls = Arrays.asList(receiverKey.split(","));
            //  deptManagerId,ownerBy,createBy
            // 创建人、归属人、部门负责人
            if (receiverls.contains("deptManagerId")) {
                if (messageMap.containsKey("ownerBy")) {
                    Long ownerBy = (Long) messageMap.get("ownerBy");
                    Long deptManagerId =  getDeptManagerIdByUser(ownerBy);
                    if (Objects.nonNull(deptManagerId) && !deptManagerId.equals(ownerBy)) {
                        receiverUserIds.add(deptManagerId);
                    }
                }
            }
            else if (!CollectionUtils.isEmpty(receiverls)) {
                for (String receiverkey : receiverls) {
                    if (messageMap.containsKey(receiverkey)) {
                        Object receiver = messageMap.get(receiverkey);
                        if (Objects.nonNull(receiver)) {
                            if (receiver instanceof String) {
                                receiverUserIds.addAll(Arrays.asList(receiver.toString().split(",")).stream().map(Long::parseLong).collect(Collectors.toSet()));
                            } else if (receiver instanceof Long) {
                                receiverUserIds.add((Long) receiver);
                            }
                        }
                    }
                }
            }
        }
        if (Objects.nonNull(senderUserId) && !CollectionUtils.isEmpty(receiverUserIds) && !receiverUserIds.equals(Set.of(1L))) {
            receiverUserIds.remove(senderUserId);
        }
        if (CollectionUtils.isEmpty(receiverUserIds)) {
            return;
        }
        Long finalSenderUserId = senderUserId;
        MessageTemplateEventGroupEntity newEventGroup = new MessageTemplateEventGroupEntity();
        BeanUtils.copyProperties(eventGroup,newEventGroup);
        Runnable ttlRunnable = TtlRunnable.get(new Runnable() {
            @Override
            public void run() {

                List<String> rmindTypes =  Arrays.asList(rmindArgs);
                List<MessageTemplateEventDetailEntity> eventDetaills = list(new LambdaQueryWrapper<MessageTemplateEventDetailEntity>().eq(MessageTemplateEventDetailEntity::getTemplateEventId,eventGroup.getId()));

                if (CollectionUtils.isEmpty(receiverUserIds)) {
                    return;
                }
                for (MessageTemplateEventDetailEntity eventDetail : eventDetaills) {
                    /**
                     * 站内
                     */
                    if (eventDetail.getTemplateDetailType().equals("site")  && eventDetail.getEnabled() && rmindTypes.contains("site")) {
                        Set<Long> toUserIds =  userMessageNoticeConfigService.checkUserNoticeConfig(receiverUserIds,newEventGroup.getId(),"site");
                        insideMessageRecordService.sendInsideMessage(newEventGroup,eventDetail,messageMap,toUserIds, eventDetail.getCallbackUrl(), finalSenderUserId);
                    }
                    /**
                     * 企业微信
                     */
                    if (eventDetail.getTemplateDetailType().equals("wecom") && eventDetail.getEnabled() && rmindTypes.contains("wecom")) {
                        Set<Long> toUserIds =  userMessageNoticeConfigService.checkUserNoticeConfig(receiverUserIds,newEventGroup.getId(),"wecom");
                        if (StrUtil.isNotBlank(noticeAppCode)) {
                            wechatMessageService.sendWechatMessage(eventDetail,messageMap,toUserIds,eventDetail.getCallbackUrl(),noticeAppCode);
                        } else {
                            wechatMessageService.sendWechatMessage(eventDetail,messageMap,toUserIds,eventDetail.getCallbackUrl());
                        }
                    }
                    /**
                     * 短信
                     */
                    if (eventDetail.getTemplateDetailType().equals("sms")  && eventDetail.getEnabled() && rmindTypes.contains("sms")) {

                    }
                    /**
                     * 邮件
                     */
                    if (eventDetail.getTemplateDetailType().equals("mail")  && eventDetail.getEnabled() && rmindTypes.contains("mail")) {
                        Set<Long> toUserIds =  userMessageNoticeConfigService.checkUserNoticeConfig(receiverUserIds,newEventGroup.getId(),"mail");
                        if (CollectionUtils.isEmpty(toUserIds)) {
                            continue;
                        }
                        SmtpPopSettingsEntity sendSmtpPops = smtpPopSettingsService.getSystemSmtpPop(1L);
                        if (Objects.isNull(sendSmtpPops)) {
                            continue;
                        }
                        List<SmtpPopSettingsEntity> receiverSmtpPops = smtpPopSettingsService.getDefaultSmtpPopls(receiverUserIds);
                        if (CollectionUtils.isEmpty(receiverSmtpPops)) {
                            continue;
                        }
                        AccessKeyEncryptor accessKeyEncryptor = AccessKeyEncryptor.getAccessKeyEncryptor("");
                        String pass = accessKeyEncryptor.decrypt(sendSmtpPops.getEmailPassword());
                        sendSmtpPops.setEmailPassword(pass);

                        MessageTemplateEventDetailEntity templateEntity = eventDetail;
                        String title = templateEntity.getMessageTitle();
                        title = title.replace("<br>","\n");
                        String content = templateEntity.getMessageCentent();

                        Iterator <Map.Entry< Integer, String >> iterator = messageMap.entrySet().iterator();
                        while (iterator.hasNext()) {
                            Map.Entry< Integer, String > entry = iterator.next();
                            String value =  HtmlUtils.userContent(entry.getValue());
                            content = content.replace("${"+entry.getKey()+"}$",value);
                        }
                        content = content.replace("<br>","\n");
                        String router = domain +""+ (StrUtil.isNotBlank(templateEntity.getCallbackUrl()) ? templateEntity.getCallbackUrl() : messageMap.get("callbackUrl"));
                        Object id = Objects.nonNull(messageMap) ? messageMap.get("id") : null;
                        Object jump = Objects.nonNull(messageMap) ? messageMap.get("jump") : null;
                        if (StrUtil.isNotBlank(router)) {
                            if (Objects.nonNull(id)) {
                                router = router.replace("${id}$",id.toString());
                            } else {
                                router = router.replace("${id}$","");
                            }
                            if (Objects.nonNull(jump)) {
                                router = router.replace("${jump}$",jump.toString());
                            } else {
                                router = router.replace("${jump}$","");
                            }
                        }
                        List<String> recipientls = receiverSmtpPops.stream().map(SmtpPopSettingsEntity::getEmailAddress).collect(Collectors.toList());
                        SendMailDTO dto = new SendMailDTO();
                        dto.setSubject(title);
                        String routers = "</p><p><a href='"+router+"'>查看</a></p>";
                        dto.setContent(content+""+routers);
                        dto.setRecipientls(recipientls);
                        emailsService.sendEmail(dto,sendSmtpPops);
                    }
                }
            }
        });
        ThreadPoolUtil.execute(ttlRunnable);
    }

    /**
     * 根据用户id 获取用户部门负责人
     */
    public Long getDeptManagerIdByUser(Long userId) {
        UserEntity user =  userService.getById(userId);
        if (Objects.nonNull(user) && user.getDeptId() != null) {
           DeptEntity dept = departService.getById(user.getDeptId());
           if (Objects.nonNull(dept)) {
               return dept.getManagerId();
           }
        }
        return null;
    }
}
