package com.sqx.modules.resumes.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sqx.common.utils.DateUtils;
import com.sqx.common.utils.PageUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.entity.UserMoneyDetails;
import com.sqx.modules.app.service.UserMoneyDetailsService;
import com.sqx.modules.app.service.UserMoneyService;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.resumes.dao.ResumesPushDao;
import com.sqx.modules.resumes.dao.RuleClassifyDao;
import com.sqx.modules.resumes.entity.*;
import com.sqx.modules.resumes.service.*;
import com.sqx.modules.utils.SenInfoCheckUtil;
import com.sqx.modules.utils.pdf.CreatePDFMainTest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestAttribute;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;

/**
 *
 */
@Slf4j
@Service
public class ResumesPushServiceImpl extends ServiceImpl<ResumesPushDao, ResumesPush> implements ResumesPushService {

    @Autowired
    private ResumesService resumesService;
    @Autowired
    private PostDetailsService postDetailsService;
    @Autowired
    private UserService userService;
    @Autowired
    private PostPushService postPushService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private UserMoneyDetailsService userMoneyDetailsService;
    @Autowired
    private UserMoneyService userMoneyService;
    @Autowired
    private ViewResumesService viewResumesService;
    @Autowired
    private CommonInfoService commonInfoService;



    @Override
    public ResumesPush selectResumesPushByUserId(Long resumesId,Long postPushId,Long postDetailsId,Integer classify){
        return baseMapper.selectOne(new QueryWrapper<ResumesPush>()
                .eq("resumes_id",resumesId)
                .eq("post_push_id",postPushId)
                .eq("classify",classify)
                .eq("post_details_id",postDetailsId));
    }

    @Override
    public void sendEmail(Long resumesId, String to, String postName, String postDetailsName){
        // 发件人电子邮箱
        String from = commonInfoService.findOne(308).getValue();

        // 指定发送邮件的主机为
        String host = commonInfoService.findOne(427).getValue();;

        // 获取系统属性
        Properties properties = new Properties();
        properties.setProperty("mail.smtp.host", host);
        properties.setProperty("mail.smtp.port", "465");
        properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        // 邮件发送协议
        properties.setProperty("mail.transport.protocol", "smtp");
        //是否启用调试模式（启用调试模式可打印客户端与服务器交互过程时一问一答的响应消息）
        properties.setProperty("mail.debug","true");
        properties.setProperty("mail.smtp.auth", "true");
        // 获取默认session对象
        Session session = Session.getDefaultInstance(properties,new Authenticator(){
            @Override
            public PasswordAuthentication getPasswordAuthentication()
            {
                //发件人邮件用户名、授权码，换成自己的发件箱及授权码
                return new PasswordAuthentication(from, commonInfoService.findOne(309).getValue());
            }
        });

        try{
            // 创建默认的 MimeMessage 对象
            MimeMessage message = new MimeMessage(session);

            // Set From，设置发件人
            InternetAddress fromMail = new InternetAddress(from);
            //设置发件人名称
            String name = commonInfoService.findOne(12).getValue();
            fromMail.setPersonal(MimeUtility.encodeText(name+"<"+from+">"));
            message.setFrom(fromMail);

            // Set To: 设置收件人
            InternetAddress toMail = new InternetAddress(to);
            //发多个邮箱
            Address[] allRecipients = {toMail};
            message.setRecipients(Message.RecipientType.TO, allRecipients);

            // Set Subject: 邮件主体
            message.setSubject("收到一封简历投递，请您查收！");

            // 设置消息体
            message.setSentDate(new Date());

            // 指定为混合关系
            MimeMultipart msgMultipart = new MimeMultipart("mixed");
            message.setContent(msgMultipart);

            // 邮件信息组装
            //组装的顺序非常重要，一定要先组装文本域，再组装文件
            MimeBodyPart htmlPart = new MimeBodyPart();
            // 组装内容
            htmlPart.setContent("精准推送简历，项目："+postName+"，岗位："+postDetailsName, "text/html;charset=UTF-8");
            msgMultipart.addBodyPart(htmlPart);

            // 组装附件
            MimeBodyPart filePart = new MimeBodyPart();
            //自己的附件地址
            String url = exportPdf(resumesId);
            if(StringUtils.isNotEmpty(url)){
                FileDataSource file_datasource = new FileDataSource(url);
                DataHandler dh = new DataHandler(file_datasource);
                filePart.setDataHandler(dh);
                // 附件区别内嵌内容的一个特点是有文件名，为防止中文乱码要编码
                filePart.setFileName(MimeUtility.encodeText(dh.getName()));
                msgMultipart.addBodyPart(filePart);

                message.saveChanges();
                //发送
                //Transport.send(message, message.getAllRecipients());
                Transport.send(message);
                log.error("Sent mail successfully....");
            }else{
                log.error("生成简历失败");
            }
        }catch (Exception e ) {
            log.error("发送邮件异常："+e.getMessage(),e);
        }
    }



    public String exportPdf(Long resumesId) {
        String http = commonInfoService.findOne(19).getValue();
        String[] split = http.split("://");
        Resumes resumes = resumesService.selectResumesByResumesIds(resumesId);
        // 模板路径
//        String tempPath = "/www/wwwroot/"+split[1]+"/service/demo.pdf";
        String tempPath = "/www/wwwroot/"+split[1]+"/service/demo.pdf";

        //文字类
        Map<String, String> dataMap = new HashMap<>();
        // dataMap中的key要和模板中的域名对应
        dataMap.put("resumesName", resumes.getResumesName());
        dataMap.put("resumesAge", resumes.getResumesAge());
        dataMap.put("resumesPhone", resumes.getResumesPhone());
        dataMap.put("resumesEducation", resumes.getResumesEducation());
        dataMap.put("resumesMarriage", resumes.getResumesMarriage());
        dataMap.put("resumesCompensation", resumes.getResumesCompensation());
        dataMap.put("resumesEmail", resumes.getResumesEmail());
        dataMap.put("resumesWorkExperience", resumes.getResumesWorkExperience());
        String resumesIntention=resumes.getResumesIntention();
        if(StringUtils.isNotEmpty(resumes.getCity())){
            resumesIntention=resumesIntention+"，"+resumes.getCity();
        }
        dataMap.put("resumesIntention", resumesIntention);
        dataMap.put("resumesMajor", resumes.getResumesMajor());
        dataMap.put("resumesPost", resumes.getResumesPost());
        dataMap.put("resumesDetails", resumes.getResumesDetails());
        dataMap.put("school", resumes.getSchool());
        Map<String, String> imgMap = new HashMap<>();
        String[] split1 = resumes.getResumesImage().split(",");
        if(split1.length>0){
            for(int i=0;i<split1.length;i++){
                if(StringUtils.isNotEmpty(split1[i])){
                    String replace = split1[i].replace("https", "http");
                    imgMap.put("image" + (i + 1), replace);
                }
            }
        }
        //表格 一行数据是一个list
        List<List<String>> resumesCompanyList = new ArrayList<>();
        for(ResumesDetails resumesDetails:resumes.getResumesCompanyList()){
            List<String> list2 = new ArrayList<>();
            list2.add(resumesDetails.getResumesTitle()+"       "+resumesDetails.getResumesPost()+"       "+resumesDetails.getResumesTime());
            resumesCompanyList.add(list2);
            list2 = new ArrayList<>();
            String resumesProject = resumesDetails.getResumesProject();
            if(StringUtils.isNotEmpty(resumesProject)){
                list2.add(resumesProject);
                resumesCompanyList.add(list2);
            }
            list2 = new ArrayList<>();
            String resumesContent = resumesDetails.getResumesContent();
            list2.add(resumesContent);
            resumesCompanyList.add(list2);
        }

        Map<String, List<List<String>>> listMap = new HashMap<>();
        // 这里的listMap中key要和模板中的域名对应
        listMap.put("resumesCompanyList", resumesCompanyList);


        Map<String, Object> o = new HashMap<>();
        o.put("tempPath", tempPath);
        o.put("dataMap", dataMap);
        o.put("imgMap", imgMap);
        o.put("tableList", listMap);
        try {
            String date = DateUtils.format(new Date());
            String fileName=resumes.getResumesName()+","+date+".pdf";
            // 上传文件路径
            String filePath ="/www/wwwroot/"+split[1]+"/file/uploadPath";
            fileName=filePath+"/"+fileName;
            FileOutputStream fos = new FileOutputStream(fileName,true);
            try {
                CreatePDFMainTest.creatPdf(o, fos);
            } catch (Exception e) {
                e.printStackTrace();
            }
            fos.flush();
            fos.close();
            return fileName;
        } catch (IOException e) {
            e.printStackTrace();
            log.error("生成简历异常："+e.getMessage(),e);
        }
        return null;
    }



}
