package com.mosty.common.core.login;

import com.mosty.common.base.domain.ResponseResult;
import com.mosty.common.core.business.entity.SysDept;
import com.mosty.common.core.login.dto.ImageRequest;
import com.mosty.common.core.util.Base64Util;
import com.mosty.common.util.ImageUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;

@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/image")
@Api(tags = "图片功能服务")
public class ImageController {

    @GetMapping("/base64")
    @ApiOperation(value = "根据URL获取base64图片", httpMethod = "GET", response = SysDept.class)
    public ResponseResult<String> selectPage(ImageRequest imageRequest) {
        try {
            String base = "";
            if (imageRequest.getUrl().startsWith("https://")) {
                base = ImageUtils.encodeImageToBase64Https(imageRequest.getUrl());
            } else {
                base = ImageUtils.encodeImageToBase64(imageRequest.getUrl());
            }
            return ResponseResult.success(base);
        } catch (Exception e) {
            return ResponseResult.fail("图片下载失败");
        }
    }

    //　下载图片(返回二进制)
    @RequestMapping(value = "/image", method = RequestMethod.GET)
    public HttpEntity<byte[]> downloadFile(String url, HttpServletRequest request) throws Exception{
        byte[] obsBytes = null;
        if (StringUtils.isNotBlank(url)) {
            url= URLDecoder.decode(url,"UTF-8");
            if (url.startsWith("https://")) {
                obsBytes = ImageUtils.encodeImageToByteHttps(url);
            } else {
                obsBytes = ImageUtils.encodeImageTobyte(url);
            }
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.IMAGE_JPEG);
        headers.setContentLength(obsBytes.length);
        return new HttpEntity(obsBytes, headers);
    }

}
