package cn.com.ty.lift.ud.utils;

import cn.com.ty.lift.ud.config.OssConfigutatioin;
import cn.com.ty.lift.ud.config.SystemCont;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.uniteidea.fileserver.upload.FileUploadHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;

/**
 * 后台生成二维码，流化后上传到阿里云服务器
 */
public class QrCodeUtil {

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

    /**
     *
     * @param userId  用户ID
     * @param url  新增接口地址
     * @return
     * @throws Exception
     */
    public static String getQrCode(Long userId,String url) throws Exception{
        //生成一个二维码

        //定义一个json字符串

        //1.创建一个jsonObject对象
//        JSONObject jsonObject = new JSONObject();
//        Long lowerUserId = 1L;
        //2.给jsonObject对象中放入数据
//        jsonObject.put("url",url);
//        jsonObject.put("userId",userId);
//        jsonObject.put("lowerUserId",lowerUserId);

        //3.将json对象转换为json格式的字符串
//        String content = jsonObject.toString();
        SystemCont systemCont = ApplicationContextUtil.getBean(SystemCont.class);
        String content = systemCont.getWxShareUrl()+ "?page=" + url + "&id=" + userId;

        //二维码的宽高
        int width=200;
        int height=200;
        //创建Map集合
        Map<EncodeHintType,Object> hints=new HashMap<EncodeHintType,Object>();
        hints.put(EncodeHintType.CHARACTER_SET,"UTF-8");
        //4.创建一个矩阵对象,Ctrl+P显示方法参数
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE,width,height,hints);

        //创建一个图片存放路径，图片名称
        //String filePath = "D:";
        //String filePath = "/usr/local/files/ty/";
        //获取 fileserver.properties 配置的上传本地缓存目录
        String filePath = FileUploadHelper.getInstance().getUploadLocalPath();
        String newFileName= userId.toString() +"QrCode.jpg";
        Path path = FileSystems.getDefault().getPath(filePath,newFileName);

        //5.将矩阵对象生成二维码
        MatrixToImageWriter.writeToPath(bitMatrix,"jpg",path);
        //二维码流化上传到服务器
        File file = new File(filePath + newFileName);
        FileInputStream fileInputStream = new FileInputStream(file);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] b = new byte[1024];
        int n;
        while ((n = fileInputStream.read(b)) != -1)
        {
            byteArrayOutputStream.write(b, 0, n);
        }
        String fullUrlFileName = null;
        try {
            String dir = "upload/" + FileUploadHelper.getSubTimeFolder();
            String relativeUrlFileName = dir + newFileName;
            OssConfigutatioin ossConfigutatioin = ApplicationContextUtil.getBean(OssConfigutatioin.class);
            //上传到文件服务器
            fullUrlFileName = ossConfigutatioin.build().putObject(relativeUrlFileName, byteArrayOutputStream.toByteArray());
            logger.info("上传二维码成功：" + fullUrlFileName);
        } catch (Exception e) {
            logger.error("二维码上传失败");
        }
        return fullUrlFileName;
    }


    public static void main(String[] args){
        try {
            Long userId = 10000L;
            String url = "http://221.234.44.30:10227/udream/api/userRebates/insert";
            getQrCode(userId,url);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
