package com.jwipc.job.handler;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Lists;
import com.jwipc.finance.model.po.DeductionPO;
import com.jwipc.finance.service.IDeductionService;
import com.jwipc.job.logic.impl.EmailSendLogicLogicImpl;
import com.jwipc.job.prop.JobProp;
import com.jwipc.spe.model.po.AppraiseRectifiedNoticePO;
import com.jwipc.spe.model.po.QmAuditManagePO;
import com.jwipc.spe.model.po.QmNoticeOrderPO;
import com.jwipc.spe.service.IQmAuditManageService;
import com.jwipc.spe.service.IQmNoticeOrderService;
import com.jwipc.spe.service.ISupAppraiseRectifiedNoticeService;
import com.jwipc.supplier.entity.Supplier;
import com.jwipc.supplier.entity.SupplierContacts;
import com.jwipc.supplier.service.ISupplierContactsService;
import com.jwipc.supplier.service.ISupplierService;
import com.jwipc.sys.model.po.SupplierEmailPO;
import com.jwipc.sys.service.ISupplierEmailService;
import com.jwipc.util.DateUtils;
import lombok.extern.slf4j.Slf4j;
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 javax.annotation.Resource;
import java.util.Calendar;
import java.util.*;

/**
 * 稽核整改、质量整改、扣款单确认处理、绩效整改4个业务场景,每周一发送提醒邮件给供应商相应人。
 */
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
@Slf4j
@Component
public class SupplierQualityNoticeEmailJob extends QuartzJobBean implements InterruptableJob {

    @Autowired
    private IQmAuditManageService qmAuditManageService;

    @Autowired
    private EmailSendLogicLogicImpl emailSendLogicLogic;

    @Autowired
    private ISupplierEmailService supplierEmailService;

    @Autowired
    private ISupplierService supplierService;

    @Autowired
    private IQmNoticeOrderService qmNoticeOrderService;

    @Autowired
    private IDeductionService deductionService;

    @Autowired
    private ISupplierContactsService supplierContactsService;

    @Autowired
    private ISupAppraiseRectifiedNoticeService supAppraiseRectifiedNoticeService;
    @Resource
    private JobProp jobProp;


    @Override
    public void interrupt() throws UnableToInterruptJobException {

    }

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        log.info("查询待供应商处理大于或等于5天以上的供应商处理的稽核整改单任务开始");
        List<QmAuditManagePO> qmAuditManagePOS = qmAuditManageService.findNoticeQmAuditManageList();
        Map emailMap  = new HashMap<>();
        if (CollUtil.isNotEmpty(qmAuditManagePOS)) {
            try {
                for (QmAuditManagePO qmAuditManagePO : qmAuditManagePOS) {
                    List<String> emailList = initEmailList(emailMap, qmAuditManagePO.getSupplierCode());
                    if (null !=  emailList && emailList.size() > 0) {
                        for (String email : emailList) {
                            Map<String, Object> params = new HashMap<>();
                            emailSendLogicLogic.syncSend(email,"稽核整改确认预警","JW_POST_146",params,1L,null);
                        }
                    }
                }
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }
        log.info("处理待供应商处理大于或等于5天以上的供应商处理的稽核整改单任务结束");
        log.info("=================\n查询待供应商处理大于或等于5天以上的供应商处理的质量整改单任务开始");
        List<QmNoticeOrderPO> qmNoticeOrderPOS = qmNoticeOrderService.selectQmNoticeOrderWarnList();
        if (CollUtil.isNotEmpty(qmNoticeOrderPOS)) {
            try {
                for (QmNoticeOrderPO qmNoticeOrderPO : qmNoticeOrderPOS) {
                    List<String> emailList = initEmailList(emailMap, qmNoticeOrderPO.getSupplierCode());
                    if (null !=  emailList && emailList.size() > 0) {
                        for (String email : emailList) {
                            Map<String, Object> params = new HashMap<>();
                            emailSendLogicLogic.syncSend(email,"质量整改确认预警","JW_POST_145",params,1L,null);
                        }
                    }
                }
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }
        log.info("处理待供应商处理大于或等于5天以上的供应商处理的质量整改单任务结束");
        log.info("=================\n查询待供应商处理大于或等于5天以上的供应商处理的扣款单确认任务开始");
        List<DeductionPO> deductionPOS = deductionService.findDeductionNoticeList();
        if (CollUtil.isNotEmpty(deductionPOS)) {
            try {
                for (DeductionPO deductionPO : deductionPOS) {
                    List<String> emailList = initEmailList(emailMap, deductionPO.getSupplierCode());
                    if (null !=  emailList && emailList.size() > 0) {
                        for (String email : emailList) {
                            Map<String, Object> params = new HashMap<>();
                            emailSendLogicLogic.syncSend(email,"扣款单确认预警","JW_POST_147",params,1L,null);
                        }
                    }
                }
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }
        log.info("处理待供应商处理大于或等于5天以上的供应商处理的扣款单确认任务结束");
        log.info("=================\n查询待供应商处理大于或等于5天以上的供应商处理的绩效整改任务开始");
        List<AppraiseRectifiedNoticePO> appraiseRectifiedNoticePOS = supAppraiseRectifiedNoticeService.findSupAppraiseRectifiedNoticeList();
        if (CollUtil.isNotEmpty(appraiseRectifiedNoticePOS)) {
            try {
                for (AppraiseRectifiedNoticePO appraiseRectifiedNoticePO : appraiseRectifiedNoticePOS) {
                    List<String> emailList = initEmailList(emailMap, appraiseRectifiedNoticePO.getSupplierCode());
                    if (null !=  emailList && emailList.size() > 0) {
                        for (String email : emailList) {
                            Map<String, Object> params = new HashMap<>();
                            Calendar cl = Calendar.getInstance();
                            params.put("year", DateUtils.formatYYYYMMDDDash(appraiseRectifiedNoticePO.getCreateTime()).split("-")[0]);
                            params.put("month",DateUtils.formatYYYYMMDDDash(appraiseRectifiedNoticePO.getCreateTime()).split("-")[1]);
                            emailSendLogicLogic.syncSend(email,"绩效整改确认预警","JW_POST_148",params,1L,null);
                        }
                    }
                }
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }
        log.info("处理待供应商处理大于或等于5天以上的供应商处理的绩效整改任务结束");
    }

    private List<String> initEmailList(Map emailMap, String supplierCode) {
        List<String> emailList;
        if (emailMap.keySet().contains(supplierCode)) {
            emailList = (List<String>) emailMap.get(supplierCode);
        } else {
            emailList = Lists.newArrayList();
            //优先取供应商邮箱配置中邮箱类型是“外部”或“内部”的邮箱 邓京术 2024-12-09
            List<SupplierEmailPO> supplierEmailPOS = supplierEmailService.selectAllUser(supplierCode);
            if (CollUtil.isNotEmpty(supplierEmailPOS)) {
                emailList.add(supplierEmailPOS.get(0).getEmail());
                emailMap.put(supplierCode, emailList);
            } else {
                final Supplier supplier = supplierService.getOne(
                        new LambdaQueryWrapper<Supplier>().eq(Supplier::getSupplierCode, supplierCode));
                if (Objects.nonNull(supplier)) {
                    final LambdaQueryWrapper<SupplierContacts> queryWrapper = new LambdaQueryWrapper<SupplierContacts>().eq(
                            SupplierContacts::getSupplierId, supplier.getId());
                    //查询供应商是品质经理、品保联系人 的邮箱
                    queryWrapper.and(wrapper -> wrapper.eq(SupplierContacts::getContactsType, "1").or().eq(SupplierContacts::getContactsType, "2"));
                    List<SupplierContacts> supplierContacts = supplierContactsService.list(queryWrapper);
                    if (CollUtil.isNotEmpty(supplierContacts)) {
                        supplierContacts.stream().forEach(
                            item -> {
                                if (StringUtils.isNotEmpty(item.getEmail())) {
                                    emailList.add(item.getEmail());
                                }
                            }
                        );
                    }
                }
                emailMap.put(supplierCode, emailList);
            }
        }
        return emailList;
    }

}
