package com.jwipc.job.handler;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jwipc.job.logic.impl.EmailSendLogicLogicImpl;
import com.jwipc.supplier.entity.SupplierInvitaion;
import com.jwipc.supplier.model.po.SupplierQualificationPO;
import com.jwipc.supplier.model.query.SupplierQualificationQuery;
import com.jwipc.supplier.service.ISupplierInvitaionService;
import com.jwipc.supplier.service.ISupplierQualificationService;
import com.jwipc.sys.client.UserClient;
import com.jwipc.sys.client.dto.UserDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *     供应商资质附件有效期预警-查询列表，按照期限和到期日期：每日凌晨
 * （1）查询 供应商状态 = 【潜在、小批量、合格】的供应商记录，资质【有效截止时间】 有值的的资质附件记录；
 * （2）当前时间 - 资质有效截止时间 <= 30 天（系统参数配置 supplierPaperValidDeadInterval） 的记录；
 * </p>
 *
 * @author wcb
 * @version 1.0
 * @since JDK 17
 */
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
@Slf4j
@Component
public class SupplierQuaWarnEmailJob extends QuartzJobBean implements InterruptableJob {

    @Autowired
    private ISupplierQualificationService supplierQualificationService;
    @Autowired
    private EmailSendLogicLogicImpl emailSendLogicLogic;

    @Autowired
    private  ISupplierInvitaionService supplierInvitaionService;


    private UserClient userClient;



    @Override
    public void interrupt() throws UnableToInterruptJobException {

    }

    @Override
    protected void executeInternal(JobExecutionContext context) {
        SupplierQualificationQuery query = new SupplierQualificationQuery();
        List<SupplierQualificationPO> supplierMaterialDemoPOS = supplierQualificationService.selectWarnList(query);
        if (CollectionUtils.isNotEmpty(supplierMaterialDemoPOS)){
            //=============
            Map<Long, List<SupplierQualificationPO>> groupedBySupplierId = supplierMaterialDemoPOS.stream()
                    .collect(Collectors.groupingBy(SupplierQualificationPO::getSupplierId));

            groupedBySupplierId.forEach((supplierId, poList) -> {
                StringBuilder nameStringBuilder = new StringBuilder();
                StringBuilder dateStringBuilder = new StringBuilder();
                Map<String,Object> params = new HashMap<>();
                poList.forEach(po -> {
                    nameStringBuilder.append(po.getQualificationName());
                    nameStringBuilder.append(";");
                    nameStringBuilder.append(System.lineSeparator());
                    dateStringBuilder.append(po.getAvailableEndDate());
                    dateStringBuilder.append(";");
                    dateStringBuilder.append(System.lineSeparator());
                });
                params.put("names",nameStringBuilder.toString());
                params.put("publicDate",dateStringBuilder.toString());
                params.put("supplierName", poList.get(0).getSupplierName());
                if(StringUtils.isNotEmpty(poList.get(0).getEmail())){
                    emailSendLogicLogic.syncSend(poList.get(0).getEmail(),"供应商资质预警提醒:","JW_POST_020",params,1L,null);
                }
                final SupplierInvitaion one = supplierInvitaionService.getOne(
                        new LambdaQueryWrapper<>(SupplierInvitaion.class).eq(SupplierInvitaion::getSupplierId,
                                supplierId), false);
                if(ObjectUtil.isNotEmpty(one)){
                    final String recommender = one.getRecommender();
                    if(StringUtils.isNotEmpty(recommender)){
                        final UserDTO byAccount = userClient.getByAccount(recommender);
                        final String email = byAccount.getEmail();
                        emailSendLogicLogic.syncSend(email,"供应商资质预警提醒:","JW_POST_020",params,1L,null);
                    }
                }
                emailSendLogicLogic.syncSend("yepp@jwele.com.cn","供应商资质预警提醒:","JW_POST_020",params,1L,null);
            });


            //============= 2025-04-21注释修改
            //for (SupplierQualificationPO supplierQualificationPO : supplierMaterialDemoPOS) {
            //    if (StringUtils.isNotEmpty(supplierQualificationPO.getEmail())){
            //        Map<String,Object> params = new HashMap<>();
            //       params.put("names",supplierQualificationPO.getQualificationName());
            //        params.put("publicDate",supplierQualificationPO.getAvailableEndDate());
            //        emailSendLogicLogic.syncSend(supplierQualificationPO.getEmail(),"供应商资质预警提醒","JW_POST_020",params,1L,null);
            //   }
            //}
        }
        log.info("{}", supplierMaterialDemoPOS);
    }
}
