package com.gree.mall.manager.logic.policy;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gree.mall.manager.bean.ExcelData;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.bean.policy.*;
import com.gree.mall.manager.commonmapper.PolicyCMapper;
import com.gree.mall.manager.constant.Constant;
import com.gree.mall.manager.enums.*;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.logic.common.CommonLogic;
import com.gree.mall.manager.plus.entity.*;
import com.gree.mall.manager.plus.service.*;
import com.gree.mall.manager.utils.RedisUtil;
import com.gree.mall.manager.utils.StringUtil;
import com.gree.mall.manager.utils.email.EmailUtilsNew;
import com.gree.mall.manager.utils.excel.ExcelUtils;
import com.gree.mall.manager.zfire.bean.ZfireParamBean;
import com.gree.mall.manager.zfire.util.FieldUtils;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j;
import org.apache.http.client.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.mail.MessagingException;
import javax.mail.Session;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Log4j
public class AgreementLogic {

    @Autowired
    PolicyCMapper policyCMapper;

    @Value("${spring.profiles.active}")
    private String active;


    @Value("${web.upload-path}")
    private String uploadUrl;


    @Autowired
    CommonLogic commonLogic;

    @Autowired
    AgreementService agreementService;

    @Autowired
    AgreementPolicyService agreementPolicyService;

    @Autowired
    PolicyService policyService;

    @Autowired
    MailboxService mailboxService;

    @Autowired
    MailboxSendRecordService mailboxSendRecordService;

    @Autowired
    MailboxReceiveService mailboxReceiveService;

    @Autowired
    MailboxSendRecordPolicyService mailboxSendRecordPolicyService;

    @Autowired
    PolicyOrderService policyOrderService;

    @Autowired
    WorkerPolicyService workerPolicyService;

    @Autowired
    WebsitUserService websitUserService;

    @Autowired
    UserService userService;

    @Autowired
    AdminWebsitService adminWebsitService;

    @Autowired
    SysDictCompanyService sysDictCompanyService;

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    LeConfigService leConfigService;

    @Autowired
    LeLetterService leLetterService;

    @Autowired
    LeLetterItemService leLetterItemService;


    public IPage<AgreementVo> list(Page page, ZfireParamBean zfireParam) {

        //获取当前登录企业id
        AdminUserCom adminUser = commonLogic.getAdminUser();

        List<String> adminCompanyIds = adminUser.getCompanyWechatIds();
        //1.组装查询条件
        zfireParam = FieldUtils.supplyParam(zfireParam, AgreementVo.class);

        IPage<AgreementVo> agreementVoIPage = policyCMapper.listAgreement(page, zfireParam, adminCompanyIds);
        return agreementVoIPage;
    }

    public AgreementDetail detail(String id) {

        Agreement agreement = agreementService.getById(id);

        AgreementDetail agreementDetail = BeanUtil.toBean(agreement, AgreementDetail.class);

        List<AgreementPolicy> agreementPolicies = agreementPolicyService.lambdaQuery().eq(AgreementPolicy::getAgreementId, agreement.getId()).list();


        List<String> aggre = agreementPolicies.stream().map(AgreementPolicy::getPolicyId).collect(Collectors.toList());


        List<Policy> policyList = policyService.lambdaQuery().in(Policy::getId, aggre).list();

        agreementDetail.setAgreementPolicies(agreementPolicies);
        agreementDetail.setPolicy(policyList);

        return agreementDetail;

    }

    @Transactional(rollbackFor = Exception.class)
    public void add(AgreementAddUp agreementAddUp) {
        AdminUserCom adminUser = commonLogic.getAdminUser();

        agreementAddUp.setCompanyWechatId(adminUser.getCompanyWechatId());
        agreementAddUp.setCompanyWechatName(adminUser.getCompanyName());
        agreementAddUp.insert();

        List<AgreementPolicy> agreementPolicies = new ArrayList<>();

        for (Policy policy : agreementAddUp.getPolicy()) {
            AgreementPolicy agreementPolicy = new AgreementPolicy();
            agreementPolicy.setPolicyId(policy.getId());
            agreementPolicy.setAgreementId(agreementAddUp.getId());

            agreementPolicies.add(agreementPolicy);
        }
        agreementPolicyService.saveBatch(agreementPolicies);
    }


    @Transactional(rollbackFor = Exception.class)
    public void update(AgreementAddUp agreementAddUp) {


        agreementAddUp.updateById();

        agreementPolicyService.lambdaUpdate().eq(AgreementPolicy::getAgreementId, agreementAddUp.getId()).remove();

        List<AgreementPolicy> agreementPolicies = new ArrayList<>();

        for (Policy policy : agreementAddUp.getPolicy()) {
            AgreementPolicy agreementPolicy = new AgreementPolicy();
            agreementPolicy.setPolicyId(policy.getId());
            agreementPolicy.setAgreementId(agreementAddUp.getId());

            agreementPolicies.add(agreementPolicy);
        }
        agreementPolicyService.saveBatch(agreementPolicies);
    }

    public MailboxAdd detailMailbox() {

        if (mailboxService.lambdaQuery().eq(Mailbox::getId, "1").count() < 1)
            return new MailboxAdd();

        Mailbox mailbox = mailboxService.getById("1");

        MailboxAdd mailboxAdd = BeanUtil.toBean(mailbox, MailboxAdd.class);

        List<MailboxReceive> list = mailboxReceiveService.lambdaQuery().eq(MailboxReceive::getMailboxId, "1").list();

        mailboxAdd.setMailboxReceives(list);

        return mailboxAdd;

    }

    public void addDetail(MailboxAdd mailbox) {
        if (mailboxService.lambdaQuery().eq(Mailbox::getId, "1").count() < 1) {
            mailbox.setId("1");
            mailbox.insert();
            return;
        }
        mailbox.setId("1");
        mailbox.updateById();

        mailboxReceiveService.lambdaUpdate().eq(MailboxReceive::getMailboxId, "1").remove();

        for (MailboxReceive mailboxReceive : mailbox.getMailboxReceives()) {

            mailboxReceive.setMailboxId("1");
        }

        mailboxReceiveService.saveBatch(mailbox.getMailboxReceives());

    }

    public IPage<MailBoxSendRecordVo> listMailBoxRecord(Page page, ZfireParamBean zfireParam) {
        //获取当前登录企业id
        AdminUserCom adminUser = commonLogic.getAdminUser();

        List<String> adminCompanyIds = adminUser.getCompanyWechatIds();
        //1.组装查询条件
        zfireParam = FieldUtils.supplyParam(zfireParam, MailBoxSendRecordVo.class);

        IPage<MailBoxSendRecordVo> policyVoIPage = policyCMapper.listMailBoxRecord(page, zfireParam, adminCompanyIds);
        return policyVoIPage;
    }

    public MailboxSendRecord detailRecord(String id) {
        MailboxSendRecord mailboxSendRecord = mailboxSendRecordService.getById(id);
        return mailboxSendRecord;
    }

    public IPage<MailboxSendRecordPolicyVo> listPolicy(Page page, ZfireParamBean zfireParam) {
        //获取当前登录企业id
        AdminUserCom adminUser = commonLogic.getAdminUser();

        List<String> adminCompanyIds = adminUser.getCompanyWechatIds();
        //1.组装查询条件
        zfireParam = FieldUtils.supplyParam(zfireParam, MailboxSendRecordPolicyVo.class);

        IPage<MailboxSendRecordPolicyVo> policyVoIPage = policyCMapper.listPolicy(page, zfireParam, adminCompanyIds);
        return policyVoIPage;
    }


    public void sendEmail(String sendBatch) throws IOException {
        MailboxSendRecord mailboxSendRecord = mailboxSendRecordService.getById(sendBatch);
        List<MailboxSendRecordPolicy> mailboxSendRecordPolicies = mailboxSendRecordPolicyService.lambdaQuery()
                .eq(MailboxSendRecordPolicy::getSendBatch, sendBatch).list();

        Mailbox mailbox = mailboxService.getById("1");

        List<MailboxReceive> mailboxReceives = mailboxReceiveService.lambdaQuery().eq(MailboxReceive::getMailboxId, "1").list();


        //发送邮箱
        EmailUtilsNew emailUtilsNew = new EmailUtilsNew(mailboxSendRecord.getSendMailbox(), mailbox.getSendPassword());


        if (mailboxSendRecord.getPolicyType().equals("AC")) {

            //发邮件
            try {
                MailboxSendRecord mailboxSendRecord1 = new MailboxSendRecord();
                mailboxSendRecord1.setId(mailboxSendRecord.getId());
                mailboxSendRecord1.setSendStatus("OK");
                mailboxSendRecord1.setSendTime(new Date());
                mailboxSendRecord1.updateById();

                this.sendEmailFile(mailboxSendRecordPolicies, mailboxSendRecord, mailbox,emailUtilsNew);

            } catch (Exception e) {
                e.printStackTrace();
                log.error("发送意外保险失败"+e.toString());
                MailboxSendRecord mailboxSendRecord1 = new MailboxSendRecord();
                mailboxSendRecord1.setId(mailboxSendRecord.getId());
                mailboxSendRecord1.setSendStatus("NO");
                mailboxSendRecord1.setSendTime(new Date());
                mailboxSendRecord1.updateById();
            }
        }

        if (mailboxSendRecord.getPolicyType().equals("EM")) {

            //发邮件
            try {
                MailboxSendRecord mailboxSendRecord1 = new MailboxSendRecord();
                mailboxSendRecord1.setId(mailboxSendRecord.getId());
                mailboxSendRecord1.setSendStatus("OK");
                mailboxSendRecord1.setSendTime(new Date());
                mailboxSendRecord1.updateById();
                this.sendEmailFileEm(mailboxSendRecordPolicies, mailboxSendRecord, mailbox,emailUtilsNew);

            } catch (Exception e) {
                e.printStackTrace();
                log.error("发送雇主保险失败"+e.toString());
                MailboxSendRecord mailboxSendRecord1 = new MailboxSendRecord();
                mailboxSendRecord1.setId(mailboxSendRecord.getId());
                mailboxSendRecord1.setSendStatus("NO");
                mailboxSendRecord1.setSendTime(new Date());
                mailboxSendRecord1.updateById();
            }
        }


        if (mailboxSendRecord.getPolicyType().equals("IN")) {

            //发邮件
            try {
                MailboxSendRecord mailboxSendRecord1 = new MailboxSendRecord();
                mailboxSendRecord1.setId(mailboxSendRecord.getId());
                mailboxSendRecord1.setSendStatus("OK");
                mailboxSendRecord1.setSendTime(new Date());
                mailboxSendRecord1.updateById();
                this.sendEmailFileIn(mailboxSendRecordPolicies, mailboxSendRecord, mailbox,emailUtilsNew);

            } catch (Exception e) {
                e.printStackTrace();
                log.error("发送工伤保险失败"+e.toString());
                MailboxSendRecord mailboxSendRecord1 = new MailboxSendRecord();
                mailboxSendRecord1.setId(mailboxSendRecord.getId());
                mailboxSendRecord1.setSendStatus("NO");
                mailboxSendRecord1.setSendTime(new Date());
                mailboxSendRecord1.updateById();
            }
        }


    }

    private void sendEmailFileIn(List<MailboxSendRecordPolicy> mailboxSendRecordPolicies, MailboxSendRecord mailboxSendRecord, Mailbox mailbox,EmailUtilsNew emailUtilsNew) throws IOException {
        String[] titles = new String[]{"序号", "网点编号", "网点名称", "服务人员编号", "服务人员名称", "联系电话", "身份证号码", "保单名称", "缴费金额",
                "生效日期", "截止日期", "所属一级网点编号", "所属一级网点编号", "代买单位"};
        List<List<Object>> rows = new ArrayList<>();
        for (int i = 0; i < mailboxSendRecordPolicies.size(); i++) {
            MailboxSendRecordPolicy record = mailboxSendRecordPolicies.get(i);
            List<Object> row = new ArrayList<>();
            row.add(i + 1);
            row.add(record.getWebsitId());
            row.add(record.getWebsitName());

            row.add(record.getPolicyNumber());
            row.add(record.getPolicyName());
            row.add(record.getPolicyMobile());
            row.add(record.getPolicyIdcard());
            rows.add(row);
        }
        // 获取资源文件存放路径，用于临时存放生成的excel文件
        String path = uploadUrl;
        if (active.equals("dev")) {
            path = Objects.requireNonNull(this.getClass().getClassLoader().getResource("")).getPath();
        }
        // 文件名：采用UUID，防止多线程同时生成导致的文件重名
        String filePath = String.format("%s%s.xlsx", path, mailboxSendRecord.getSendBatch() + "-工伤险");
        ExcelData excelData = new ExcelData();
        excelData.setTitles(Arrays.asList(titles));
        excelData.setRows(rows);
        ExcelUtils.createExcel(filePath, excelData);
        File excel = new File(filePath);

        //发送邮箱

        //分发邮件
        Session session = emailUtilsNew.loadMailSession();

        emailUtilsNew.send(session,mailboxSendRecord.getReceiveMailbox(), mailbox.getSendMailbox(), "工伤险-" + mailboxSendRecord.getSendBatch() + "-" + mailbox.getSendName(), "你好，以下是" + DateUtil.format(new Date(), "yyyy-MM-dd")
                    + mailbox.getSendName() + "保险人员名单详情见附件", filePath);


        //删除该文件
        excel.delete();
    }

    private void sendEmailFileEm(List<MailboxSendRecordPolicy> mailboxSendRecordPolicies, MailboxSendRecord mailboxSendRecord, Mailbox mailbox,EmailUtilsNew emailUtilsNew) throws IOException {

        String[] titles = new String[]{"序号", "网点编号", "网点名称", "保险类型", "被保险人姓名", "被保险人证件类型", "被保险人证件号码",
                "被替换人姓名", "被替换人证件类型", "被替换人证件号码"};
        List<List<Object>> rows = new ArrayList<>();
        for (int i = 0; i < mailboxSendRecordPolicies.size(); i++) {
            MailboxSendRecordPolicy record = mailboxSendRecordPolicies.get(i);
            List<Object> row = new ArrayList<>();
            row.add(i + 1);
            row.add(record.getWebsitId());
            row.add(record.getWebsitName());
            if (StringUtil.isEmpty(record.getReplaceName()))
                row.add("新增");
            else
                row.add("替换");
            row.add(record.getPolicyName());
            row.add("居民身份证");
            row.add(record.getPolicyIdcard());
            if (!StringUtil.isEmpty(record.getReplaceName())) {
                row.add(record.getReplaceName());
                row.add("居民身份证");
                row.add(record.getReplaceIdcard());
            }
            rows.add(row);
        }
        // 获取资源文件存放路径，用于临时存放生成的excel文件
        String path = "/tmp";
        if (active.equals("dev")) {
            path = Objects.requireNonNull(this.getClass().getClassLoader().getResource("")).getPath();
        }
        // 文件名：采用UUID，防止多线程同时生成导致的文件重名
        String filePath = String.format("%s%s.xlsx", path, mailboxSendRecord.getSendBatch() + "-雇主险");
        ExcelData excelData = new ExcelData();
        excelData.setTitles(Arrays.asList(titles));
        excelData.setRows(rows);
        ExcelUtils.createExcel(filePath, excelData);
        File excel = new File(filePath);


        //分发邮件
        Session session = emailUtilsNew.loadMailSession();

        emailUtilsNew.send(session,mailboxSendRecord.getReceiveMailbox(), mailbox.getSendMailbox(), "雇主险-" + mailboxSendRecord.getSendBatch() + "-" + mailbox.getSendName(), "你好，以下是" + DateUtil.format(new Date(), "yyyy-MM-dd")
                + mailbox.getSendName() + "保险人员名单详情见附件", filePath);


        //删除该文件
        excel.delete();
    }


    /**
     * 发送买保险名单的邮件
     *
     * @param mailboxSendRecordPolicies
     * @param mailboxSendRecord
     * @param mailbox
     */
    private void sendEmailFile(List<MailboxSendRecordPolicy> mailboxSendRecordPolicies, MailboxSendRecord mailboxSendRecord, Mailbox mailbox,EmailUtilsNew emailUtilsNew) throws IOException {

        String[] titles = new String[]{"序号", "投保人", "保单号", "网点编号", "网点名称", "保险类型", "被保险人姓名", "被保险人证件类型", "被保险人证件号码"};
        List<List<Object>> rows = new ArrayList<>();
        for (int i = 0; i < mailboxSendRecordPolicies.size(); i++) {
            MailboxSendRecordPolicy record = mailboxSendRecordPolicies.get(i);
            List<Object> row = new ArrayList<>();
            row.add(i + 1);
            row.add(mailbox.getSendName());
            row.add(record.getPolicyNumber());
            row.add(record.getWebsitId());
            row.add(record.getWebsitName());
            row.add("新增");
            row.add(record.getPolicyName());
            row.add("居民身份证");
            row.add(record.getPolicyIdcard());
            rows.add(row);
        }
        // 获取资源文件存放路径，用于临时存放生成的excel文件
        String path = "/tmp/";
        if (active.equals("dev")) {
            path = Objects.requireNonNull(this.getClass().getClassLoader().getResource("")).getPath();
        }
        // 文件名：采用UUID，防止多线程同时生成导致的文件重名
        String filePath = String.format("%s%s.xlsx", path, mailboxSendRecord.getSendBatch() + "-意外险");
        ExcelData excelData = new ExcelData();
        excelData.setTitles(Arrays.asList(titles));
        excelData.setRows(rows);
        ExcelUtils.createExcel(filePath, excelData);
        File excel = new File(filePath);



        //分发邮件
        Session session = emailUtilsNew.loadMailSession();

        emailUtilsNew.send(session,mailboxSendRecord.getReceiveMailbox(), mailbox.getSendMailbox(), "意外险-" + mailboxSendRecord.getSendBatch() + "-" + mailbox.getSendName(), "你好，以下是" + DateUtil.format(new Date(), "yyyy-MM-dd")
                + mailbox.getSendName() + "保险人员名单详情见附件", filePath);

        //删除该文件
        excel.delete();
    }

    public void del(String id) {
        agreementService.removeById(id);
    }


    @Async
    @Transactional(rollbackFor = Exception.class)
    public void sendEmailScheTask2() {


        Mailbox mailbox = mailboxService.getById("1");

        //今天要发送的保单
  /*      Date endTime = DateUtil.parseDateTime(DateUtils.formatDate(new Date(),"yyyy-MM-dd") +" "+ mailbox.getSendTime()+":00");
        if(new Date().getTime() < endTime.getTime()){
            //还没到可发邮件的时间
            return;
        }

        if (mailboxSendRecordService.lambdaQuery().gt(MailboxSendRecord::getSendTime, DateUtil.beginOfDay(new Date())).count() > 0) {
            return;
        }*/




        List<MailboxReceive> mailboxReceives = mailboxReceiveService.lambdaQuery().eq(MailboxReceive::getMailboxId, mailbox.getId()).list();


        //意外保险发送邮件
        List<PolicyOrder> policyOrders = policyOrderService.lambdaQuery().eq(PolicyOrder::getType, PolicyTypeEnum.AC.getKey())
                .eq(PolicyOrder::getIsPay, IsYesNoEnum.YES.getKey())
                .eq(PolicyOrder::getIsSend, IsYesNoEnum.NO.getKey()).list();


        if (!CollectionUtils.isEmpty(policyOrders)) {

            EmailUtilsNew emailUtilsNew = new EmailUtilsNew(mailbox.getSendMailbox(), mailbox.getSendPassword());

            MailboxSendRecord mailboxSendRecord = new MailboxSendRecord();
            mailboxSendRecord.setId(IdWorker.getIdStr());
            mailboxSendRecord.setPolicyType(PolicyTypeEnum.AC.getKey());
            mailboxSendRecord.setSendBatch(mailboxSendRecord.getId());
            mailboxSendRecord.setSendMailbox(mailbox.getSendMailbox());
            mailboxSendRecord.setReceiveMailbox(mailbox.getAccidentMailbox());
            mailboxSendRecord.setReceiptStatus(IsYesNoEnum.NO.getKey());
            mailboxSendRecord.setCompanyWechatId(mailbox.getCompanyWechatId());
            mailboxSendRecord.setCompanyWechatName(mailbox.getCompanyWechatName());

            List<MailboxSendRecordPolicy> mailboxSendRecordPolicies = new ArrayList<>();

            for (PolicyOrder policyOrder : policyOrders) {
                MailboxSendRecordPolicy mailboxSendRecordPolicy = new MailboxSendRecordPolicy();

                mailboxSendRecordPolicy.setCompanyWechatId(mailbox.getCompanyWechatId());
                mailboxSendRecordPolicy.setCompanyWechatName(mailbox.getCompanyWechatName());
                mailboxSendRecordPolicy.setPolicyNumber(policyOrder.getPolicyNumber());
                mailboxSendRecordPolicy.setPolicyName(policyOrder.getWorkerName());
                mailboxSendRecordPolicy.setWebsitName(policyOrder.getWebsitName());
                mailboxSendRecordPolicy.setWebsitId(policyOrder.getWebsitId());
                mailboxSendRecordPolicy.setPolicyMobile(policyOrder.getWorkerMobile());
                mailboxSendRecordPolicy.setPolicyIdcard(policyOrder.getWorkerIdcard());
                mailboxSendRecordPolicy.setType("IN");
                mailboxSendRecordPolicy.setSendBatch(mailboxSendRecord.getSendBatch());
                mailboxSendRecordPolicy.setPolicyOrderId(policyOrder.getId());
                mailboxSendRecordPolicy.setPolicyType(PolicyTypeEnum.AC.getKey());

                mailboxSendRecordPolicies.add(mailboxSendRecordPolicy);

                policyOrder.setIsSend(IsYesNoEnum.YES.getKey());
                policyOrder.setSendTime(new Date());
                policyOrder.setSendBatch(mailboxSendRecord.getSendBatch());
                policyOrder.updateById();
            }

            mailboxSendRecord.insert();
            mailboxSendRecordPolicyService.saveBatch(mailboxSendRecordPolicies);

            //发邮件
            try {
                this.sendEmailFile(mailboxSendRecordPolicies, mailboxSendRecord, mailbox,emailUtilsNew);
                mailboxSendRecord.setSendStatus("OK");
                mailboxSendRecord.setSendTime(new Date());
                mailboxSendRecord.updateById();
            } catch (Exception e) {
                mailboxSendRecord.setSendStatus("NO");
                mailboxSendRecord.setSendTime(new Date());
                mailboxSendRecord.updateById();
            }
        }


    }


    @Async
    @Transactional(rollbackFor = Exception.class)
    public void sendEmailSche() {


        Mailbox mailbox = mailboxService.getById("1");
        Date date = new Date();



        //今天要发送的保单
        Date endTime = DateUtil.parseDateTime(DateUtils.formatDate(date,"yyyy-MM-dd") +" "+ mailbox.getSendTime()+":00");
        if(date.before(endTime)){
            //还没到可发邮件的时间
            return;
        }

        if (mailboxSendRecordService.lambdaQuery().gt(MailboxSendRecord::getSendTime, DateUtil.beginOfDay(date))
                .eq(MailboxSendRecord::getPolicyType,PolicyTypeEnum.AC.getKey()).count() > 0) {
            return;
        }




        List<MailboxReceive> mailboxReceives = mailboxReceiveService.lambdaQuery().eq(MailboxReceive::getMailboxId, mailbox.getId()).list();


        //意外保险发送邮件
        List<PolicyOrder> policyOrders = policyOrderService.lambdaQuery().eq(PolicyOrder::getType, PolicyTypeEnum.AC.getKey())
                .eq(PolicyOrder::getIsPay, IsYesNoEnum.YES.getKey())
                .eq(PolicyOrder::getIsSend, IsYesNoEnum.NO.getKey()).list();


        if (!CollectionUtils.isEmpty(policyOrders)) {

            EmailUtilsNew emailUtilsNew = new EmailUtilsNew(mailbox.getSendMailbox(), mailbox.getSendPassword());

            MailboxSendRecord mailboxSendRecord = new MailboxSendRecord();
            mailboxSendRecord.setId(IdWorker.getIdStr());
            mailboxSendRecord.setPolicyType(PolicyTypeEnum.AC.getKey());
            mailboxSendRecord.setSendBatch(mailboxSendRecord.getId());
            mailboxSendRecord.setSendMailbox(mailbox.getSendMailbox());
            mailboxSendRecord.setReceiveMailbox(mailbox.getAccidentMailbox());
            mailboxSendRecord.setReceiptStatus(IsYesNoEnum.NO.getKey());
            mailboxSendRecord.setCompanyWechatId(mailbox.getCompanyWechatId());
            mailboxSendRecord.setCompanyWechatName(mailbox.getCompanyWechatName());

            List<MailboxSendRecordPolicy> mailboxSendRecordPolicies = new ArrayList<>();

            for (PolicyOrder policyOrder : policyOrders) {
                MailboxSendRecordPolicy mailboxSendRecordPolicy = new MailboxSendRecordPolicy();

                mailboxSendRecordPolicy.setCompanyWechatId(mailbox.getCompanyWechatId());
                mailboxSendRecordPolicy.setCompanyWechatName(mailbox.getCompanyWechatName());
                mailboxSendRecordPolicy.setPolicyNumber(policyOrder.getPolicyNumber());
                mailboxSendRecordPolicy.setPolicyName(policyOrder.getWorkerName());
                mailboxSendRecordPolicy.setWebsitName(policyOrder.getWebsitName());
                mailboxSendRecordPolicy.setWebsitId(policyOrder.getWebsitId());
                mailboxSendRecordPolicy.setPolicyMobile(policyOrder.getWorkerMobile());
                mailboxSendRecordPolicy.setPolicyIdcard(policyOrder.getWorkerIdcard());
                mailboxSendRecordPolicy.setType("IN");
                mailboxSendRecordPolicy.setSendBatch(mailboxSendRecord.getSendBatch());
                mailboxSendRecordPolicy.setPolicyOrderId(policyOrder.getId());
                mailboxSendRecordPolicy.setPolicyType(PolicyTypeEnum.AC.getKey());

                mailboxSendRecordPolicies.add(mailboxSendRecordPolicy);

                policyOrder.setIsSend(IsYesNoEnum.YES.getKey());
                policyOrder.setSendTime(new Date());
                policyOrder.setSendBatch(mailboxSendRecord.getSendBatch());
                policyOrder.updateById();
            }

            mailboxSendRecord.insert();
            mailboxSendRecordPolicyService.saveBatch(mailboxSendRecordPolicies);

            //发邮件
            try {
                mailboxSendRecord.setSendStatus("OK");
                mailboxSendRecord.setSendTime(new Date());
                mailboxSendRecord.updateById();
                this.sendEmailFile(mailboxSendRecordPolicies, mailboxSendRecord, mailbox,emailUtilsNew);

            } catch (Exception e) {
                mailboxSendRecord.setSendStatus("NO");
                mailboxSendRecord.setSendTime(new Date());
                mailboxSendRecord.updateById();
            }
        }


    }

    public void receEmail() throws IOException, MessagingException {

        Mailbox mailbox = mailboxService.getById("1");

        List<MailboxReceive> mailboxReceives = mailboxReceiveService.lambdaQuery().eq(MailboxReceive::getMailboxId, mailbox.getId()).list();

        List<MailboxSendRecord> mailboxSendRecordList = mailboxSendRecordService.lambdaQuery()
                .between(MailboxSendRecord::getSendTime, DateUtil.beginOfDay(new Date()), DateUtil.endOfDay(new Date()))
                .eq(MailboxSendRecord::getReceiptStatus, IsYesNoEnum.NO.getKey()).list();

        for (MailboxSendRecord mailboxSendRecord : mailboxSendRecordList) {

            Boolean b = false;

            for (String s : mailbox.getAccidentMailbox().split(",")) {
                Boolean rece = new EmailUtilsNew(mailbox.getSendMailbox(), mailbox.getSendPassword())
                        .receEmail(s, mailboxSendRecord.getSendBatch());

                if (rece)
                    b=true;

            }


            List<MailboxSendRecordPolicy> mailboxSendRecordPolicies = mailboxSendRecordPolicyService.lambdaQuery().in(MailboxSendRecordPolicy::getSendBatch, mailboxSendRecord.getSendBatch()).list();

            List<String> policyOrderId = mailboxSendRecordPolicies.stream().map(MailboxSendRecordPolicy::getPolicyOrderId).collect(Collectors.toList());



            if (b) {


                mailboxSendRecord.setReceiptStatus(IsYesNoEnum.YES.getKey());
                mailboxSendRecord.setReceiptTime(new Date());
                mailboxSendRecord.updateById();


                if (mailboxSendRecord.getPolicyType().equals(PolicyTypeEnum.AC.getKey())) {


                    policyOrderService.lambdaUpdate()
                            .in(PolicyOrder::getId, policyOrderId)
                            .set(PolicyOrder::getIsReceipt, IsYesNoEnum.YES.getKey())
                            .set(PolicyOrder::getReceiptTime, new Date())
                            .set(PolicyOrder::getPolicyOrderStatus, PolicyOrderEmStutasEnum.BZZ.getKey()).update();

                    List<PolicyOrder> policyOrders = policyOrderService.lambdaQuery().in(PolicyOrder::getId, policyOrderId).list();

                    for (PolicyOrder policyOrder : policyOrders) {

                        Policy policy = policyService.getById(policyOrder.getPolicyId());

                        workerPolicyService.lambdaUpdate()
                                .eq(WorkerPolicy::getOrderId,policyOrder.getId()).remove();

                        policyOrder.setIsReceipt(IsYesNoEnum.YES.getKey());
                        policyOrder.setReceiptTime(new Date());


                        List<WorkerPolicy> workerPolicies = workerPolicyService.lambdaQuery()
                                .eq(WorkerPolicy::getWebsitId, policyOrder.getWebsitId())
                                .eq(WorkerPolicy::getWebsitUserId, policyOrder.getWebsitUserId())
                                .eq(WorkerPolicy::getPolicyType, "AC")
                                .in(WorkerPolicy::getStatus, PolicyOrderStatusEnum.BZZ.getKey(),PolicyOrderStatusEnum.DSX.getKey())
                                .orderByDesc(WorkerPolicy::getEndTime)
                                .list();

                        //取师傅最后时间的后一天，小于保险时间就取保险时间

                        Date startTime = DateUtil.offsetDay(new Date(),1);

                        if (!CollectionUtils.isEmpty(workerPolicies)){
                            startTime = DateUtil.beginOfDay(DateUtil.offsetDay(workerPolicies.get(0).getEndTime(),1));
                        }

                        if (startTime.before(policy.getStartTime()))
                            startTime = policy.getStartTime();


                        policyOrder.setStartTime(DateUtil.beginOfDay(startTime));
                        policyOrder.setEndTime(this.getEndOfDay(policy.getEndTime()));

                        if (new Date().after(policyOrder.getStartTime()))
                            policyOrder.setPolicyOrderStatus("BZZ");
                        else
                            policyOrder.setPolicyOrderStatus("DSX");

                        policyOrder.updateById();

                        //生成师傅待生效保险
                        WorkerPolicy workerPolicy = new WorkerPolicy();
                        workerPolicy.setWebsitId(policyOrder.getWorkerNumber());
                        workerPolicy.setCompany(policy.getCompany());
                        workerPolicy.setType("IN");
                        workerPolicy.setPolicyName(policy.getPolicyName());
                        workerPolicy.setPolicyOrder(policy.getPolicyNumber());
                        workerPolicy.setOrderId(policyOrder.getId());
                        workerPolicy.setPolicyOrder(policy.getPolicyNumber());
                        workerPolicy.setPolicyType("AC");
                        workerPolicy.setStartTime(policyOrder.getStartTime());
                        workerPolicy.setEndTime(this.getEndOfDay(policyOrder.getEndTime()));
                        workerPolicy.setWebsitUserId(policyOrder.getWebsitUserId());
                        workerPolicy.setWebsitId(policyOrder.getWebsitId());
                        workerPolicy.setWebsitName(policyOrder.getWebsitName());
                        workerPolicy.setPolicyPrice(policyOrder.getPayAmount());
                        workerPolicy.setWorkerName(policyOrder.getWorkerName());
                        workerPolicy.setWorkerId(policyOrder.getWorkerNumber());


                        if (new Date().after(workerPolicy.getStartTime()))
                            workerPolicy.setStatus("BZZ");
                        else
                            workerPolicy.setStatus("DSX");

                        workerPolicy.insert();
                    }
                }


                if (mailboxSendRecord.getPolicyType().equals(PolicyTypeEnum.EM.getKey())) {


                    policyOrderService.lambdaUpdate()
                            .in(PolicyOrder::getId, policyOrderId)
                            .set(PolicyOrder::getStartTime, DateUtil.beginOfDay(DateUtil.offsetDay(new Date(), 1)))
                            .set(PolicyOrder::getEndTime, this.getEndOfDay(DateUtil.offsetMonth(new Date(), 12)))
                            .set(PolicyOrder::getIsReceipt, IsYesNoEnum.YES.getKey())
                            .set(PolicyOrder::getReceiptTime, new Date())
                            .set(PolicyOrder::getPolicyOrderStatus, PolicyOrderEmStutasEnum.DSX.getKey()).update();


                    List<PolicyOrder> policyOrders = policyOrderService.lambdaQuery().in(PolicyOrder::getId, policyOrderId).list();

                    List<WorkerPolicy> workerPolicies = new ArrayList<>();

                    for (PolicyOrder policyOrder : policyOrders) {

                        workerPolicyService.lambdaUpdate().eq(WorkerPolicy::getOrderId,policyOrder.getId()).remove();
                        WorkerPolicy workerPolicy = new WorkerPolicy();
                        workerPolicy.setWorkerId(policyOrder.getWorkerNumber());
                        workerPolicy.setType("IN");
                        workerPolicy.setPolicyName(policyOrder.getPolicyName());
                        workerPolicy.setOrderId(policyOrder.getId());
                        workerPolicy.setPolicyOrder(policyOrder.getPolicyId());
                        workerPolicy.setPolicyType(policyOrder.getType());
                        workerPolicy.setStatus(PolicyOrderEmStutasEnum.DSX.getKey());
                        workerPolicy.setStartTime(DateUtil.beginOfDay(DateUtil.offsetDay(new Date(), 1)));
                        workerPolicy.setEndTime(this.getEndOfDay(DateUtil.offsetMillisecond(DateUtil.endOfDay(DateUtil.offsetMonth(new Date(), 12)),-999)));
                        workerPolicy.setWebsitUserId(policyOrder.getWebsitUserId());
                        workerPolicy.setWebsitId(policyOrder.getWebsitId());
                        workerPolicy.setWebsitName(policyOrder.getWebsitName());
                        workerPolicy.setWorkerName(policyOrder.getWorkerName());
                        workerPolicy.setWorkerName(policyOrder.getWorkerName());

                        if (new Date().after(workerPolicy.getStartTime()))
                            workerPolicy.setStatus("BZZ");
                        else
                            workerPolicy.setStatus("DSX");

                        workerPolicies.add(workerPolicy);
                    }
                    workerPolicyService.saveBatch(workerPolicies);

                }


                if (mailboxSendRecord.getPolicyType().equals(PolicyTypeEnum.IN.getKey())) {
                    //将今天的工伤险都收到回执
                    policyOrderService.lambdaUpdate()
                            .in(PolicyOrder::getId, policyOrderId)
                            .set(PolicyOrder::getIsReceipt, IsYesNoEnum.YES.getKey())
                            .set(PolicyOrder::getReceiptTime, new Date())
                            .set(PolicyOrder::getPolicyOrderStatus, PolicyOrderInStutasEnum.DGM.getKey()).update();


                }


            }

        }

    }

    public void offInsure() {

        workerPolicyService.lambdaUpdate()
                .le(WorkerPolicy::getEndTime, DateUtil.beginOfDay(new Date()))
                .set(WorkerPolicy::getStatus, PolicyOrderStatusEnum.YSX.getKey()).update();

        policyOrderService.lambdaUpdate()
                .le(PolicyOrder::getEndTime,  DateUtil.beginOfDay(new Date()))
                .set(PolicyOrder::getPolicyOrderStatus, PolicyOrderStatusEnum.YSX.getKey()).update();


        List<PolicyOrder> list = policyOrderService.lambdaQuery()
                .ge(PolicyOrder::getEndTime,  DateUtil.beginOfDay(new Date()))
                .le(PolicyOrder::getStartTime, new Date())
                .eq(PolicyOrder::getIsReceipt, IsYesNoEnum.YES.getKey())
                .ne(PolicyOrder::getPolicyOrderStatus, PolicyOrderStatusEnum.BZZ.getKey())
                .ne(PolicyOrder::getPolicyOrderStatus, PolicyOrderStatusEnum.YSX.getKey())
                .select(PolicyOrder::getId)
                .list();

        if (!CollectionUtils.isEmpty(list)) {
            workerPolicyService.lambdaUpdate()
                    .ge(WorkerPolicy::getEndTime,  DateUtil.beginOfDay(new Date()))
                    .le(WorkerPolicy::getStartTime, new Date())
                    .in(WorkerPolicy::getOrderId, list.stream().map(PolicyOrder::getId).collect(Collectors.toList()))
                    .ne(WorkerPolicy::getStatus, PolicyOrderStatusEnum.BZZ.getKey())
                    .set(WorkerPolicy::getStatus, PolicyOrderStatusEnum.BZZ.getKey())
                    .update();
        }


        policyOrderService.lambdaUpdate()
                .ge(PolicyOrder::getEndTime,  DateUtil.beginOfDay(new Date()))
                .le(PolicyOrder::getStartTime, new Date())
                .eq(PolicyOrder::getIsReceipt, IsYesNoEnum.YES.getKey())
                .ne(PolicyOrder::getPolicyOrderStatus, PolicyOrderStatusEnum.BZZ.getKey())
                .ne(PolicyOrder::getPolicyOrderStatus, PolicyOrderStatusEnum.YSX.getKey())
                .set(PolicyOrder::getPolicyOrderStatus, PolicyOrderStatusEnum.BZZ.getKey())
                .update();


    }


    public void task4() {
        List<WebsitUser> websitUsers = websitUserService.lambdaQuery().eq(WebsitUser::getExamineStatus, "WAIT_WORKER").list();

        //保险齐全变成待保险审批
        for (WebsitUser websitUser : websitUsers) {
            if (workerPolicyService.lambdaQuery().in(WorkerPolicy::getStatus, "BZZ", "DSX")
                    .eq(WorkerPolicy::getWebsitUserId, websitUser.getId()).count() > 1) {
                websitUser.setExamineStatus("POLICY_WAIT");
                websitUser.updateById();
            }
        }
        List<WebsitUser> websitUsersOk = websitUserService.lambdaQuery().eq(WebsitUser::getExamineStatus, "OK").list();

        //失效工程师
        for (WebsitUser websitUser : websitUsersOk) {
            if (workerPolicyService.lambdaQuery().in(WorkerPolicy::getStatus, "BZZ")
                    .eq(WorkerPolicy::getWebsitUserId, websitUser.getId()).count() < 2) {
                websitUser.setExamineStatus("WAIT_WORKER");
                websitUser.updateById();
            }
        }
    }


    public void task5() {

        List<WebsitUser> websitUsers = websitUserService.lambdaQuery().eq(WebsitUser::getExamineStatus, ExamineWorkerStatusEnum.OK.getKey()).list();

        Mailbox mailbox = mailboxService.getById("1");

        for (WebsitUser websitUser : websitUsers) {

            User user = userService.getById(websitUser.getUserId());

            String remark = "";
            if ((user.getHightExamineTime() != null && user.getHightExamineTime().before(DateUtil.offsetMonth( DateUtil.beginOfDay(new Date()),1)))
            ){

                remark = remark+"高空证"+DateUtil.format(user.getHightExamineTime(),"yyyy-MM-dd");
            }


            if (( user.getIdCardEndTime() != null && user.getIdCardEndTime().before(DateUtil.offsetMonth( DateUtil.beginOfDay(new Date()),1)))

            ){
                if (!StringUtil.isEmpty(remark))
                    remark = remark+",";
                remark = remark+"身份证"+DateUtil.format(user.getIdCardEndTime(),"yyyy-MM-dd");
            }

            List<WorkerPolicy> workerPolicies = workerPolicyService.lambdaQuery()
                    .eq(WorkerPolicy::getWebsitUserId,websitUser.getId())
                    .in(WorkerPolicy::getStatus, WorkerPolicyStatusEnum.BZZ.getKey(), WorkerPolicyStatusEnum.DSX.getKey())
                    .list();

            for (WorkerPolicy workerPolicy : workerPolicies) {
                if (workerPolicy.getPolicyType().equals(PolicyTypeEnum.AC.getKey()) &&
                workerPolicy.getEndTime() != null && workerPolicy.getEndTime().before(DateUtil.offsetMonth( DateUtil.beginOfDay(new Date()),1))
                ) {
                    if (!StringUtil.isEmpty(remark))
                        remark = remark+",";
                    remark = remark+"意外险"+DateUtil.format(workerPolicy.getEndTime(),"yyyy-MM-dd");
                }
                if (workerPolicy.getPolicyType().equals(PolicyTypeEnum.EM.getKey()) &&
                        workerPolicy.getEndTime() != null && workerPolicy.getEndTime().before(DateUtil.offsetMonth( DateUtil.beginOfDay(new Date()),1))
                ) {
                    if (!StringUtil.isEmpty(remark))
                        remark = remark+",";
                    remark = remark+"雇主险"+DateUtil.format(workerPolicy.getEndTime(),"yyyy-MM-dd");
                }

                if (workerPolicy.getPolicyType().equals(PolicyTypeEnum.IN.getKey()) &&
                        workerPolicy.getEndTime() != null && workerPolicy.getEndTime().before(DateUtil.offsetDay( DateUtil.beginOfDay(new Date()),mailbox.getOverNum()))
                ) {
                    if (!StringUtil.isEmpty(remark))
                        remark = remark+",";
                    remark = remark+"工伤险"+DateUtil.format(workerPolicy.getEndTime(),"yyyy-MM-dd");
                }
            }

            if (!StringUtil.isEmpty(remark)) {

                WebsitUser websitUser1 = new WebsitUser();
                websitUser1.setId(websitUser.getId());
                websitUser1.setOverdueRemark(remark);
                if (!StringUtil.isEmpty(remark)) {
                    websitUser1.setIsOverdue(IsYesNoEnum.YES.getKey());
                } else {
                    websitUser1.setIsOverdue(IsYesNoEnum.NO.getKey());
                }

                if ((user.getHightExamineTime() != null && user.getHightExamineTime().before(new Date()))
                ){
                    websitUser1.setExamineStatus(ExamineWorkerStatusEnum.OVERDUE.getKey());
                }

                if (( user.getIdCardEndTime() != null && user.getIdCardEndTime().before(new Date()))

                ){
                    websitUser1.setExamineStatus(ExamineWorkerStatusEnum.OVERDUE.getKey());
                }
                websitUser1.updateById();
            }
            if (StringUtil.isEmpty(remark)){
                websitUserService.lambdaUpdate().eq(WebsitUser::getId,websitUser.getId())
                        .set(WebsitUser::getOverdueRemark,"").update();
            }

        }


    }


    @Async
    @Transactional(rollbackFor = Exception.class)
    public void sendEmailScheEMTask2() {


        Mailbox mailbox = mailboxService.getById("1");

        //今天要发送的保单
        //Date startTime = DateUtil.beginOfDay(new Date());
   /*     Date endTime = DateUtil.parseDateTime(DateUtils.formatDate(new Date(),"yyyy-MM-dd") +" "+ mailbox.getSendTime()+":00");
        if(new Date().getTime() < endTime.getTime()){
            //还没到可发邮件的时间
            return;
        }

        if (mailboxSendRecordService.lambdaQuery().gt(MailboxSendRecord::getSendTime, DateUtil.beginOfDay(new Date())).count() > 0) {
            return;
        }*/




        List<MailboxReceive> mailboxReceives = mailboxReceiveService.lambdaQuery().eq(MailboxReceive::getMailboxId, mailbox.getId()).list();


        //雇主保险发送邮件
        List<PolicyOrder> policyOrdersEm = policyOrderService.lambdaQuery()
                .eq(PolicyOrder::getType, PolicyTypeEnum.EM.getKey())
                .eq(PolicyOrder::getIsImport, IsYesNoEnum.NO.getKey())
                .eq(PolicyOrder::getIsSend, IsYesNoEnum.NO.getKey()).list();

        if (!CollectionUtils.isEmpty(policyOrdersEm)) {

            EmailUtilsNew emailUtilsNew = new EmailUtilsNew(mailbox.getSendMailbox(), mailbox.getSendPassword());
            MailboxSendRecord mailboxSendRecord = new MailboxSendRecord();
            mailboxSendRecord.setId(IdWorker.getIdStr());
            mailboxSendRecord.setPolicyType(PolicyTypeEnum.EM.getKey());
            mailboxSendRecord.setSendBatch(mailboxSendRecord.getId());
            mailboxSendRecord.setSendMailbox(mailbox.getSendMailbox());
            mailboxSendRecord.setReceiveMailbox(mailbox.getEmployerMailbox());
            mailboxSendRecord.setReceiptStatus(IsYesNoEnum.NO.getKey());
            mailboxSendRecord.setCompanyWechatId(mailbox.getCompanyWechatId());
            mailboxSendRecord.setCompanyWechatName(mailbox.getCompanyWechatName());

            List<MailboxSendRecordPolicy> mailboxSendRecordPolicies = new ArrayList<>();

            for (PolicyOrder policyOrder : policyOrdersEm) {
                MailboxSendRecordPolicy mailboxSendRecordPolicy = new MailboxSendRecordPolicy();

                mailboxSendRecordPolicy.setCompanyWechatId(mailboxSendRecord.getCompanyWechatId());
                mailboxSendRecordPolicy.setCompanyWechatName(mailboxSendRecord.getCompanyWechatName());
                mailboxSendRecordPolicy.setPolicyNumber(policyOrder.getPolicyId());
                mailboxSendRecordPolicy.setPolicyName(policyOrder.getWorkerName());
                mailboxSendRecordPolicy.setPolicyOrderId(policyOrder.getId());
                mailboxSendRecordPolicy.setWebsitName(policyOrder.getWebsitName());
                mailboxSendRecordPolicy.setWebsitId(policyOrder.getWebsitId());
                mailboxSendRecordPolicy.setPolicyMobile(policyOrder.getWorkerMobile());

                mailboxSendRecordPolicy.setPolicyIdcard(policyOrder.getWorkerIdcard());
                mailboxSendRecordPolicy.setPolicyIdcard(policyOrder.getWorkerIdcard());
                mailboxSendRecordPolicy.setType("IN");
                mailboxSendRecordPolicy.setSendBatch(mailboxSendRecord.getSendBatch());
                mailboxSendRecordPolicy.setPolicyType(PolicyTypeEnum.EM.getKey());

                if (!StringUtil.isEmpty(policyOrder.getReplaceName())) {
                    mailboxSendRecordPolicy.setType("RE");
                    mailboxSendRecordPolicy.setReplaceName(policyOrder.getReplaceName());
                    mailboxSendRecordPolicy.setReplaceIdcard(policyOrder.getReplaceIdcard());
                }


                mailboxSendRecordPolicies.add(mailboxSendRecordPolicy);

                policyOrder.setIsSend(IsYesNoEnum.YES.getKey());
                policyOrder.setSendTime(new Date());
                policyOrder.setSendBatch(mailboxSendRecord.getSendBatch());
                policyOrder.updateById();
            }


            //发邮件
            try {
                this.sendEmailFileEm(mailboxSendRecordPolicies, mailboxSendRecord, mailbox, emailUtilsNew);
                mailboxSendRecord.setSendStatus("OK");
                mailboxSendRecord.setSendTime(new Date());
                mailboxSendRecord.updateById();
            } catch (Exception e) {
                mailboxSendRecord.setSendStatus("NO");
                mailboxSendRecord.setSendTime(new Date());
                mailboxSendRecord.updateById();
            }

            mailboxSendRecord.insert();
            mailboxSendRecordPolicyService.saveBatch(mailboxSendRecordPolicies);
        }


    }



    @Async
    @Transactional(rollbackFor = Exception.class)
    public void sendEmailScheEM() {


        Mailbox mailbox = mailboxService.getById("1");
        Date date = new Date();
        //今天要发送的保单
        //Date startTime = DateUtil.beginOfDay(new Date());
        Date endTime = DateUtil.parseDateTime(DateUtils.formatDate(date,"yyyy-MM-dd") +" "+ mailbox.getSendTime()+":00");
         if(date.before(endTime)){
           //还没到可发邮件的时间
            return;
        }

        if (mailboxSendRecordService.lambdaQuery().gt(MailboxSendRecord::getSendTime, DateUtil.beginOfDay(date))
                .eq(MailboxSendRecord::getPolicyType,PolicyTypeEnum.EM.getKey())
                .count() > 0) {
            return;
        }




        List<MailboxReceive> mailboxReceives = mailboxReceiveService.lambdaQuery().eq(MailboxReceive::getMailboxId, mailbox.getId()).list();


        //雇主保险发送邮件
        List<PolicyOrder> policyOrdersEm = policyOrderService.lambdaQuery()
                .eq(PolicyOrder::getType, PolicyTypeEnum.EM.getKey())
                .eq(PolicyOrder::getIsImport, IsYesNoEnum.NO.getKey())
                .eq(PolicyOrder::getIsSend, IsYesNoEnum.NO.getKey()).list();

        if (!CollectionUtils.isEmpty(policyOrdersEm)) {

            EmailUtilsNew emailUtilsNew = new EmailUtilsNew(mailbox.getSendMailbox(), mailbox.getSendPassword());
            MailboxSendRecord mailboxSendRecord = new MailboxSendRecord();
            mailboxSendRecord.setId(IdWorker.getIdStr());
            mailboxSendRecord.setPolicyType(PolicyTypeEnum.EM.getKey());
            mailboxSendRecord.setSendBatch(mailboxSendRecord.getId());
            mailboxSendRecord.setSendMailbox(mailbox.getSendMailbox());
            mailboxSendRecord.setReceiveMailbox(mailbox.getEmployerMailbox());
            mailboxSendRecord.setReceiptStatus(IsYesNoEnum.NO.getKey());
            mailboxSendRecord.setCompanyWechatId(mailbox.getCompanyWechatId());
            mailboxSendRecord.setCompanyWechatName(mailbox.getCompanyWechatName());

            List<MailboxSendRecordPolicy> mailboxSendRecordPolicies = new ArrayList<>();

            for (PolicyOrder policyOrder : policyOrdersEm) {
                MailboxSendRecordPolicy mailboxSendRecordPolicy = new MailboxSendRecordPolicy();

                mailboxSendRecordPolicy.setCompanyWechatId(mailboxSendRecord.getCompanyWechatId());
                mailboxSendRecordPolicy.setCompanyWechatName(mailboxSendRecord.getCompanyWechatName());
                mailboxSendRecordPolicy.setPolicyNumber(policyOrder.getPolicyId());
                mailboxSendRecordPolicy.setPolicyName(policyOrder.getWorkerName());
                mailboxSendRecordPolicy.setPolicyOrderId(policyOrder.getId());
                mailboxSendRecordPolicy.setWebsitName(policyOrder.getWebsitName());
                mailboxSendRecordPolicy.setWebsitId(policyOrder.getWebsitId());
                mailboxSendRecordPolicy.setPolicyMobile(policyOrder.getWorkerMobile());

                mailboxSendRecordPolicy.setPolicyIdcard(policyOrder.getWorkerIdcard());
                mailboxSendRecordPolicy.setPolicyIdcard(policyOrder.getWorkerIdcard());
                mailboxSendRecordPolicy.setType("IN");
                mailboxSendRecordPolicy.setSendBatch(mailboxSendRecord.getSendBatch());
                mailboxSendRecordPolicy.setPolicyType(PolicyTypeEnum.EM.getKey());

                if (!StringUtil.isEmpty(policyOrder.getReplaceName())) {
                    mailboxSendRecordPolicy.setType("RE");
                    mailboxSendRecordPolicy.setReplaceName(policyOrder.getReplaceName());
                    mailboxSendRecordPolicy.setReplaceIdcard(policyOrder.getReplaceIdcard());
                }


                mailboxSendRecordPolicies.add(mailboxSendRecordPolicy);

                policyOrder.setIsSend(IsYesNoEnum.YES.getKey());
                policyOrder.setSendTime(new Date());
                policyOrder.setSendBatch(mailboxSendRecord.getSendBatch());
                policyOrder.updateById();
            }


            //发邮件
            try {
                this.sendEmailFileEm(mailboxSendRecordPolicies, mailboxSendRecord, mailbox, emailUtilsNew);
                mailboxSendRecord.setSendStatus("OK");
                mailboxSendRecord.setSendTime(new Date());
                mailboxSendRecord.updateById();
            } catch (Exception e) {
                mailboxSendRecord.setSendStatus("NO");
                mailboxSendRecord.setSendTime(new Date());
                mailboxSendRecord.updateById();
            }

            mailboxSendRecord.insert();
            mailboxSendRecordPolicyService.saveBatch(mailboxSendRecordPolicies);
    }


}


    @Async
    @Transactional(rollbackFor = Exception.class)
    public void sendEmailScheINTask2() {

        Mailbox mailbox = mailboxService.getById("1");

        //今天要发送的保单
        //Date startTime = DateUtil.beginOfDay(new Date());
/*        Date endTime = DateUtil.parseDateTime(DateUtils.formatDate(new Date(),"yyyy-MM-dd") +" "+ mailbox.getSendTime()+":00");
        if(new Date().getTime() < endTime.getTime()){
            //还没到可发邮件的时间
            return;
        }

        if (mailboxSendRecordService.lambdaQuery().gt(MailboxSendRecord::getSendTime, DateUtil.beginOfDay(new Date())).count() > 0) {
            return;
        }*/




        List<MailboxReceive> mailboxReceives = mailboxReceiveService.lambdaQuery().eq(MailboxReceive::getMailboxId, mailbox.getId()).list();
        //工伤保险发送邮件
        for (MailboxReceive mailboxReceive : mailboxReceives) {

            EmailUtilsNew emailUtilsNew = new EmailUtilsNew(mailbox.getSendMailbox(), mailbox.getSendPassword());
            List<PolicyOrder> policyOrdersIn = policyOrderService.lambdaQuery()
                    .eq(PolicyOrder::getType, PolicyTypeEnum.IN.getKey())
                    .eq(PolicyOrder::getIsImport, IsYesNoEnum.NO.getKey())
                    .eq(PolicyOrder::getBuyUnitId, mailboxReceive.getDictId())
                    .eq(PolicyOrder::getIsSend, IsYesNoEnum.NO.getKey()).list();

            if (!CollectionUtils.isEmpty(policyOrdersIn)) {


                MailboxSendRecord mailboxSendRecord = new MailboxSendRecord();
                mailboxSendRecord.setId(IdWorker.getIdStr());
                mailboxSendRecord.setPolicyType(PolicyTypeEnum.IN.getKey());
                mailboxSendRecord.setSendBatch(mailboxSendRecord.getId());
                mailboxSendRecord.setSendMailbox(mailbox.getSendMailbox());
                mailboxSendRecord.setReceiveMailbox(mailboxReceive.getReceiveMailbox());
                mailboxSendRecord.setReceiptStatus(IsYesNoEnum.NO.getKey());
                mailboxSendRecord.setCompanyWechatId(mailbox.getCompanyWechatId());
                mailboxSendRecord.setCompanyWechatName(mailbox.getCompanyWechatName());

                List<MailboxSendRecordPolicy> mailboxSendRecordPolicies = new ArrayList<>();

                for (PolicyOrder policyOrder : policyOrdersIn) {
                    MailboxSendRecordPolicy mailboxSendRecordPolicy = new MailboxSendRecordPolicy();

                    mailboxSendRecordPolicy.setCompanyWechatId(mailboxSendRecord.getCompanyWechatId());
                    mailboxSendRecordPolicy.setCompanyWechatName(mailboxSendRecord.getCompanyWechatName());
                    mailboxSendRecordPolicy.setPolicyNumber(policyOrder.getPolicyId());
                    mailboxSendRecordPolicy.setPolicyOrderId(policyOrder.getId());
                    mailboxSendRecordPolicy.setPolicyName(policyOrder.getWorkerName());
                    mailboxSendRecordPolicy.setWebsitName(policyOrder.getWebsitName());
                    mailboxSendRecordPolicy.setWebsitId(policyOrder.getWebsitId());
                    mailboxSendRecordPolicy.setPolicyMobile(policyOrder.getWorkerMobile());
                    mailboxSendRecordPolicy.setPolicyIdcard(policyOrder.getWorkerIdcard());
                    mailboxSendRecordPolicy.setType("IN");
                    mailboxSendRecordPolicy.setSendBatch(mailboxSendRecord.getSendBatch());
                    mailboxSendRecordPolicy.setPolicyType(PolicyTypeEnum.IN.getKey());


                    mailboxSendRecordPolicies.add(mailboxSendRecordPolicy);

                    policyOrder.setIsSend(IsYesNoEnum.YES.getKey());
                    policyOrder.setSendTime(new Date());
                    policyOrder.setSendBatch(mailboxSendRecord.getSendBatch());
                    policyOrder.updateById();
                }

                mailboxSendRecord.insert();
                mailboxSendRecordPolicyService.saveBatch(mailboxSendRecordPolicies);

                //发邮件
                try {
                    this.sendEmailFileIn(mailboxSendRecordPolicies, mailboxSendRecord, mailbox, emailUtilsNew);
                    mailboxSendRecord.setSendStatus("OK");
                    mailboxSendRecord.setSendTime(new Date());
                    mailboxSendRecord.updateById();
                } catch (Exception e) {
                    mailboxSendRecord.setSendStatus("NO");
                    mailboxSendRecord.setSendTime(new Date());
                    mailboxSendRecord.updateById();
                }
            }
        }

    }


    @Async
    @Transactional(rollbackFor = Exception.class)
    public void sendEmailScheIN() {

        Mailbox mailbox = mailboxService.getById("1");
        Date date = new Date();
        //今天要发送的保单
        //Date startTime = DateUtil.beginOfDay(new Date());
        Date endTime = DateUtil.parseDateTime(DateUtils.formatDate(date,"yyyy-MM-dd") +" "+ mailbox.getSendTime()+":00");
        if(date.before(endTime)){
            //还没到可发邮件的时间
            return;
        }

        if (mailboxSendRecordService.lambdaQuery().gt(MailboxSendRecord::getSendTime, DateUtil.beginOfDay(date))
                .eq(MailboxSendRecord::getPolicyType,PolicyTypeEnum.IN.getKey())
                .count() > 0) {
            return;
        }




        List<MailboxReceive> mailboxReceives = mailboxReceiveService.lambdaQuery().eq(MailboxReceive::getMailboxId, mailbox.getId()).list();
        //工伤保险发送邮件
        for (MailboxReceive mailboxReceive : mailboxReceives) {

            EmailUtilsNew emailUtilsNew = new EmailUtilsNew(mailbox.getSendMailbox(), mailbox.getSendPassword());
            List<PolicyOrder> policyOrdersIn = policyOrderService.lambdaQuery()
                    .eq(PolicyOrder::getType, PolicyTypeEnum.IN.getKey())
                    .eq(PolicyOrder::getIsImport, IsYesNoEnum.NO.getKey())
                    .eq(PolicyOrder::getBuyUnitId, mailboxReceive.getDictId())
                    .eq(PolicyOrder::getIsSend, IsYesNoEnum.NO.getKey()).list();

            if (!CollectionUtils.isEmpty(policyOrdersIn)) {


                MailboxSendRecord mailboxSendRecord = new MailboxSendRecord();
                mailboxSendRecord.setId(IdWorker.getIdStr());
                mailboxSendRecord.setPolicyType(PolicyTypeEnum.IN.getKey());
                mailboxSendRecord.setSendBatch(mailboxSendRecord.getId());
                mailboxSendRecord.setSendMailbox(mailbox.getSendMailbox());
                mailboxSendRecord.setReceiveMailbox(mailboxReceive.getReceiveMailbox());
                mailboxSendRecord.setReceiptStatus(IsYesNoEnum.NO.getKey());
                mailboxSendRecord.setCompanyWechatId(mailbox.getCompanyWechatId());
                mailboxSendRecord.setCompanyWechatName(mailbox.getCompanyWechatName());

                List<MailboxSendRecordPolicy> mailboxSendRecordPolicies = new ArrayList<>();

                for (PolicyOrder policyOrder : policyOrdersIn) {
                    MailboxSendRecordPolicy mailboxSendRecordPolicy = new MailboxSendRecordPolicy();

                    mailboxSendRecordPolicy.setCompanyWechatId(mailboxSendRecord.getCompanyWechatId());
                    mailboxSendRecordPolicy.setCompanyWechatName(mailboxSendRecord.getCompanyWechatName());
                    mailboxSendRecordPolicy.setPolicyNumber(policyOrder.getPolicyId());
                    mailboxSendRecordPolicy.setPolicyOrderId(policyOrder.getId());
                    mailboxSendRecordPolicy.setPolicyName(policyOrder.getWorkerName());
                    mailboxSendRecordPolicy.setWebsitName(policyOrder.getWebsitName());
                    mailboxSendRecordPolicy.setWebsitId(policyOrder.getWebsitId());
                    mailboxSendRecordPolicy.setPolicyMobile(policyOrder.getWorkerMobile());
                    mailboxSendRecordPolicy.setPolicyIdcard(policyOrder.getWorkerIdcard());
                    mailboxSendRecordPolicy.setType("IN");
                    mailboxSendRecordPolicy.setSendBatch(mailboxSendRecord.getSendBatch());
                    mailboxSendRecordPolicy.setPolicyType(PolicyTypeEnum.IN.getKey());


                    mailboxSendRecordPolicies.add(mailboxSendRecordPolicy);

                    policyOrder.setIsSend(IsYesNoEnum.YES.getKey());
                    policyOrder.setSendTime(new Date());
                    policyOrder.setSendBatch(mailboxSendRecord.getSendBatch());
                    policyOrder.updateById();
                }

                mailboxSendRecord.insert();
                mailboxSendRecordPolicyService.saveBatch(mailboxSendRecordPolicies);

                //发邮件
                try {
                    this.sendEmailFileIn(mailboxSendRecordPolicies, mailboxSendRecord, mailbox, emailUtilsNew);
                    mailboxSendRecord.setSendStatus("OK");
                    mailboxSendRecord.setSendTime(new Date());
                    mailboxSendRecord.updateById();
                } catch (Exception e) {
                    mailboxSendRecord.setSendStatus("NO");
                    mailboxSendRecord.setSendTime(new Date());
                    mailboxSendRecord.updateById();
                }
            }
        }

    }

    public void task6() {


        List<WebsitUser> websitUsers = websitUserService.lambdaQuery().eq(WebsitUser::getExamineStatus, ExamineStatusEnum.OK.getKey()).list();

        List<String> websitUserIds = websitUsers.stream().map(WebsitUser::getId).collect(Collectors.toList());


        List<WorkerPolicy> workerPolicies = workerPolicyService.lambdaQuery().in(WorkerPolicy::getWebsitUserId, websitUserIds)
                .eq(WorkerPolicy::getPolicyType,PolicyTypeEnum.IN.getKey())
                .eq(WorkerPolicy::getStatus,PolicyOrderStatusEnum.BZZ.getKey())
                .le(WorkerPolicy::getEndTime,DateUtil.offsetDay(DateUtil.endOfDay(new Date()),3))
                .list();

        for (WorkerPolicy workerPolicy : workerPolicies) {

            if (policyOrderService.lambdaQuery().eq(PolicyOrder::getPolicyOrderStatus, PolicyOrderInStutasEnum.DGM.getKey())
                    .eq(PolicyOrder::getWebsitUserId,workerPolicy.getWebsitUserId())
                    .eq(PolicyOrder::getType,"IN").count() > 0) {
                continue;
            }

            if (policyOrderService.lambdaQuery().gt(PolicyOrder::getEndTime,workerPolicy.getEndTime())
                    .eq(PolicyOrder::getWebsitUserId,workerPolicy.getWebsitUserId())
                    .in(PolicyOrder::getPolicyOrderStatus,"BZZ","DSX")
                    .eq(PolicyOrder::getType,"IN").count() > 0
            ){
                continue;
            }

            AdminWebsit adminWebsit = adminWebsitService.getById(workerPolicy.getWebsitId());
            WebsitUser websitUser = websitUserService.getById(workerPolicy.getWebsitUserId());
            User user = userService.getById(websitUser.getUserId());

            SysDictCompany sysDictCompany = sysDictCompanyService.lambdaQuery().eq(SysDictCompany::getDictCode, adminWebsit.getInsureSteadUnit())
                    .eq(SysDictCompany::getDictType,"INSURE_STEAD_UNIT").one();


            PolicyOrder policyOrder = new PolicyOrder();
            policyOrder.setBelongCompany(adminWebsit.getBelongCompany());
            policyOrder.setBelongCompanyCode(adminWebsit.getBelongCompanyCode());
            policyOrder.setPolicyOrderStatus(PolicyOrderInStutasEnum.DGM.getKey());
            policyOrder.setPolicyName("工伤险");
            policyOrder.setCompanyWechatId(adminWebsit.getCompanyWechatId());
            policyOrder.setCompanyWechatName(adminWebsit.getCompanyWechatName());
            policyOrder.setPolicyId(IdWorker.getIdStr());
            policyOrder.setId(policyOrder.getPolicyId());
            policyOrder.setWebsitId(adminWebsit.getWebsitId());
            policyOrder.setWebsitName(adminWebsit.getName());
            policyOrder.setWorkerNumber(websitUser.getWorkerNumber());
            policyOrder.setWorkerName(user.getNickName());
            policyOrder.setWorkerIdcard(user.getIdCard());
            policyOrder.setWorkerMobile(user.getMobile());
            policyOrder.setBuyUnitId(adminWebsit.getInsureSteadUnit());
            policyOrder.setBuyUnit(sysDictCompany.getDictValue());
            policyOrder.setCompany(sysDictCompany.getDictValue());

            policyOrder.setWebsitUserId(websitUser.getId());
            policyOrder.setType("IN");
            policyOrder.insert();


        }
    }

    public void task7() {
        Mailbox mailbox = mailboxService.getById(1);
        List<WebsitUser> websitUsers = websitUserService.lambdaQuery().eq(WebsitUser::getExamineStatus, ExamineStatusEnum.OK.getKey()).list();

        List<String> websitUserIds = websitUsers.stream().map(WebsitUser::getId).collect(Collectors.toList());


        List<WorkerPolicy> workerPolicies = workerPolicyService.lambdaQuery().in(WorkerPolicy::getWebsitUserId, websitUserIds)
                .eq(WorkerPolicy::getPolicyType,PolicyTypeEnum.EM.getKey())
                .eq(WorkerPolicy::getStatus,PolicyOrderStatusEnum.BZZ.getKey())
                .le(WorkerPolicy::getEndTime,DateUtil.offsetDay(DateUtil.endOfDay(new Date()),mailbox.getOverNum()))
                .list();

        for (WorkerPolicy workerPolicy : workerPolicies) {

            if (policyOrderService.lambdaQuery().eq(PolicyOrder::getPolicyOrderStatus, PolicyOrderEmStutasEnum.XG.getKey())
                    .eq(PolicyOrder::getWebsitUserId,workerPolicy.getWebsitUserId())
                    .eq(PolicyOrder::getType,"EM").count() > 0) {
                continue;
            }

            if (policyOrderService.lambdaQuery().eq(PolicyOrder::getPolicyOrderStatus, PolicyOrderEmStutasEnum.DSX.getKey())
                    .eq(PolicyOrder::getWebsitUserId,workerPolicy.getWebsitUserId())
                    .eq(PolicyOrder::getType,"EM").count() > 0) {
                continue;
            }

            if (policyOrderService.lambdaQuery().eq(PolicyOrder::getPolicyOrderStatus, PolicyOrderEmStutasEnum.DTH.getKey())
                    .eq(PolicyOrder::getWebsitUserId,workerPolicy.getWebsitUserId())
                    .eq(PolicyOrder::getType,"EM").count() > 0) {
                continue;
            }


            AdminWebsit adminWebsit = adminWebsitService.getById(workerPolicy.getWebsitId());

            if (adminWebsit == null)
                continue;

            WebsitUser websitUser = websitUserService.getById(workerPolicy.getWebsitUserId());
            User user = userService.getById(websitUser.getUserId());


            PolicyOrder policyOrder = new PolicyOrder();
            policyOrder.setBelongCompany(adminWebsit.getBelongCompany());
            policyOrder.setBelongCompanyCode(adminWebsit.getBelongCompanyCode());
            policyOrder.setPolicyOrderStatus(PolicyOrderEmStutasEnum.XG.getKey());
            policyOrder.setPolicyName("雇主险");
            policyOrder.setCompanyWechatId(adminWebsit.getCompanyWechatId());
            policyOrder.setCompanyWechatName(adminWebsit.getCompanyWechatName());
            policyOrder.setPolicyId(IdWorker.getIdStr());
            policyOrder.setId(policyOrder.getPolicyId());
            policyOrder.setWebsitId(adminWebsit.getWebsitId());
            policyOrder.setWebsitName(adminWebsit.getName());
            policyOrder.setWorkerNumber(websitUser.getWorkerNumber());
            policyOrder.setWorkerName(user.getNickName());
            policyOrder.setWorkerIdcard(user.getIdCard());
            policyOrder.setWorkerMobile(user.getMobile());
            policyOrder.setWebsitUserId(websitUser.getId());
            policyOrder.setType("EM");
            policyOrder.insert();


        }

    }

    /**
     * 获取某天最小时间
     * @param date 时间
     * @return 获取某天最小时间
     */
    public  Date getEndOfDay(Date date) {
        LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(date.getTime()), ZoneId.systemDefault());;
        LocalTime localTime = LocalTime.of(23, 59, 59);
        LocalDateTime endOfDay = localDateTime.with(localTime);
        return Date.from(endOfDay.atZone(ZoneId.systemDefault()).toInstant());
    }

    public void task8() {

        LeConfig leConfig = leConfigService.getById("1");

        if (leLetterService.lambdaQuery().eq(LeLetter::getStatus, LetterStatusEnum.SEND.getKey())
                .le(LeLetter::getSendTime, DateUtil.offsetDay(new Date(),-1*leConfig.getDayNum()))
                .count() > 0) {
            leLetterService.lambdaUpdate().eq(LeLetter::getStatus, LetterStatusEnum.SEND.getKey())
                    .le(LeLetter::getSendTime, DateUtil.offsetDay(new Date(),-1*leConfig.getDayNum()))
                    .set(LeLetter::getExamineStatus, "OK")
                    .set(LeLetter::getExamineTime, new Date())
                    .set(LeLetter::getExamineName, "申诉截止时间已到白动批复")
                    .set(LeLetter::getStatus,LetterStatusEnum.EXECUTED.getKey()).update();
        }

        if (leConfig.getIsDay().equals(IsYesNoEnum.YES.getKey())) {

            List<LeLetterItem> letterItems = leLetterItemService.lambdaQuery().eq(LeLetterItem::getWebsitAppeal, "AP")
                    .and(item -> item.isNull(LeLetterItem::getExamineStatus).or().eq(LeLetterItem::getExamineStatus,""))
                    .le(LeLetterItem::getCreateTime, DateUtil.offsetDay(new Date(), -1 * leConfig.getCoreNum()))
                    .list();

            if (!CollectionUtils.isEmpty(letterItems)) {

                for (LeLetterItem letterItem : letterItems) {

                    letterItem.setExamineStatus("OK");
                    letterItem.setExamineTime(new Date());
                    letterItem.setExamineName("审批截止时间已到自动批复");

                    letterItem.updateById();
                    leLetterService.lambdaUpdate().eq(LeLetter::getStatus, LetterStatusEnum.WAIT_EXAMINE.getKey())
                            .eq(LeLetter::getLeLetterId,letterItem.getLeLetterId())
                            .set(LeLetter::getStatus, LetterStatusEnum.REVOKE.getKey())
                            .set(LeLetter::getExamineStatus, "OK")
                            .set(LeLetter::getExamineTime, new Date())
                            .set(LeLetter::getExamineName, "审批截止时间已到自动批复")
                            .update();

                }


            }
        }


    }
}