package com.jwipc.job.handler;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.jwipc.constant.FreezeConst;
import com.jwipc.constant.SysConfigKey;
import com.jwipc.job.logic.impl.EmailSendLogicLogicImpl;
import com.jwipc.supplier.constant.AuthenticationState;
import com.jwipc.supplier.entity.Supplier;
import com.jwipc.supplier.entity.SupplierInvitaion;
import com.jwipc.supplier.entity.SupplierPurchaseCategory;
import com.jwipc.supplier.service.ISupplierInvitaionService;
import com.jwipc.supplier.service.ISupplierPurchaseCategoryService;
import com.jwipc.supplier.service.ISupplierService;
import com.jwipc.sys.entity.SysConfig;
import com.jwipc.sys.entity.User;
import com.jwipc.sys.service.ISysConfigService;
import com.jwipc.sys.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;

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

/**
 * <p> </p>
 *
 * @author ZhangJie
 * @version 1.0
 * @since JDK 1.8
 */
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
@Slf4j
@Component
public class SmallbatchSupplierPushEmailJob extends QuartzJobBean implements InterruptableJob {
    @Autowired
    private ISupplierPurchaseCategoryService supplierPurchaseCategoryService;
    @Autowired
    private ISupplierService supplierService;
    @Autowired
    private EmailSendLogicLogicImpl emailSendLogicLogic;
    @Autowired
    private ISupplierInvitaionService supplierInvitaionService;
    @Autowired
    private IUserService userService;
    @Autowired
    private ISysConfigService sysConfigService;

    @Override
    public void interrupt() throws UnableToInterruptJobException {

    }

    @Override
    protected void executeInternal(JobExecutionContext context) {
        final List<SupplierPurchaseCategory> purchaseCategories = supplierPurchaseCategoryService.list(
                new LambdaQueryWrapper<SupplierPurchaseCategory>().le(SupplierPurchaseCategory::getEffectiveTime,
                                LocalDateTime.now().plusDays(30L))
                        .eq(SupplierPurchaseCategory::getIsFreeze, FreezeConst.NORMAL.getCode())
                        .eq(SupplierPurchaseCategory::getState, AuthenticationState.SMALL_BATCH.getState()));
        if (CollUtil.isNotEmpty(purchaseCategories)) {
            final Set<Long> supplierIds = purchaseCategories.stream().map(SupplierPurchaseCategory::getSupplierId)
                    .collect(Collectors.toSet());
            final List<Supplier> suppliers = supplierService.listByIds(supplierIds);
            final Map<Long, String> supplierCache = suppliers.stream()
                    .collect(Collectors.toMap(Supplier::getId, Supplier::getSupplierErpCode));
            final List<SupplierInvitaion> invitaions = supplierInvitaionService.list(
                    new LambdaQueryWrapper<>(SupplierInvitaion.class).in(SupplierInvitaion::getSupplierId,
                            supplierCache.keySet()));
            //获取邀请人的邮件，然后组装成 Map<supplierId,email>
            Map<Long, String> recommenderEmailsCache = Maps.newHashMap();
            if (CollUtil.isNotEmpty(invitaions)) {
                final Set<String> userCodes = invitaions.stream().filter(a -> StrUtil.isNotEmpty(a.getRecommender()))
                        .map(SupplierInvitaion::getRecommender).collect(
                                Collectors.toSet());
                if (CollUtil.isNotEmpty(userCodes)) {

                    final List<User> list = userService.list(
                                    new LambdaQueryWrapper<>(User.class).in(User::getAccountName, userCodes)).stream()
                            .filter(a -> StrUtil.isNotEmpty(a.getEmail())).toList();
                    if (CollUtil.isNotEmpty(list)) {
                        //需要做数据组装
                        final Map<Long, String> map = invitaions.stream().collect(
                                Collectors.toMap(SupplierInvitaion::getSupplierId, SupplierInvitaion::getRecommender));
                        final Map<String, String> userMap = list.stream()
                                .collect(Collectors.toMap(User::getAccountName, User::getEmail));
                        for (Long supplierId : map.keySet()) {
                            final String accountName = map.get(supplierId);
                            if (StrUtil.isNotEmpty(userMap.get(accountName))) {
                                recommenderEmailsCache.put(supplierId, userMap.get(accountName));
                            }
                        }

                    }
                }
            }

            for (Supplier supplier : suppliers) {
                Map<String, Object> params = new HashMap<>();
                params.put("supplierName", supplier.getSupplierName());
                params.put("supplierCode", supplier.getSupplierCode());
                //查询邮箱系统配置的邮箱
                final SysConfig config = sysConfigService.getOne(
                        new LambdaQueryWrapper<>(SysConfig.class).eq(SysConfig::getConfigKey,
                                SysConfigKey.MAIL_LIST_SUPPLIER_PRE_FREEZE.getCode()), false);
                final String email = recommenderEmailsCache.get(supplier.getId());
                Set<String> emails = Sets.newHashSet();
                if (StrUtil.isNotEmpty(email)) {
                    emails.add(email);
                }
                if (Objects.nonNull(config) && StrUtil.isNotEmpty(config.getConfigValue())) {
                    final List<String> split = StrUtil.split(config.getConfigValue(), StrUtil.COMMA);
                    emails.addAll(split);
                }
                if (CollUtil.isNotEmpty(emails)) {
                    emailSendLogicLogic.asynchSend(emails, null, "JW_POST_115",
                            params, 1L, null);
                }

            }
        }

    }
}
