package com.qmth.distributed.print.business.util;

import com.qmth.distributed.print.business.bean.marking.ConvertJpgStorage;
import com.qmth.distributed.print.business.entity.BasicCardRule;
import com.qmth.distributed.print.business.entity.ExamCard;
import com.qmth.distributed.print.business.entity.ExamCardDetail;
import com.qmth.distributed.print.business.enums.MakeMethodEnum;
import com.qmth.distributed.print.business.service.PrintCommonService;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.entity.BasicAttachment;
import com.qmth.teachcloud.common.enums.CardCreateMethodEnum;
import com.qmth.teachcloud.common.enums.ExceptionResultEnum;
import com.qmth.teachcloud.common.enums.PageSizeEnum;
import com.qmth.teachcloud.common.enums.UploadFileEnum;
import com.qmth.teachcloud.common.util.ConvertUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.entity.ContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Description: 题卡html转化为
 * @Author: CaoZixuan
 * @Date: 2022-04-14
 */
@Component
public class HtmlToJpgUtil {
    @Lazy
    @Resource
    PrintCommonService printCommonService;

    @Resource
    CreatePdfUtil createPdfUtil;

    private final static Logger log = LoggerFactory.getLogger(HtmlToJpgUtil.class);

    /**
     * 转换html -> jpg : 生成本地临时文件
     *
     * @param cardTitle    题卡名称
     * @param htmlContent  html内容
     * @param pageSizeEnum 转化pdf的纸张类型
     */
    public List<BasicAttachment> convertHtmlToJpg(String cardTitle, String htmlContent, PageSizeEnum pageSizeEnum) throws Exception {
        // 本地存储目录
        String rootPath = SystemConstant.TEMP_FILES_DIR + File.separator + System.currentTimeMillis();
        // html临时路径
        String htmlPath = rootPath + File.separator + "html" + File.separator + cardTitle + SystemConstant.HTML_PREFIX;
        // pdf临时路径
        String pdfPath = rootPath + File.separator + "pdf" + File.separator + cardTitle + SystemConstant.PDF_PREFIX;
        // jpg临时路径
        String jpgPath = rootPath + File.separator + "jpg" + File.separator + cardTitle;
        List<BasicAttachment> basicAttachmentList = new ArrayList<>();
        // html
        try {
            File htmlFile = new File(htmlPath);
            if (!htmlFile.getParentFile().exists()) {
                htmlFile.getParentFile().mkdirs();
            }
            // 生成html文件
            FileCopyUtils.copy(htmlContent.getBytes(), htmlFile);
            // 转pdf文件
            File pdfFile = new File(pdfPath);
            if (!pdfFile.getParentFile().exists()) {
                pdfFile.getParentFile().mkdirs();
            }
            HtmlToPdfUtil.convert(htmlPath, pdfPath, pageSizeEnum);
            // pdf文件转jpg
            List<File> jpgFileList = ConvertUtil.pdfToImageFile(pdfPath, jpgPath);

            for (File jpgFile : jpgFileList) {
                InputStream inputStream = new FileInputStream(jpgFile);
                MultipartFile multipartFile = new MockMultipartFile(jpgFile.getName(), jpgFile.getName(),
                        ContentType.APPLICATION_OCTET_STREAM.toString(), inputStream);
                BasicAttachment basicAttachment = printCommonService.saveAttachment(multipartFile, DigestUtils.md5Hex(multipartFile.getBytes()), UploadFileEnum.FILE);
                basicAttachmentList.add(basicAttachment);
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        } finally {
            ConvertUtil.delFolder(rootPath);
        }
        return basicAttachmentList;
    }

    /**
     * 转换html -> jpg : 生成本地临时文件
     *
     * @param cardTitle    题卡名称
     * @param htmlContent  题卡内容
     * @param pageSizeEnum 转化pdf的纸张类型
     */
    public List<ConvertJpgStorage> convertHtmlToJpgByCard(String cardTitle, String htmlContent, PageSizeEnum pageSizeEnum) throws Exception {
        List<ConvertJpgStorage> convertJpgStorageList = new ArrayList<>();
        try {
            String regex = "\\$\\{\\w+}";
            htmlContent = htmlContent.replaceAll("<img src=\"data:image/png;base64,\\$\\{examNumber\\}\">", "");
            htmlContent = htmlContent.replaceAll(regex, "");
            convertJpgStorageList = this.convertHtmlToJpg(cardTitle, htmlContent, pageSizeEnum).stream().flatMap(e -> {
                ConvertJpgStorage tmp = new ConvertJpgStorage();
                String name = e.getName();
                String index = name.substring(name.lastIndexOf("-") + 1);
                tmp.setAttachmentId(e.getId());
                tmp.setIndex(Integer.valueOf(index));
                return Stream.of(tmp);
            }).collect(Collectors.toList());

            if (convertJpgStorageList.size() == 0) {
                throw ExceptionResultEnum.ERROR.exception("生成jpg文件异常");
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return convertJpgStorageList;
    }
}
