package com.ycwl.basic.puzzle.fill.datasource;

import com.fasterxml.jackson.databind.JsonNode;
import com.ycwl.basic.model.pc.mp.MpConfigEntity;
import com.ycwl.basic.puzzle.fill.enums.DataSourceType;
import com.ycwl.basic.repository.ScenicRepository;
import com.ycwl.basic.storage.StorageFactory;
import com.ycwl.basic.utils.WxMpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.nio.file.Files;
import java.util.UUID;

/**
 * 微信小程序二维码数据源策略
 * 用于生成微信小程序二维码并上传至OSS
 */
@Slf4j
@Component
public class WechatQrcodeDataSourceStrategy implements DataSourceStrategy {

    @Autowired
    private ScenicRepository scenicRepository;

    @Override
    public String resolve(JsonNode sourceFilter, String sortStrategy, DataSourceContext context) {
        if (context.getFaceId() == null) {
            log.warn("生成微信小程序二维码失败: faceId为空");
            return null;
        }

        if (context.getScenicId() == null) {
            log.warn("生成微信小程序二维码失败: scenicId为空");
            return null;
        }

        try {
            // 获取景区的小程序配置
            MpConfigEntity scenicMpConfig = scenicRepository.getScenicMpConfig(context.getScenicId());
            if (scenicMpConfig == null) {
                log.error("生成微信小程序二维码失败: 未找到景区[{}]的小程序配置", context.getScenicId());
                return null;
            }

            // 从sourceFilter中获取page路径，默认使用 pages/videoSynthesis/from_face
            String page = "pages/videoSynthesis/from_face";
            if (sourceFilter != null && sourceFilter.has("page")) {
                page = sourceFilter.get("page").asText();
            }

            // 生成临时文件
            File qrcode = new File("qrcode_" + context.getFaceId() + "_" + UUID.randomUUID().toString().substring(0, 8) + ".jpg");

            try {
                // 调用微信API生成小程序码
                WxMpUtil.generateUnlimitedWXAQRCode(
                    scenicMpConfig.getAppId(),
                    scenicMpConfig.getAppSecret(),
                    page,
                    context.getFaceId().toString(),
                    qrcode
                );

                // 上传到OSS
                try (FileInputStream fis = new FileInputStream(qrcode)) {
                    String fileName = String.format("qrcode_%d_%s.jpg",
                        context.getFaceId(),
                        UUID.randomUUID().toString().replace("-", "").substring(0, 16));

                    String qrcodeUrl = StorageFactory.use().uploadFile(
                        "image/jpeg",
                        fis,
                        "puzzle",
                        "wechat_qrcode",
                        fileName
                    );

                    log.info("生成微信小程序二维码成功: faceId={}, page={}, url={}",
                        context.getFaceId(), page, qrcodeUrl);

                    return qrcodeUrl;
                }
            } finally {
                // 清理临时文件
                if (qrcode.exists()) {
                    try {
                        Files.delete(qrcode.toPath());
                    } catch (Exception e) {
                        log.warn("删除临时二维码文件失败: {}", qrcode.getAbsolutePath(), e);
                    }
                }
            }

        } catch (Exception e) {
            log.error("生成微信小程序二维码异常: faceId={}, scenicId={}",
                context.getFaceId(), context.getScenicId(), e);
            return null;
        }
    }

    @Override
    public String getSupportedType() {
        return DataSourceType.WECHAT_QRCODE.getCode();
    }
}
