package com.ruoyi.common.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.utils.email.BaseEmailEntity;
import com.ruoyi.common.utils.email.EmailUtil;
import com.ruoyi.project.business.domain.TpParaLibrary;
import com.ruoyi.project.business.domain.bo.quotation.ElevatorParamAddBO;
import com.ruoyi.project.business.domain.dto.QuotationDTO;
import com.ruoyi.project.business.enums.JEPSplitEnum;
import com.ruoyi.project.business.enums.ParamTypeEnum;
import com.ruoyi.project.business.enums.QuotationMsgEnum;
import com.ruoyi.project.business.service.ITpParaLibraryService;
import com.ruoyi.project.common.domain.Message;
import com.ruoyi.project.common.service.ISseEmitterService;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.service.ISysUserService;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

@Slf4j
public class QuotationUtil {

    public static final String QUOTATION_DATA = "quotationData";

    public static final String SITE_NAME = "site.name";

    public static final String ADMIN = "1";

    public static void initMap(List<ElevatorParamAddBO> paramList) {

        Map<String, String> paramCodeValueMap = new HashMap<>();
        Map<String, Object> paramCodeCalculateValueMap = new HashMap<>();
        Map<String, String> paramCodeInputTypeMap = new HashMap<>();
        Map<String, String> paramCodeLabelMap = new HashMap<>();

        List<String> paramCodeList = new ArrayList<>();
        paramList.forEach(item -> {
            if (!item.getParamType().equals(ParamTypeEnum.BAR.getCode())) {
                paramCodeCalculateValueMap.put(JEPSplitEnum.PARAM_SPLIT_FLAG.getFuncKey() + item.getParaCode()
                        + JEPSplitEnum.PARAM_SPLIT_FLAG.getFuncKey(),
                    item.getParaValue());
                paramCodeInputTypeMap.put(JEPSplitEnum.PARAM_SPLIT_FLAG.getFuncKey() + item.getParaCode()
                    + JEPSplitEnum.PARAM_SPLIT_FLAG.getFuncKey(), item.getParamType());
                paramCodeValueMap.put(item.getParaCode(), item.getParaValue());
            }
            paramCodeList.add(item.getParaCode());
        });

        if (CollUtil.isNotEmpty(paramCodeList)) {
            ITpParaLibraryService tpParaLibraryService = SpringUtil.getBean(ITpParaLibraryService.class);
            List<TpParaLibrary> tpParaLibraryList = tpParaLibraryService.list(Wrappers.<TpParaLibrary>lambdaQuery()
                .in(TpParaLibrary::getParaCode, paramCodeList)
            );
            paramCodeLabelMap = tpParaLibraryList.stream()
                .peek(item -> {
                    paramCodeInputTypeMap.put(JEPSplitEnum.PARAM_SPLIT_FLAG.getFuncKey() + item.getParaCode()
                        + JEPSplitEnum.PARAM_SPLIT_FLAG.getFuncKey(), item.getInputType());
                })
                .collect(Collectors.toMap(TpParaLibrary::getParaCode, TpParaLibrary::getParaName, (a, b) -> a));
        }

        QuotationDTO quotationDTO = new QuotationDTO();
        quotationDTO.setParamCodeValueMap(paramCodeValueMap);
        quotationDTO.setParamCodeCalculateValueMap(paramCodeCalculateValueMap);
        quotationDTO.setParamCodeInputTypeMap(paramCodeInputTypeMap);
        quotationDTO.setParamCodeLabelMap(paramCodeLabelMap);
        Objects.requireNonNull(RequestContextHolder.getRequestAttributes())
            .setAttribute(QUOTATION_DATA, quotationDTO, RequestAttributes.SCOPE_REQUEST);
    }

    public static QuotationDTO getQuotationData() {
        Object attribute = Objects.requireNonNull(RequestContextHolder.getRequestAttributes())
            .getAttribute(QUOTATION_DATA, RequestAttributes.SCOPE_REQUEST);
        if (Objects.nonNull(attribute) && attribute instanceof QuotationDTO) {
            return (QuotationDTO)attribute;
        }
        return new QuotationDTO();
    }

    public static void sendMsgAsync(QuotationMsgEnum msgEnum, List<Long> userIdList, String quotationNo) {
        // log.info("准备发送异步通知");
        ThreadUtil.execAsync(() -> sendMsg(msgEnum, userIdList, quotationNo));
    }

    public static void sendMsg(QuotationMsgEnum msgEnum, List<Long> userIdList, String quotationNo) {
        // 发送站内信
        Message message = new Message();
        message.setMessageType(msgEnum.getMsgType());
        message.setMessageContent(MessageUtils.getMessage(msgEnum.getMsg(), 0, quotationNo));
        message.setMessageContentUS(MessageUtils.getMessage(msgEnum.getMsg(), 1, quotationNo));
        message.setMessageContentRU(MessageUtils.getMessage(msgEnum.getMsg(), 2, quotationNo));
        message.setMessageContentES(MessageUtils.getMessage(msgEnum.getMsg(), 3, quotationNo));
        message.setCreateBy(ADMIN);
        ISseEmitterService sseEmitterService = SpringUtil.getBean(ISseEmitterService.class);
        sseEmitterService.sendSaveMessage(userIdList, message);
        // 发送邮件
        ISysUserService userService = SpringUtil.getBean(ISysUserService.class);
        List<SysUser> list = userService.list(Wrappers.<SysUser>lambdaQuery().in(SysUser::getUserId, userIdList));
        // 测试邮件发送
        // emailList = Collections.singletonList("jinyw@golden-tech.com.cn");
        BaseEmailEntity email = BaseEmailEntity.builder()
            .to(list.stream().map(SysUser::getEmail).toArray(String[]::new))
            .subject(MessageUtils.getMessage(SITE_NAME, 0))
            .text(MessageUtils.getMessage(msgEnum.getMsg(), 0, quotationNo))
            .build();
        EmailUtil emailUtil = SpringUtil.getBean(EmailUtil.class);
        try {
            emailUtil.sendSimpleMail(email);
        } catch (Exception e) {
            log.error("邮件通知异常", e);
        }
        List<String> nickNameList = list
            .stream()
            .map(t -> t.getNickName() + "||" + t.getEmail())
            .collect(Collectors.toList());
        log.info("++++++++++报价编号 [{}] 邮件通知 [{}]", quotationNo, StringUtils.join(nickNameList, "],["));
    }

}
