package com.sagacloud.utils.qrCode;
/*
 * Author: Jxing
 * Create Time: 2019/1/7
 */

import com.sagacloud.utils.ExternalUrl;
import com.sagacloud.utils.HttpRequestUtil;
import com.sagacloud.utils.OssUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Map;

public class QRCodeRunnable implements Runnable {
    String pjId;
    Boolean genPersagyQr;
    private String innerImageUrl;
    // key --> 对象id, value --> 在文件服务系统内的文件名(一般是对象id + QR)
    Map<String, String> idFilekeyMap;
    private static final Logger log = LoggerFactory.getLogger(QRCodeRunnable.class);

    public QRCodeRunnable(Map<String, String> idFilekeyMap, String innerImageUrl, String pjId, Boolean genPersagyQr) {
        this.idFilekeyMap = idFilekeyMap;
        this.innerImageUrl = innerImageUrl;
        this.pjId = pjId;
        this.genPersagyQr = genPersagyQr;
    }

    @Override
    public void run() {
        if(idFilekeyMap == null || idFilekeyMap.size() == 0)
            return;
        Image innerImage = null;
        if(innerImageUrl != null && innerImageUrl.length() > 0) {
            try {
                innerImage = HttpRequestUtil.getImage(innerImageUrl);
            }catch (Exception ignore){innerImage = null;}
        }
        for(String id : idFilekeyMap.keySet()) {
            try {
                String key;
                if(this.genPersagyQr){
                    if((id + "QR").equals(idFilekeyMap.get(id))){
                        key = String.format("http://qrcode.persagy.com/scan?pjId=%s&key=%s", this.pjId, id);
                    }else{
                        key = String.format("http://qrcode.persagy.com/scan?pjId=%s&key=%s", this.pjId, idFilekeyMap.get(id));
                    }
                }else{
                    key = String.join("", "http://meos.sagacloud.cn/scan?key=", id);
                }
                BufferedImage image = QRCodeUtil.createImageFromFile(key, innerImage,  true);
                String result = HttpRequestUtil.sendImageFile(ExternalUrl.getFileUpload(idFilekeyMap.get(id), true), image);
                System.out.println(result);
            } catch (Exception e) {
                log.warn("二维码上传失败:" + id);
                e.printStackTrace();
            }
        }
    }

    public Map<String, String> getIdFilekeyMap() {
        return idFilekeyMap;
    }

    public void setIdFilekeyMap(Map<String, String> idFilekeyMap) {
        this.idFilekeyMap = idFilekeyMap;
    }

    public String getInnerImageUrl() {
        return innerImageUrl;
    }

    public void setInnerImageUrl(String innerImageUrl) {
        this.innerImageUrl = innerImageUrl;
    }

}
