package com.dxhy.core.task;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.dxhy.common.util.MD5;
import com.dxhy.core.model.mailGather.OcrResultToyxVo;
import com.dxhy.core.model.openservice.OpenServiceOcr;
import com.dxhy.core.service.openservice.impl.OpenServicePlatformServiceImpl;
import com.dxhy.core.util.EmailParseUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.Test;

import javax.mail.*;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Properties;

class SnEmailGatherTaskTest {

    @Test
    void parseEmail() {
        //邮件接收协议
        String mail_protocol = "mail.store.protocol";
        //邮件接收协议类型
        String mail_protocol_type2 = "pop3";
        String mail_protocol_type = "pop";
        //邮件接收服务器端口
        String mail_port = "mail.pop3.port";
        //邮件接收服务器端口
        String port = "110";
        //邮件接收服务器地址
        String mail_host = "mail.pop3.host";
        String emailName = "745139984@qq.com";
        String password = "ncmydeiilzyabfgb";
        String mailSuffix = emailName.split("@")[1];
        //邮箱类型
        String mailType = mailSuffix.split("\\.")[0];
        Properties props = new Properties();
        if(mailType.equalsIgnoreCase("qq")){
            //qq邮箱
            props.setProperty(mail_protocol, mail_protocol_type2); // 协议
            props.setProperty(mail_host, mail_protocol_type+"."+mailSuffix); // pop3服务器
            props.setProperty(mail_port, port); // 端口
        }else {
            props.setProperty(mail_protocol, mail_protocol_type2); // 协议
            props.setProperty(mail_host, mail_protocol_type2+"."+mailSuffix); // pop3服务器
            props.setProperty(mail_port, port); // 端口
        }
        Session session = Session.getInstance(props);
        Store store = null;
        try {
            store = session.getStore("pop3");
            store.connect(emailName, password);
            //连接邮箱服务器
            //获取当前时间
//            Date currentTime = new Date();
            // 品 ping获得收件箱    pop3协议只有一个有效的文件夹就是INBOX
            Folder folder = store.getFolder("INBOX");
            //获取邮件列表
            folder.open(Folder.READ_WRITE);
            // 由于POP3协议无法获知邮件的状态,所以getUnreadMessageCount得到的是收件箱的邮件总数
            System.out.println("未读邮件数: " + folder.getUnreadMessageCount());
            // 由于POP3协议无法获知邮件的状态,所以下面得到的结果始终都是为0
            System.out.println("删除邮件数: " + folder.getDeletedMessageCount());
            System.out.println("新邮件: " + folder.getNewMessageCount());
            // 获得收件箱中的邮件总数
            System.out.println("邮件总数: " + folder.getMessageCount());

//            Calendar calendar = Calendar.getInstance();
//            // 搜索1天前到今天收到的的所有邮件，根据时间筛选邮件
//            calendar.add(Calendar.DAY_OF_MONTH, -1);
//            // 创建ReceivedDateTerm对象，ComparisonTerm.GE（大于等于），Date类型的时间 new Date(calendar.getTimeInMillis())----（表示1天前）
//            SentDateTerm term = new SentDateTerm(ComparisonTerm.LE, new Date(calendar.getTimeInMillis()));
//            Message[] messages = folder.search(term);
            Message[] messages = folder.getMessages();
            for (int i = 0, count = messages.length; i < count; i++) {
                MimeMessage msg = (MimeMessage) messages[i];
                System.out.println("------------------解析第" + msg.getMessageNumber() + "封邮件-------------------- ");
                System.out.println("主题: " + EmailParseUtils.getSubject(msg));
                System.out.println("发件人: " + EmailParseUtils.getFrom(msg));
//                System.out.println("收件人：" + EmailParseUtils.getReceiveAddress(msg, null));
                System.out.println("发送时间：" + EmailParseUtils.getSentDate(msg, null));
                System.out.println("是否已读：" + EmailParseUtils.isSeen(msg));
                System.out.println("邮件优先级：" + EmailParseUtils.getPriority(msg));
                System.out.println("是否需要回执：" + EmailParseUtils.isReplySign(msg));
                System.out.println("邮件大小：" + msg.getSize() * 1024 + "kb");
                boolean isContainerAttachment = EmailParseUtils.isContainAttachment(msg);
                System.out.println("是否有附件： "+isContainerAttachment);
                if(isContainerAttachment) {
                    List<Map<String, String>> mapList = Lists.newArrayList();
                    EmailParseUtils.saveAttachment(msg, mapList);
                    for (Map<String, String> map : mapList) {
                        map.put("emailName",emailName);
                        String pdfStream = map.get("pdfStream");
                        if(StringUtils.isNotBlank(pdfStream)){
                            List<OpenServiceOcr> openServiceOcrs = OpenServicePlatformServiceImpl.OcrToSnTest(pdfStream);
                            if(openServiceOcrs != null && !openServiceOcrs.isEmpty()){
                                Map<String, Object> ocrResult = convertToOcrResult(openServiceOcrs, map);

                                String salt = "e4b0190b2fadc0adbe54471ffd79a729";
                                try {

                                    String md5Encode = MD5.getMd5Encode(ocrResult.get("batchId") + salt);
                                    Map<String, String> hashMap = Maps.newHashMap();
                                    hashMap.put("Authorization",md5Encode);
                                    String body = HttpRequest.post("http://192.168.33.105:2333/ticket/receive").addHeaders(hashMap).body(JSONObject.toJSONString(ocrResult)).timeout(300000).execute().body();

                                    Map resultMap = JSONObject.parseObject(body, Map.class);
                                    Object status = resultMap.get("status");
                                    System.out.println(JSONObject.toJSONString("================="+resultMap));
                                    if(status != null && "200".equals(String.valueOf(status))){

                                    }
                                    System.out.println(body);
                                } catch (NoSuchAlgorithmException e) {
                                    throw new RuntimeException(e);
                                }

                            }
                        }
                        System.out.println("");
                    }

                }
//                POP3Folder inbox = (POP3Folder) folder;
//                String uid = inbox.getUID(msg);
//                System.out.println("uid: ------------------" + uid);
//                Flags flags = msg.getFlags();
//                if (!flags.contains(Flags.Flag.SEEN)) {
//                    //设置为已读
//                    msg.setFlag(Flags.Flag.SEEN, true);
//                }
                System.out.println("");
            }
            System.out.println("");
//            Date endTime = new Date();
            //计算耗时时间
//        double elapsedTime = CalendarUtil.arithDateTime(endTime, currentTime);
            // 释放资源
            folder.close(false); // false为不更新邮件，true为更新，一般在删除邮件后使用
            store.close();
        } catch (NoSuchProviderException e) {
            throw new RuntimeException(e);
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static Map<String, Object> convertToOcrResult(List<OpenServiceOcr> openServiceOcrs, Map<String, String> map){
        List<OcrResultToyxVo> resultToyxVoList = Lists.newArrayList();
        Map<String, Object> hashMap = Maps.newHashMap();
        String batchId = String.valueOf(System.currentTimeMillis());
        hashMap.put("batchId",batchId);

        for (int i = 0; i < openServiceOcrs.size(); i++) {
            OpenServiceOcr openServiceOcr = openServiceOcrs.get(i);
            OpenServiceOcr.InvoiceOcrData invoiceOcrData = openServiceOcr.getData();
            OcrResultToyxVo resultToyxVo = new OcrResultToyxVo();
            resultToyxVo.setCompanyId("c040");
            resultToyxVo.setSource("01");
            resultToyxVo.setInvoiceCode(invoiceOcrData.getFPDM());
            resultToyxVo.setInvoiceNumber(invoiceOcrData.getFPHM());
            resultToyxVo.setTotalAmount(invoiceOcrData.getJSHJ());
            resultToyxVo.setBuyerName(invoiceOcrData.getGMFMC());
            resultToyxVo.setSellerName(invoiceOcrData.getXHFMC());
            resultToyxVo.setFileName(map.get("fileName"));
            resultToyxVo.setFileType("102");
            resultToyxVo.setFileByte(map.get("pdfStream"));
            resultToyxVo.setEmail(map.get("emailName"));
            resultToyxVo.setEmployeeId("01142085");

            resultToyxVoList.add(resultToyxVo);
        }
        hashMap.put("list",resultToyxVoList);


        return hashMap;
    }

    public static Map<String, String> convertInvoiceType(){
        Map<String, String> map = Maps.newHashMap();
        //10	增值税专用发票,11	增值税普通发票 ,12	增值税电子普通发票 ,13	增值税普通发票(卷票),
        // 14	机动车销售统一发票,15	二手车销售统一发票,16	定额发票,17	机打发票,18	出租车发票 ,
        // 19	火车票 ,20	客运汽车,21	航空运输电子客票行程单 ,22	过路费发票 ,
        // 24	增值税电子普通发票(通行费)25	增值税电子专用发票,26	电子发票（增值税专用发票） ,
        // 27	电子发票（普通发票）,28	船票	区块链发票   海关缴款书
        //增值税专用发票: 01,增值税普通发票:04,增值税电子专用发票：08,增值税普通发票(电子):10,
        // 增值税普通发票(卷式):11,通行费发票:14,出租车票:91,火车票:92,飞机票:93,汽车票:94,
        // 定额发票:95,国际小票:96,通用机打票:97,过路过桥:98,机动车销售统一发票:03,二手车销售统一发票:15,
        // 可报销其他发票:85,滴滴出行行程单:86,完税证明:87,船票:88,其他:00
        map.put("01","10");
        map.put("04","11");
        map.put("10","12");
        map.put("11","13");
        map.put("03","14");
        map.put("15","15");
        map.put("95","16");
        map.put("96","17");
        map.put("91","18");
        map.put("92","19");
        map.put("94","20");
        map.put("93","21");
        map.put("","22");
        map.put("14","24");
        map.put("04","25");
        map.put("31","26");
        map.put("32","27");
        map.put("88","28");
        return map;
    }

    @Test
    void mailAuth() {
    }

    public static void main(String[] args) throws NoSuchAlgorithmException {
        String value = String.valueOf(System.currentTimeMillis());
        System.out.println(value);
        String str = "1680510212905" + "e4b0190b2fadc0adbe54471ffd79a729";
        String encode = MD5.getMd5Encode(str);
        if("acec779e6689227e4ede6d1a513d94b0".equals(encode)){
            System.out.println("");
        }
        cn.hutool.crypto.digest.MD5 md5 = cn.hutool.crypto.digest.MD5.create();
        System.out.println();
    }
}