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

import cn.hutool.core.bean.BeanUtil;
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.enums.*;
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.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 org.apache.http.client.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.mail.MessagingException;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class AgreementLogic {

    @Autowired
    PolicyCMapper policyCMapper;

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


    @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;


    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();


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

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

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

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


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

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


    }

    private void sendEmailFileIn(List<MailboxSendRecordPolicy> mailboxSendRecordPolicies, MailboxSendRecord mailboxSendRecord, Mailbox mailbox) 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 = "/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));
        ExcelUtils.createExcel(filePath, excelData);
        File excel = new File(filePath);

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

        //分发邮件

        for (String s : mailboxSendRecord.getReceiveMailbox().split(",|，")) {
            emailUtilsNew.send(s, 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) 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));
        ExcelUtils.createExcel(filePath, excelData);
        File excel = new File(filePath);

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

        //分发邮件

        for (String s : mailboxSendRecord.getReceiveMailbox().split(",|，")) {
            emailUtilsNew.send(s, 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) 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);

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

        //分发邮件

        for (String s : mailboxSendRecord.getReceiveMailbox().split(",|，")) {
            emailUtilsNew.send(s, 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);
    }

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


        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> 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)) {
            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(mailboxSendRecord.getCompanyWechatId());
                mailboxSendRecordPolicy.setCompanyWechatId(mailboxSendRecord.getCompanyWechatName());
                mailboxSendRecordPolicy.setPolicyNumber(policyOrder.getPolicyId());
                mailboxSendRecordPolicy.setPolicyName(policyOrder.getWorkerName());
                mailboxSendRecordPolicy.setWebsitName(policyOrder.getWebsitName());
                mailboxSendRecordPolicy.setWebsitId(policyOrder.getWebsitId());
                mailboxSendRecordPolicy.setPolicyMobile(policyOrder.getWorkerMobile());
                mailboxSendRecordPolicy.setPolicyNumber(policyOrder.getWorkerNumber());
                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.updateById();
            }

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

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


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

        if (!CollectionUtils.isEmpty(policyOrders)) {
            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.setCompanyWechatId(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.setPolicyNumber(policyOrder.getWorkerNumber());
                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.updateById();
            }

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

            //发邮件
            try {
                this.sendEmailFileEm(mailboxSendRecordPolicies, mailboxSendRecord, mailbox);
                mailboxSendRecord.setSendStatus("OK");
                mailboxSendRecord.setSendTime(new Date());
                mailboxSendRecord.updateById();
            } catch (Exception e) {
                mailboxSendRecord.setSendStatus("NO");
                mailboxSendRecord.setSendTime(new Date());
                mailboxSendRecord.updateById();
            }
        }
        //工伤保险发送邮件
        for (MailboxReceive mailboxReceive : mailboxReceives) {
            List<PolicyOrder> policyOrdersIn = policyOrderService.lambdaQuery()
                    .eq(PolicyOrder::getType, PolicyTypeEnum.IN.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.setCompanyWechatId(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.setPolicyNumber(policyOrder.getWorkerNumber());
                    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.updateById();
                }

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

                //发邮件
                try {
                    this.sendEmailFileIn(mailboxSendRecordPolicies, mailboxSendRecord, mailbox);
                    mailboxSendRecord.setSendStatus("OK");
                    mailboxSendRecord.setSendTime(new Date());
                    mailboxSendRecord.updateById();
                } 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 rece = new EmailUtilsNew(mailbox.getSendMailbox(), mailbox.getSendPassword())
                    .receEmail(mailbox.getAccidentMailbox(), mailboxSendRecord.getSendBatch());

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

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



            if (rece) {


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


                if (mailboxSendRecord.getPolicyType().equals(PolicyTypeEnum.AC.getKey())) {
                    policyOrderService.lambdaUpdate()
                            .in(PolicyOrder::getId, policyOrderId)
                            .le(PolicyOrder::getStartTime, new Date())
                            .ge(PolicyOrder::getEndTime, new Date())
                            .set(PolicyOrder::getPolicyOrderStatus, PolicyOrderEmStutasEnum.BZZ.getKey()).update();
                    workerPolicyService.lambdaUpdate()
                            .in(WorkerPolicy::getOrderId, policyOrderId)
                            .le(WorkerPolicy::getStartTime, new Date())
                            .ge(WorkerPolicy::getEndTime, new Date())
                            .set(WorkerPolicy::getStatus, "BZZ").update();
                }


                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, DateUtil.endOfDay(DateUtil.offsetMonth(new Date(), 12)))
                            .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) {
                        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(DateUtil.endOfDay(DateUtil.offsetMonth(new Date(), 12)));
                        workerPolicy.setWebsitUserId(policyOrder.getWebsitUserId());
                        workerPolicy.setWebsitId(policyOrder.getWebsitId());
                        workerPolicy.setWebsitName(policyOrder.getWebsitName());
                        workerPolicy.setWorkerName(policyOrder.getWorkerName());
                        workerPolicies.add(workerPolicy);
                    }
                    workerPolicyService.saveBatch(workerPolicies);

                }


                if (mailboxSendRecord.getPolicyType().equals(PolicyTypeEnum.IN.getKey())) {
                    //将今天的工伤险都收到回执
                    policyOrderService.lambdaUpdate()
                            .in(PolicyOrder::getId, policyOrderId)
                            .set(PolicyOrder::getPolicyOrderStatus, PolicyOrderEmStutasEnum.DSX.getKey()).update();
                }


            }

        }

    }

    public void offInsure() {

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

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


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

        if (!CollectionUtils.isEmpty(list)) {
            workerPolicyService.lambdaUpdate()
                    .ge(WorkerPolicy::getEndTime, 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, new Date())
                .le(PolicyOrder::getStartTime, new Date())
                .eq(PolicyOrder::getIsReceipt, IsYesNoEnum.YES.getKey())
                .ne(PolicyOrder::getPolicyOrderStatus, PolicyOrderStatusEnum.BZZ.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();
            }
        }

    }

    public void huizhi() {
    }
}
