package net.northking.cctp.upperComputer.attach;

import cn.hutool.core.bean.BeanUtil;
import net.northking.cctp.upperComputer.entity.Attachment;
import net.northking.cctp.upperComputer.entity.DebuggerDeviceInfo;
import net.northking.cctp.upperComputer.utils.HttpUtils;
import net.northking.cctp.upperComputer.utils.SpringUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * 附件信息上传
 *
 */
public class AttachInfoUpload implements Runnable {

    private static final Logger logger = LoggerFactory.getLogger(AttachInfoUpload.class);

    private AttachmentDB attachmentDB;

    public AttachInfoUpload(AttachmentDB attachmentDB) {
        this.attachmentDB = attachmentDB;
    }

    @Override
    public void run() {
        AttachmentInfoRepository repo = SpringUtils.getBean(AttachmentInfoRepository.class);
        try {
            String filePath = attachmentDB.getFilePath();
            if (attachmentDB.getX() > 0 && attachmentDB.getY() > 0) {
                filePath = addSignatureToImage(attachmentDB.getFilePath(), attachmentDB.getX(), attachmentDB.getY());
            }
            String serverAddr = SpringUtils.getProperties("nk.mobile-computer.serverAddr");
            String publicUploadAddr = SpringUtils.getProperties("nk.mobile-computer.publicUploadAddr");
            String uploadUrl = serverAddr + publicUploadAddr;
            Attachment upload = HttpUtils.upload(uploadUrl,
                    filePath, attachmentDB.getTenantId(),
                    attachmentDB.getObjectId(), attachmentDB.getBizCode(),
                    attachmentDB.getId());
            if (upload != null && StringUtils.isNotBlank(upload.getUrlPath())) {
                // 上传成功
                logger.debug("文件上传成功：{}， storagePath -> {}", BeanUtil.beanToMap(upload).toString(), attachmentDB.getId());
                // 删除数据库信息
                repo.deleteById(attachmentDB.getId());
            }
        } catch (Exception e) {
            logger.error("附件上传失败", e);
            // 附件信息的失败次数加1，并更新数据库数据
            attachmentDB.setFailureTimes(attachmentDB.getFailureTimes() + 1);
            repo.saveAndFlush(attachmentDB);
        }

    }

    /**
     * 给截图增加红点操作。
     * @param filePath
     * @param x
     * @param y
     * @return
     */
    private String addSignatureToImage(String filePath, Integer x, Integer y) {
        if (x == null || y == null) {
            return filePath;
        }
        File originFile = new File(filePath);
        if (!originFile.exists()) {
            logger.info("截图文件不存在：{}", originFile.getAbsolutePath());
            return filePath;
        }
        String fullName = originFile.getName();
        String suffix = fullName.substring(fullName.lastIndexOf(".") + 1);
        String name = fullName.substring(0, fullName.lastIndexOf("."));
        File targetFile = new File(originFile.getParentFile().getAbsolutePath() + File.separator + name + "_with_dot" + "." + suffix);
        try {
            BufferedImage bi = ImageIO.read(originFile);
            Graphics2D g2d = bi.createGraphics();   // 生成画布
            g2d.setColor(Color.RED);    // 红色
            g2d.fillOval(x, y, 20, 20); // 在图片的x，y上画上一个直径20的实心原点
            g2d.dispose();
            ImageIO.write(bi, suffix, targetFile);
        } catch (IOException e) {
            logger.error("io异常", e);
        } catch (Exception e) {
            logger.error("添加红点失败", e);
        }
        if (!targetFile.exists()) {
            targetFile = originFile;
        }
        return targetFile.getAbsolutePath();
    }
}
