package com.greenorange.promotion.service.wechat.impl;


import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.freewayso.image.combiner.ImageCombiner;
import com.freewayso.image.combiner.element.TextElement;
import com.freewayso.image.combiner.enums.BaseLine;
import com.freewayso.image.combiner.enums.OutputFormat;
import com.freewayso.image.combiner.enums.ZoomMode;
import com.google.gson.Gson;
import com.greenorange.promotion.common.ErrorCode;
import com.greenorange.promotion.config.WxAccessToken;
import com.greenorange.promotion.constant.SystemConstant;
import com.greenorange.promotion.exception.BusinessException;
import com.greenorange.promotion.mapper.UserInfoMapper;
import com.greenorange.promotion.model.dto.CommonRequest;
import com.greenorange.promotion.model.entity.Course;
import com.greenorange.promotion.model.entity.FileInfo;
import com.greenorange.promotion.model.entity.UserInfo;
import com.greenorange.promotion.model.enums.UserRoleEnum;
import com.greenorange.promotion.service.course.CourseService;
import com.greenorange.promotion.service.file.FileInfoService;
import com.greenorange.promotion.service.wechat.WechatGetQrcodeService;
import com.greenorange.promotion.utils.QRCodeUtil;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class WechatGetQrcodeServiceImpl implements WechatGetQrcodeService {


    // 文件上传的存储目录
    @Value("${file.upload-dir}")
    private String uploadDir;


    private final static String ACCESS_TOKEN_KEY = "accessToken";

    // 优化：设置一个合理的缓冲区大小
    private static final int BUFFER_SIZE = 8192; // 8 KB

    @Resource
    private RedisTemplate<String, Object> redisTemplate;


    @Schema(description = "小程序 appId")
    @Value("${wx.mini.appId}")
    private String appId;

    @Schema(description = "小程序 appSecret")
    @Value("${wx.mini.appSecret}")
    private String appSecret;

    @Resource
    private FileInfoService fileInfoService;


    /**
     * 获取接口调用凭据
     */
    @Override
    public WxAccessToken getAccessToken() {
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret;
        String response = null;
        try {
            response = HttpUtil.get(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Gson gson = new Gson();
        WxAccessToken wxAccessToken = gson.fromJson(response, WxAccessToken.class);
        String access_token = wxAccessToken.getAccess_token();
        redisTemplate.opsForValue().set(ACCESS_TOKEN_KEY, access_token, 7200, TimeUnit.SECONDS);
        return wxAccessToken;
    }


    @Override
    public WxAccessToken getApiAccessToken() {
        String accessToken = (String) redisTemplate.opsForValue().get(ACCESS_TOKEN_KEY);
        if (accessToken == null) {
            accessToken = this.getAccessToken().getAccess_token();
        }
        WxAccessToken wxAccessToken = WxAccessToken.builder()
                .access_token(accessToken)
                .expires_in("7200").build();
        return wxAccessToken;
    }


    /**
     * 获取微信小程序二维码
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String getWxQrCode(String inviteCode, UserRoleEnum userRoleEnum) throws IOException {
        String accessToken = (String) redisTemplate.opsForValue().get(ACCESS_TOKEN_KEY);
        if (accessToken == null) {
            accessToken = this.getAccessToken().getAccess_token();
        }
        Map<String, Object> param = new HashMap<>();
        param.put("page", "pages/loginModule/register/register");
        param.put("scene", inviteCode + "=" + userRoleEnum.getValue());
        param.put("width", 430);
        param.put("env_version", "release");
        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(qrImage);
        byte[] resultBytes = resultStream.readAllBytes();
        // 创建上传目录，如果不存在
        String biz = "default";
        String fileName = RandomStringUtils.random(8, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") + "." + "png";
        // 获取文件类型
        String fileType = FileUtil.getSuffix(fileName);
        // 获取view值
        String view = RandomStringUtils.random(8, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
        File file = new File(uploadDir + fileName);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();// 如果路径不存在则创建
        }
        // 将文件上传到目标位置
        try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file), BUFFER_SIZE)) {
            bos.write(resultBytes);
        } catch (IOException e) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "文件上传失败，失败原因：" + e.getMessage());
        }
        // 生成图片并保存
//        try (FileOutputStream fos = new FileOutputStream(UPLOAD_DIR)) {
//            fos.write(resultBytes);  // 将二进制数据写入文件
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        // 将二维码转换为Base64编码
//        String base64Image = "data:image/jpeg;base64," + Base64.getEncoder().encodeToString(responseBytes);
        // 获取文件大小
        Double fileSize = file.length() / 1024.0;
        fileSize = Double.valueOf(String.format("%.2f", fileSize));
        // 获取文件哈希值
        InputStream inputStream = new FileInputStream(file);
        String hashValue = DigestUtils.sha256Hex(inputStream);
        // 保存文件
        FileInfo fileInfo = FileInfo.builder()
                .name(fileName)
                .type(fileType)
                .size(fileSize)
                .fileView(view)
                .biz(biz)
                .hashValue(hashValue)
                .build();
        fileInfoService.save(fileInfo);
        return biz + "-" + view;
    }



//
//    /**
//     * 微信小程序获取课程码
//     */
//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public String getWxCourseQrCode(CommonRequest commonRequest, HttpServletRequest request) throws Exception {
//        String accessToken = (String) redisTemplate.opsForValue().get(ACCESS_TOKEN_KEY);
//        if (accessToken == null) {
//            accessToken = this.getAccessToken().getAccess_token();
//        }
//        // 获取用户邀请码
//        Long userId = (Long) request.getAttribute("userId");
//        UserInfo userInfo = userInfoMapper.selectById(userId);
//        String invitationCode = userInfo.getInvitationCode();
//        // 获取课程信息
//        Long courseId = commonRequest.getId();
//        Course course = courseService.getById(courseId);
//        String courseTitle = course.getName();
//        String originalPrice = String.valueOf(course.getOriginPrice());
//        String discountPrice = String.valueOf(course.getDiscountPrice());
//        String discountText = "元券后价";
//
//
//        Map<String, Object> param = new HashMap<>();
//        param.put("page", "pages/loginModule/register/register");
//        param.put("scene", "invitationCode=" + invitationCode + "&courseId=" + courseId);
//        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();
//
//        String FontType = "Microsoft YaHei UI";
//        int FontStyle = Font.PLAIN;
//
//        // 加载一张空白图像
//        String blankUrl = "https://img.picui.cn/free/2025/06/21/6856a072e9eea.png";
//        ImageCombiner combiner = new ImageCombiner(blankUrl, 341, 391, ZoomMode.WidthHeight, OutputFormat.PNG);
//
//        // 加载课程图片
//        String courseUrl = SystemConstant.FILE_COMMON_PREFIX + course.getImage();
//        BufferedImage courseImage = ImageIO.read(new URL(courseUrl));
//
//        // 将二维码数据转换为 BufferedImage
//        BufferedImage qrImage = ImageIO.read(new ByteArrayInputStream(responseBytes));
//
//        // 缩放图片(不失真）
//        Image scaledImage = qrImage.getScaledInstance(134, 134, Image.SCALE_SMOOTH);
//        BufferedImage resizedImage = new BufferedImage(134, 134, BufferedImage.TYPE_INT_RGB);
//        resizedImage.getGraphics().drawImage(scaledImage, 0, 0, null);
//
//        combiner.setQuality(1f);
//
//        // 将课程图片合并到组合器中
//        combiner.addImageElement(courseImage, 18, 16, 306, 158, ZoomMode.WidthHeight).setRoundCorner(5).setCenter(true);
//        // 将二维码图片合并到组合器中
//        combiner.addImageElement(resizedImage, 190, 240);
//
//        // 绘制文本
//        TextElement courseTitleElement = new TextElement(courseTitle, FontType, FontStyle, 18, 20, 186);
//        courseTitleElement.setColor(Color.decode("#323232"))
//                            .setCenter(true)
//                            .setAutoBreakLine(306);
//        combiner.addElement(courseTitleElement);
//
//        TextElement originalPriceElement = new TextElement(originalPrice, FontType, FontStyle, 24, 56, 275);
//        originalPriceElement.setColor(Color.decode("#8C8C8C")).setStrikeThrough(true);
//        combiner.addElement(originalPriceElement);
//
//        TextElement discountedPriceElement = new TextElement(discountPrice, FontType, Font.BOLD, 28, 31, 343);
//        discountedPriceElement.setColor(Color.decode("#F84947")).setBaseLine(BaseLine.Base).setSpace(0.01f);
//        combiner.addElement(discountedPriceElement);
//
//        TextElement discountedTextElement = new TextElement(discountText, FontType, FontStyle, 16, discountedPriceElement.getX() + discountedPriceElement.getWidth(), 341);
//        discountedTextElement.setColor(Color.decode("#F84947")).setBaseLine(BaseLine.Base);
//        combiner.addElement(discountedTextElement);
//
//        combiner.combine();
//
//        InputStream resultStream = combiner.getCombinedImageStream();
//        byte[] resultBytes = resultStream.readAllBytes();
//        // 创建上传目录，如果不存在
//        String biz = "default";
//        String fileName = RandomStringUtils.random(8, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") + "." + "png";
//        // 获取文件类型
//        String fileType = FileUtil.getSuffix(fileName);
//        // 获取view值
//        String view = RandomStringUtils.random(8, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
//        File file = new File(uploadDir + fileName);
//        if (!file.getParentFile().exists()) {
//            file.getParentFile().mkdirs();// 如果路径不存在则创建
//        }
//        // 将文件上传到目标位置
//        try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file), BUFFER_SIZE)) {
//            bos.write(resultBytes);
//        } catch (IOException e) {
//            throw new BusinessException(ErrorCode.OPERATION_ERROR, "文件上传失败，失败原因：" + e.getMessage());
//        }
//
//        // 获取文件大小
//        Double fileSize = file.length() / 1024.0;
//        fileSize = Double.valueOf(String.format("%.2f", fileSize));
//        // 获取文件哈希值
//        InputStream inputStream = new FileInputStream(file);
//        String hashValue = DigestUtils.sha256Hex(inputStream);
//        // 保存文件
//        FileInfo fileInfo = FileInfo.builder()
//                .name(fileName)
//                .type(fileType)
//                .size(fileSize)
//                .fileView(view)
//                .biz(biz)
//                .hashValue(hashValue)
//                .build();
//        fileInfoService.save(fileInfo);
//
//        String viewValue = biz + "-" + view;
//        // 保存课程推广码申请记录
//        CourseQrcodeApply courseQrcodeApply = CourseQrcodeApply.builder()
//                .userId(userId)
//                .courseId(courseId)
//                .courseQrcode(viewValue)
//                .build();
//        courseQrcodeApplyService.save(courseQrcodeApply);
//        return viewValue;
//    }




}
