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.UserBrowse;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.service.UserBrowseService;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.chat.entity.ChatContent;
import com.sqx.modules.chat.entity.ChatConversation;
import com.sqx.modules.chat.service.ChatContentService;
import com.sqx.modules.chat.service.ChatConversationService;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.firstLogin.entity.ResumesDto;
import com.sqx.modules.message.entity.MessageInfo;
import com.sqx.modules.message.service.MessageService;
import com.sqx.modules.resumes.dao.ResumesDao;
import com.sqx.modules.resumes.entity.*;
import com.sqx.modules.resumes.service.*;
import com.sqx.modules.sendRecord.entity.SendRecord;
import com.sqx.modules.sendRecord.service.SendRecordService;
import com.sqx.modules.utils.SenInfoCheckUtil;
import com.sqx.modules.utils.excel.ExcelData;
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.transaction.annotation.Transactional;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 个人简历
 */
@Slf4j
@Service
public class ResumesServiceImpl extends ServiceImpl<ResumesDao, Resumes> implements ResumesService {

    @Autowired
    private ResumesDetailsService resumesDetailsService;
    @Autowired
    private UserService userService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private UserBrowseService userBrowseService;
    @Autowired
    private ViewResumesService viewResumesService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private SendRecordService sendRecordService;
    @Autowired
    private ChatConversationService conversationService;
    @Autowired
    private CommonInfoService commonInfoService;
    @Autowired
    private AuditResumesService auditResumesService;
    @Autowired
    private PostPushService pushService;
    @Autowired
    private ShieldCompanyService shieldCompanyService;
    @Autowired
    private ChatContentService chatContentService;

    @Override
    public Result insertResumes(Resumes resumes) {
        Resumes oldResumes = selectResumesByUserId(resumes.getUserId());
        if (oldResumes != null) {
            return Result.error("您已经提交过简历了，请不要重复提交！");
        }
        String format = DateUtils.format(new Date());
        resumes.setCreateTime(format);
        resumes.setUpdateTime(format);
        baseMapper.insert(resumes);

        if (resumes.getResumesCompanyList() != null && resumes.getResumesCompanyList().size() > 0) {
            for (ResumesDetails resumesDetails : resumes.getResumesCompanyList()) {
                resumesDetails.setResumesClassify(1);
                resumesDetails.setResumesId(resumes.getResumesId());
                resumesDetails.setCreateTime(format);
                resumesDetailsService.save(resumesDetails);
            }
        }
        if (resumes.getResumesWorkList() != null && resumes.getResumesWorkList().size() > 0) {
            for (ResumesDetails resumesDetails : resumes.getResumesWorkList()) {
                resumesDetails.setResumesClassify(2);
                resumesDetails.setResumesId(resumes.getResumesId());
                resumesDetails.setCreateTime(format);
                resumesDetailsService.save(resumesDetails);
            }
        }
        String value = commonInfoService.findOne(319).getValue();
        if (StringUtils.isNotEmpty(value) && "否".equals(value)) {
            auditResumes(resumes.getResumesId().toString(), "系统审核通过", 1);
        }

        return Result.success();
    }

    @Override
    public Result updateResumes(Resumes resumes) {
        String format = DateUtils.format(new Date());
        resumes.setUpdateTime(format);
        resumes.setStatus(1);
        baseMapper.updateById(resumes);
        MessageInfo messageInfo = new MessageInfo();
        messageInfo.setState("30");
        messageInfo.setIsSee("0");
        messageInfo.setContent(String.valueOf(resumes.getResumesEmail()));
        messageService.save(messageInfo);

        Resumes oldResumes = baseMapper.selectById(resumes.getResumesId());
        UserEntity userEntity = userService.selectUserById(oldResumes.getUserId());
        userService.updateById(userEntity);
        resumesDetailsService.deleteResumesDetailsByResumesId(resumes.getResumesId());
        if (resumes.getResumesCompanyList() != null && resumes.getResumesCompanyList().size() > 0) {
            for (ResumesDetails resumesDetails : resumes.getResumesCompanyList()) {
                resumesDetails.setResumesClassify(1);
                resumesDetails.setResumesId(resumes.getResumesId());
                resumesDetails.setCreateTime(format);
                resumesDetailsService.save(resumesDetails);
            }
        }
        if (resumes.getResumesWorkList() != null && resumes.getResumesWorkList().size() > 0) {
            for (ResumesDetails resumesDetails : resumes.getResumesWorkList()) {
                resumesDetails.setResumesClassify(2);
                resumesDetails.setResumesId(resumes.getResumesId());
                resumesDetails.setCreateTime(format);
                resumesDetailsService.save(resumesDetails);
            }
        }
        String value = commonInfoService.findOne(319).getValue();
        if (StringUtils.isNotEmpty(value) && "否".equals(value)) {
            auditResumes(resumes.getResumesId().toString(), "系统审核通过", 1);
        }
        return Result.success();
    }


    @Override
    public Result updateResumesStatus(Resumes resumes) {
        String format = DateUtils.format(new Date());
        resumes.setUpdateTime(format);
        baseMapper.updateById(resumes);
        Resumes oldResumes = baseMapper.selectById(resumes.getResumesId());
        UserEntity userEntity = userService.selectUserById(oldResumes.getUserId());
        if (resumes.getStatus() != null && (resumes.getStatus() == 4 || resumes.getStatus() == 1 || resumes.getStatus() == 3)) {


            userService.updateById(userEntity);
        } else if (resumes.getStatus() != null && resumes.getStatus() == 2) {
            userService.updateById(userEntity);
        }
        if ((resumes.getResumesCompanyList() != null && resumes.getResumesCompanyList().size() > 0) || ((resumes.getResumesWorkList() != null && resumes.getResumesWorkList().size() > 0))) {
            resumesDetailsService.deleteResumesDetailsByResumesId(resumes.getResumesId());
            if (resumes.getResumesCompanyList() != null && resumes.getResumesCompanyList().size() > 0) {
                for (ResumesDetails resumesDetails : resumes.getResumesCompanyList()) {
                    resumesDetails.setResumesClassify(1);
                    resumesDetails.setResumesId(resumes.getResumesId());
                    resumesDetails.setCreateTime(format);
                    resumesDetailsService.save(resumesDetails);
                }
            }

            if (resumes.getResumesWorkList() != null && resumes.getResumesWorkList().size() > 0) {
                for (ResumesDetails resumesDetails : resumes.getResumesWorkList()) {
                    resumesDetails.setResumesClassify(2);
                    resumesDetails.setResumesId(resumes.getResumesId());
                    resumesDetails.setCreateTime(format);
                    resumesDetailsService.save(resumesDetails);
                }
            }
        }


        return Result.success();
    }


    @Override
    public Result updateResumess(Resumes resumes) {
        if (resumes.getStatus().equals(2)) {
            Resumes oldResumes = baseMapper.selectById(resumes.getResumesId());
            UserEntity userEntity = userService.selectUserById(oldResumes.getUserId());
            userService.updateById(userEntity);
        }

        Resumes oldResumes = baseMapper.selectById(resumes.getResumesId());
        if (oldResumes.getIsRecommend() == null || oldResumes.getIsRecommend() == 1) {
            oldResumes.setIsRecommend(3);
            MessageInfo messageInfo = new MessageInfo();
            messageInfo.setState("60");
            messageInfo.setIsSee("0");
            messageInfo.setContent(String.valueOf(resumes.getResumesEmail()));
            messageService.save(messageInfo);
        }
        baseMapper.updateById(resumes);
        return Result.success();
    }


    @Override
    public Result deleteResumesByResumesId(Long resumesId) {
        //删除其他人的浏览记录
        userBrowseService.remove(new QueryWrapper<UserBrowse>().eq("resumes_id", resumesId));
        baseMapper.deleteById(resumesId);
        return Result.success();
    }

    @Override
    public Result selectResumesList(Integer page, Integer limit, String startTime, String endTime, Resumes resumes) {
       IPage<Resumes> resumesPage = baseMapper.selectResumesList(new Page<>(page, limit), startTime, endTime, resumes);
        List<Resumes> records = resumesPage.getRecords();
        for (Resumes record : records) {
            Long resumesId = record.getResumesId();
            resumes.setResumesCompanyList(resumesDetailsService.selectResumesDetailsList(resumesId, 1));
            resumes.setResumesWorkList(resumesDetailsService.selectResumesDetailsList(resumesId, 2));
        }
        return Result.success().put("data", new PageUtils(resumesPage));
   }
    @Override
    public Result selectResumesListHr(Integer page, Integer limit, ResumesListDto resumesDto) {
        Page<ResumesListDto> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
    List<ResumesListDto> resumesPage = baseMapper.selectResumesListHr(resumesDto) ;
    return Result.success().put("data",resumesPage);
}

    @Override
    public Result selectResumesListByCompany(Integer page, Integer limit, Long companyId, Resumes resumes, Integer screen) {
        /*List<String> companyClassify = pushService.getCompanyClassify(companyId);
        if (companyClassify.size() <= 0) {
            return Result.success().put("data", null);
        }*/
        IPage<Resumes> resumesPage = baseMapper.selectResumesListByCompany(new Page<>(page, limit), companyId, resumes, screen, null);
        for (Resumes record : resumesPage.getRecords()) {
            Long resumesId = record.getResumesId();
            record.setResumesCompanyList(resumesDetailsService.selectResumesDetailsList(resumesId, 1));
            record.setResumesWorkList(resumesDetailsService.selectResumesDetailsList(resumesId, 2));
        }
        return Result.success().put("data", new PageUtils(resumesPage));
    }


    @Override
    public Resumes selectResumesByUserId(Long userId) {
        return baseMapper.selectOne(new QueryWrapper<Resumes>().eq("user_id", userId));
    }

    @Override
    public Resumes selectResumesByResumesId(Long resumesId, Long userId, Long companyId) {
        Resumes resumes = baseMapper.selectResumesByResumesId(userId,resumesId);
        if (userId != null && resumes != null) {
            int count = userBrowseService.count(new QueryWrapper<UserBrowse>().eq("user_id", userId).eq("resumes_id", resumesId));
            if (count == 0) {
                UserBrowse userBrowse = new UserBrowse();
                userBrowse.setUserId(userId);
                userBrowse.setBrowseType(2);
                userBrowse.setResumesId(resumesId);
                userBrowse.setUpdateTime(LocalDateTime.now());
                userBrowse.setResumesUserId(resumes.getUserId());
                userBrowseService.save(userBrowse);
            }
        }

        if (userId != null && userId != 0) {
            resumes.setIsPay(0);
            Company company = companyService.selectCompanyByUserId(userId);
            if (company != null) {
                Integer viewResumes = viewResumesService.count(new QueryWrapper<ViewResumes>().eq("company_id", company.getCompanyId()).eq("resumes_id", resumesId));
                if (viewResumes != null  && viewResumes>0) {
                    resumes.setIsPay(1);
                }
            }
        }
        if (companyId != null) {
            int count = shieldCompanyService.count(new QueryWrapper<ShieldCompany>().eq("user_id", resumes.getUserId()).eq("company_id", companyId).eq("shield_type", 2));
            if (count > 0) {
                resumes.setIsShield(1);
            } else {
                resumes.setIsShield(0);
            }
        }

        resumes.setResumesCompanyList(resumesDetailsService.selectResumesDetailsList(resumesId, 1));
        resumes.setResumesWorkList(resumesDetailsService.selectResumesDetailsList(resumesId, 2));
        UserEntity userEntity = userService.selectUserById(resumes.getUserId());
        if (userEntity != null) {
            resumes.setAvatar(userEntity.getAvatar());
            resumes.setUserName(userEntity.getUserName());
        }
        return resumes;
    }

    @Override
    public Resumes selectResumesByResumesIds(Long resumesId) {
        Resumes resumes = baseMapper.selectById(resumesId);
        if (resumes != null) {
            resumes.setResumesCompanyList(resumesDetailsService.selectResumesDetailsList(resumesId, 1));
            resumes.setResumesWorkList(resumesDetailsService.selectResumesDetailsList(resumesId, 2));
            UserEntity userEntity = userService.selectUserById(resumes.getUserId());
            if (userEntity != null) {
                resumes.setUserName(userEntity.getUserName());
                resumes.setAvatar(userEntity.getAvatar());
            }
        }
        return resumes;
    }

    @Override
    public Result refreshResumes(Long userId, Long resumesId) {
        UserEntity userEntity = userService.getById(userId);
        if (userEntity.getUserRefreshCount() > 0) {
            Resumes resumes = baseMapper.selectById(resumesId);
            resumes.setUpdateTime(DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));
            baseMapper.updateById(resumes);
            userEntity.setUserRefreshCount(userEntity.getUserRefreshCount() - 1);
            userService.updateById(userEntity);
            return Result.success();
        } else {
            return Result.error("今日可刷新次数已用完");
        }

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result sendResumes(Long userId, Long to, Long postPushId) {
        Resumes resumes = baseMapper.selectOne(new QueryWrapper<Resumes>().eq("user_id", userId));
        Company company = companyService.getOne(new QueryWrapper<Company>().eq("user_id", to));
        sendEmail(resumes.getResumesId(), company.getEmail(), resumes.getResumesName());
        SendRecord sendRecord = new SendRecord();
        sendRecord.setUserId(userId);
        sendRecord.setCompanyUserId(to);
        sendRecord.setStatus(1);
        sendRecord.setCompanyId(company.getCompanyId());
        sendRecord.setCreateTime(LocalDateTime.now());
        sendRecord.setUpdateTime(LocalDateTime.now());
        sendRecord.setPostPushId(postPushId);
        sendRecordService.save(sendRecord);
        //设置聊天回话 发送简历
        ChatConversation conversation = conversationService.getOne(new QueryWrapper<ChatConversation>().eq("user_id", userId).eq("focused_user_id", to));
        conversation.setIsSendResumes(1);
        conversationService.updateById(conversation);

        ChatContent chatContent = new ChatContent();
        chatContent.setChatConversationId(conversation.getChatConversationId());

        chatContent.setMessageType("10");
        chatContent.setUserId(userId);
        chatContent.setStatus(1);
        chatContent.setContent("简历已发送");
        chatContent.setCreateTime(DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));
        chatContentService.save(chatContent);

        ChatContent content = new ChatContent();
        content.setContent("简历请求已同意");
        chatContentService.update(content, new QueryWrapper<ChatContent>()
                .eq("chat_conversation_id",conversation.getChatConversationId()).eq("content", "简历请求"));

        chatContent.setContent("已收到简历");
        chatContent.setUserId(to);
        chatContentService.save(chatContent);

        MessageInfo messageInfo = new MessageInfo();
        messageInfo.setContent("您的企业邮箱收到了一封简历");
        messageInfo.setTitle("系统通知");
        messageInfo.setState(String.valueOf(4));
        messageInfo.setUserId(String.valueOf(to));
        messageInfo.setCreateAt(DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));
        messageInfo.setIsSee("0");
        messageService.saveBody(messageInfo);
        return Result.success();
    }

    @Override
    public ExcelData exportExcelResumesList(String startTime, String endTime, Resumes resumes) {
        List<Resumes> resumesList = baseMapper.exportExcelCompanyList(startTime, endTime, resumes);
        ExcelData data = new ExcelData();
        data.setName("简历列表");
        List<String> titles = new ArrayList<>();
        titles.add("编号");
        titles.add("姓名");
        titles.add("性别");
        titles.add("年龄");
        titles.add("电话");
        titles.add("学历");
        titles.add("婚姻状态");
        titles.add("期望薪资");
        titles.add("电子邮件");
        titles.add("工作经验");
        titles.add("求职岗位");
        titles.add("自我介绍");
        titles.add("用户名称");
        titles.add("状态");
        titles.add("更新时间");
        titles.add("创建时间");
        titles.add("审核内容");
        titles.add("学校");
        titles.add("毕业时间");
        titles.add("是否推荐");
        titles.add("意向城市");
        titles.add("家庭住址");
        titles.add("求职状态");
        titles.add("行业");
        data.setTitles(titles);
        List<List<Object>> rows = new ArrayList<>();
        for (Resumes res : resumesList) {
            List<Object> row = new ArrayList<>();
            row.add(res.getResumesId());
            row.add(res.getResumesName());
            if (res.getResumesSex() == 1) {
                row.add("男");
            } else {
                row.add("女");
            }


            row.add(res.getResumesAge());
            row.add(res.getResumesPhone());
            row.add(res.getResumesEducation());
            row.add(res.getResumesMarriage());
            row.add(res.getResumesCompensation());
            row.add(res.getResumesEmail());
            row.add(res.getResumesWorkExperience());
            row.add(res.getResumesPost());
            row.add(res.getResumesDetails());
            UserEntity userEntity = userService.getById(res.getUserId());
            if (userEntity != null && StringUtils.isNotBlank(userEntity.getUserName())) {
                row.add(userEntity.getUserName());
            } else {
                row.add("用户已注销");
            }
            if (res.getStatus() == 1) {
                row.add("待审核");
            } else if (res.getStatus() == 2) {
                row.add("正常");
            } else if (res.getStatus() == 3) {
                row.add("拒绝");
            } else if (res.getStatus() == 4) {
                row.add("已入职");
            }
            row.add(res.getUpdateTime());
            row.add(res.getCreateTime());
            row.add(res.getAuditContent());
            row.add(res.getSchool());
            row.add(res.getGraduationTime());
            if (res.getIsRecommend() != null) {
                if (res.getIsRecommend() == 1) {
                    row.add("否");
                } else {
                    row.add("是");
                }
            } else {
                row.add("否");
            }


            row.add(res.getCity());
            row.add(res.getAddress());

            if (res.getResumesStatus() == 1) {
                row.add("离职-正在找工作");
            } else if (res.getResumesStatus() == 2) {
                row.add("在职-考虑机会");
            } else if (res.getResumesStatus() == 3) {
                row.add("在职-暂不考虑");
            }

            row.add(res.getIndustryName());
            rows.add(row);
        }
        data.setRows(rows);
        return data;

    }

    @Override
    public Result checkPower(Long resumesId, Long userId) {
        HashMap<String, Object> hashMap = new HashMap<>();
        UserEntity userEntity = userService.getById(userId);
        if (userEntity == null) {
            return Result.error("用户信息已失效,请登录后重试");
        }
        Company company = companyService.getOne(new QueryWrapper<Company>().eq("user_id", userId));
        if (company == null) {
            return Result.error("公司信息不存在");
        }
        int vipCount = Integer.parseInt(commonInfoService.findOne(421).getValue());

        int plainCount = Integer.parseInt(commonInfoService.findOne(422).getValue());

        BigDecimal vipMoney = new BigDecimal(commonInfoService.findOne(419).getValue());

        BigDecimal plainMoney = new BigDecimal(commonInfoService.findOne(420).getValue());

        int count = viewResumesService.getUseCount(company.getCompanyId());

        hashMap.put("nowCount", count);
        if (userEntity.getIsCompanyVip()!=null && userEntity.getIsCompanyVip() == 1) {
            hashMap.put("type", 1);
            hashMap.put("maxCount", vipCount);
            hashMap.put("money", vipMoney);
        } else {
            hashMap.put("type", 2);
            hashMap.put("maxCount", plainCount);
            hashMap.put("money", plainMoney);


        }
        return Result.success().put("data", hashMap);
    }

    @Override
    public Result updateShow(Long resumesId) {
        Resumes resumes = baseMapper.selectById(resumesId);
        if (resumes==null){
            return Result.error("简历不存在");
        }else {
            if (resumes.getIsShow()==1){
                resumes.setIsShow(0);
            }else {
                resumes.setIsShow(1);
            }
            return Result.upStatus(baseMapper.updateById(resumes));
        }


    }

    public void sendEmail(Long resumesId, String to, String resumesName) {
        // 收件人电子邮箱
        //String to = "2652276852@qq.com";

        // 发件人电子邮箱
        String from = commonInfoService.findOne(308).getValue();

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

        // 获取系统属性
        //Properties properties = System.getProperties();
        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");
        /*//协议
        properties.setProperty("mail.transport.protocol", "smtp");
        //服务器
        properties.setProperty("mail.smtp.host", "smtp.163.com");
        //端口
        properties.setProperty("mail.smtp.port", "465");
        //使用smtp身份验证
        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("收到一封投递简历：" + resumesName + "，请您查收！");

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

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

            // 邮件信息组装
            //组装的顺序非常重要，一定要先组装文本域，再组装文件
            MimeBodyPart htmlPart = new MimeBodyPart();
            // 组装内容
            htmlPart.setContent("收到一封简历投递：" + resumesName + "，请您查收！", "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 = 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());
        dataMap.put("resumesMajor", resumes.getMajor());
        dataMap.put("resumesIntention", resumes.getCity());
        dataMap.put("resumesPost", resumes.getResumesPost());
        dataMap.put("school", resumes.getSchool());
        Map<String, String> imgMap = new HashMap<>();
        if (StringUtils.isNotEmpty(resumes.getResumesImage())) {
            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);
        }
        //项目经验
        //表格 一行数据是一个list
        List<List<String>> resumesWorkList = new ArrayList<>();
        //一行输出三十字 不能超过三十行  每一个项目占用一行
        for (ResumesDetails resumesDetails : resumes.getResumesWorkList()) {
            List<String> list2 = new ArrayList<>();
            String title = resumesDetails.getResumesTitle() + "       " + resumesDetails.getResumesPost() + "       " + resumesDetails.getResumesTime();
            list2.add(title);
            resumesWorkList.add(list2);
            list2 = new ArrayList<>();
            String resumesContent = resumesDetails.getResumesContent();
            list2.add(resumesContent);
            resumesWorkList.add(list2);
        }


        List<List<String>> resumesDetails = new ArrayList<>();
        ArrayList<String> strings = new ArrayList<>();
        strings.add(resumes.getResumesDetails());
        resumesDetails.add(strings);


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

        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(), DateUtils.DATE_PATTERN);
            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;
    }

    @Override
    public Result auditResumes(String ids, String content, Integer status) {
        String format = DateUtils.format(new Date());
        String value = commonInfoService.findOne(310).getValue();
        for (String id : ids.split(",")) {
            Resumes resumes = baseMapper.selectById(Long.parseLong(id));
            if (resumes.getStatus().equals(1)) {

                AuditResumes auditResumes = new AuditResumes();
                auditResumes.setResumesId(resumes.getResumesId());
                auditResumes.setCreateTime(format);
                UserEntity userEntity = userService.selectUserById(resumes.getUserId());
                MessageInfo messageInfo = new MessageInfo();
                messageInfo.setContent(content);
                messageInfo.setTitle("简历审核通知");
                messageInfo.setState(String.valueOf(5));
                messageInfo.setUserName(userEntity.getUserName());
                messageInfo.setUserId(String.valueOf(userEntity.getUserId()));
                messageInfo.setCreateAt(format);
                messageInfo.setIsSee("0");

                List<String> msgList = new ArrayList<>();
                msgList.add("简历审核通知");
                if (status == 1) {
                    resumes.setStatus(2);
                    resumes.setAuditContent("审核通过");
                    messageInfo.setContent("审核通过");
                    auditResumes.setAuditContent("审核通过");
                    msgList.add("审核通过");
                } else {
                    resumes.setStatus(3);
                    resumes.setAuditContent(content);
                    auditResumes.setAuditContent(content);
                    msgList.add("审核失败，请前往简历详情查看原因！");
                }
                userService.updateById(userEntity);
                messageService.saveBody(messageInfo);
                msgList.add(DateUtils.format(new Date()));
                SenInfoCheckUtil.sendMsg(userEntity.getOpenId(), value, msgList, 3, null);
                if (StringUtils.isNotEmpty(userEntity.getClientid())) {
                    userService.pushToSingle(messageInfo.getTitle(), messageInfo.getContent(), userEntity.getClientid());
                }
                baseMapper.updateById(resumes);
                auditResumesService.save(auditResumes);
            }
        }
        return Result.success();
    }


}
