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

import com.alibaba.fastjson.JSON;
import com.qmth.teachcloud.common.bean.marking.ConvertJpgStorage;
import com.qmth.teachcloud.common.bean.vo.FilePathVo;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.entity.BasicAttachment;
import com.qmth.teachcloud.common.enums.UploadFileEnum;
import com.qmth.teachcloud.common.service.BasicAttachmentService;
import com.qmth.teachcloud.common.service.FileUploadService;
import com.qmth.teachcloud.common.util.ConvertUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

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

    @Resource
    private BasicAttachmentService basicAttachmentService;
    @Resource
    private FileUploadService fileUploadService;

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

    /**
     * pdf转图片
     *
     * @param cardId
     * @param file
     * @param userId
     * @return
     */
    public List<ConvertJpgStorage> convertPdfToJpg(Long cardId, File file, Long userId) {
        // jpg临时路径
        List<ConvertJpgStorage> convertJpgStorages = new ArrayList<>();
        List<BasicAttachment> basicAttachmentList = new ArrayList<>();
        // html
        try {
            // pdf文件转jpg
            List<File> jpgFileList = ConvertUtil.pdfToImageFile(file);
            for (int i = 0; i < jpgFileList.size(); i++) {
                int index = i + 1;
                String fileName = cardId + "-" + index + SystemConstant.JPG_PREFIX;
                FilePathVo filePathVo = fileUploadService.uploadFile(jpgFileList.get(i), UploadFileEnum.IMAGE, fileName);
                BasicAttachment basicAttachment = new BasicAttachment(JSON.toJSONString(filePathVo), fileName, SystemConstant.JPG_PREFIX, new BigDecimal(file.length()), filePathVo.getMd5(), userId);
                basicAttachmentService.save(basicAttachment);
                basicAttachmentList.add(basicAttachment);

                convertJpgStorages.add(new ConvertJpgStorage(basicAttachment.getId(), index));
            }
        } catch (Exception e) {
            basicAttachmentService.batchDeleteAttachment(basicAttachmentList);
        }
        return convertJpgStorages;
    }
}
