package com.greenorange.promotion.controller.wechat;


import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.greenorange.promotion.common.BaseResponse;
import com.greenorange.promotion.common.ErrorCode;
import com.greenorange.promotion.common.ResultUtils;
import com.greenorange.promotion.config.WxAccessToken;
import com.greenorange.promotion.service.wechat.WechatGetQrcodeService;
import com.greenorange.promotion.utils.QRCodeUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;


@Slf4j
@RestController
@Tag(name = "获取二维码模块")
@RequestMapping("/qrcode")
public class WechatGetQrcodeController {


    private final static String ACCESS_TOKEN_KEY = "accessToken";



    @Resource
    private RedisTemplate<String, Object> redisTemplate;


    @Resource
    private WechatGetQrcodeService wechatGetQrcodeService;



    /**
     * (小程序端)获取接口调用凭据
     */
    @GetMapping("/get/token")
    @Operation(summary = "(小程序端)获取接口调用凭据", description = "参数：无, 权限：所有人, 方法名：getAccessToken")
    public BaseResponse<WxAccessToken> getAccessToken() {
        String accessToken = (String) redisTemplate.opsForValue().get(ACCESS_TOKEN_KEY);
        if (accessToken == null) {
            accessToken = wechatGetQrcodeService.getAccessToken().getAccess_token();
        }
        WxAccessToken wxAccessToken = WxAccessToken.builder()
                .access_token(accessToken)
                .expires_in("7200").build();
        return ResultUtils.success(wxAccessToken);
    }




    /**
     * 微信小程序获取二维码
     */
    @PostMapping("/get/qrcode")
    @Operation(summary = "微信小程序获取二维码", description = "参数：无, 权限：所有人, 方法名：getQrcode")
    public BaseResponse<String> getQrcode() throws IOException {
        String accessToken = (String) redisTemplate.opsForValue().get(ACCESS_TOKEN_KEY);
        if (accessToken == null) {
            accessToken = wechatGetQrcodeService.getAccessToken().getAccess_token();
        }
        Map<String, Object> param = new HashMap<>();
        param.put("page", "pages/test/test");
        param.put("scene", "a=1");
        param.put("width", 430); // 宽度
        param.put("check_path", false);
        param.put("env_version", "develop");
        String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken;
        String jsonParams = JSONUtil.toJsonStr(param);
        byte[] responseBytes = HttpUtil.createPost(url)
                .header("Content-Type", "application/json")
                .body(jsonParams)
                .execute()
                .bodyBytes();


        // 将二维码数据转换为 BufferedImage
        BufferedImage qrImage = ImageIO.read(new ByteArrayInputStream(responseBytes));
        // 获取用户头像
        String avatarUrl = "https://img.picui.cn/free/2025/04/09/67f5d7bd6b368.jpg"; // 假设这是用户头像的URL
        BufferedImage avatarImage = QRCodeUtil.getScaledAvatar(avatarUrl, 188, 188);
        // 获取空白图像
        String blankUrl = "https://www.helloimg.com/i/2025/04/07/67f34b0490d07.png";
        // 加载一张空白图片来覆盖logo（假设是透明背景的图片）
        BufferedImage blankImage = QRCodeUtil.getScaledAvatar(blankUrl, 196, 196); // 空白图片路径
        // 将头像转换为圆形
        BufferedImage circularAvatar = QRCodeUtil.getCircularImage(avatarImage);
        // 将空白头像转换为圆形
        BufferedImage circularBlank = QRCodeUtil.getCircularImage(blankImage);
        // 合并二维码和空白图片
        BufferedImage mergedWithBlank = QRCodeUtil.addImages(qrImage, circularBlank, 116, 116); // 偏移量根据需要调整
        // 合并二维码和头像
        BufferedImage resultImage = QRCodeUtil.addImages(mergedWithBlank, circularAvatar, 120, 120);
        // 将合成后的图片转换为 Base64 编码
        InputStream resultStream = QRCodeUtil.bufferedImageToInputStream(resultImage);
        byte[] resultBytes = resultStream.readAllBytes();


        // 生成图片并保存
        try (FileOutputStream fos = new FileOutputStream("qrcode.png")) {
            fos.write(resultBytes);  // 将二进制数据写入文件
        } catch (IOException e) {
            e.printStackTrace();
            return ResultUtils.error(ErrorCode.OPERATION_ERROR, "保存二维码图片失败");
        }
        // 将二维码转换为Base64编码
        String base64Image = "data:image/jpeg;base64," + Base64.getEncoder().encodeToString(responseBytes);
        return ResultUtils.success(base64Image);
    }






}
