package com.ms.biz.tool;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;
import javax.imageio.ImageIO;

import cn.hutool.core.codec.Base64Decoder;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ms.biz.common.Ret;
import com.ms.biz.paas.StorageService;
import com.ms.biz.service.Shop1688DsAuthService;
import com.ms.dal.entity.Shop1688DsAuth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class TailorImgTool {

    @Autowired
    private DsJsonRequestTemplate dsJsonRequestTemplate;

    @Autowired
    private Shop1688DsAuthService shop1688DsAuthService;

    @Autowired
    StorageService storageService;

    public String getTailorImgUrl(Long shopId, String imgPath) {
        Shop1688DsAuth shop1688DsAuth = shop1688DsAuthService.getDetailByShopId(shopId);
        String authCode = shop1688DsAuth.getAuthCode();
        HashMap<String, Object> params = new HashMap<>();
        params.put("authCode", authCode);
        params.put("imgUrl", imgPath);
        String res = null;
        JSONObject resObj = null;
        for (int j = 0; j < 3; j++) {
            try {
                res = dsJsonRequestTemplate.execute("/micro_move/get_image_data", params);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (ObjectUtil.isNotNull(res)) {
                resObj = JSON.parseObject(res);
                break;
            }
        }
        if (ObjectUtil.isNull(resObj) || "fail".equals(resObj.getString("result"))) {
            return imgPath;
        }
        String imageData = resObj.getString("imageData");
        InputStream oldStream = new ByteArrayInputStream(Base64Decoder.decode(imageData));
        BufferedImage oldImage = null;
        try {
            oldImage = ImageIO.read(oldStream);
        } catch (IOException e) {
            e.printStackTrace();
            return imgPath;
        }
        if (oldImage.getWidth() == oldImage.getHeight()) {
            return imgPath;
        }
        int max = Math.max(oldImage.getWidth(), oldImage.getHeight());
        // 创建一个指定大小的空白图片
        BufferedImage backgroundImg = new BufferedImage(max, max, BufferedImage.TYPE_INT_RGB);
        // 填充白色背景
        Graphics2D graphics = backgroundImg.createGraphics();
        graphics.setColor(Color.WHITE);
        graphics.fillRect(0, 0, max, max);
        graphics.dispose();
        // 保存生成的图片
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImgUtil.pressImage(backgroundImg, outputStream, oldImage, 0, 0, 1.0f);

        byte[] newImageData = new byte[0];
        try {
            newImageData = ImageTool.convertBmpToJpgDataByImgData(outputStream.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        }
        String ossPath = String.format("temp/%s/%s.jpg", new SimpleDateFormat("yyyy-MM-dd").format(new Date()), UUID.randomUUID());
        Ret uploadRet = storageService.uploadContent(ossPath, newImageData);
        if (CommonTool.isFailRet(uploadRet)) {
            System.out.println(uploadRet.getReason());
            return "";
        }
        return storageService.getPubOssUrlByOssPath(ossPath);

    }
}
