package net.northking.cctp.se.attach;

import cn.hutool.core.bean.BeanUtil;
import net.northking.cctp.se.file.Attachment;
import net.northking.cctp.se.repository.AttachmentInfoRepository;
import net.northking.cctp.se.util.HttpUtils;
import net.northking.cctp.se.util.SpringUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 附件信息上传
 *
 */
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() {
        if (attachmentDB.getX() > 0 && attachmentDB.getY() > 0) {
            addSignature();
        }
        AttachmentInfoRepository repo = SpringUtils.getBean(AttachmentInfoRepository.class);
        try {
            Attachment upload = HttpUtils.upload(attachmentDB.getFilePath(),
                    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);
        }

    }

    private void addSignature() {
        // 根据信息添加红点或者其他标记
    }
}
