package com.seer.teach.mp.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.seer.teach.common.constants.CommonConstant;
import com.seer.teach.common.enums.ResultCodeEnum;
import com.seer.teach.common.exception.CommonException;
import com.seer.teach.common.minio.config.MinioConfig;
import com.seer.teach.common.response.OssImageUploadResp;
import com.seer.teach.common.service.impl.CommonFileServiceImpl;
import com.seer.teach.mp.api.request.GetQrCodeReq;
import com.seer.teach.mp.service.IWechatMiniProgramService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class WechatMiniProgramServiceImpl implements IWechatMiniProgramService {

    @Autowired
    private WxMaService wxMaService;

    @Autowired
    private CommonFileServiceImpl commonService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Value("${zs.mini.qrcode.expire-time:3}")
    private Integer miniQrCodeExpireTime;

    @Override
    public WxMaJscode2SessionResult code2Session(String jsCode) {
        try {
            return wxMaService.jsCode2SessionInfo(jsCode);
        } catch (WxErrorException e) {
            log.info("微信小程序登录失败",e);
            throw new CommonException(ResultCodeEnum.WX_SESSION_CODE_USED_ERROR);
        }
    }

    @Override
    public OssImageUploadResp createQrcode(GetQrCodeReq reqParams) {
        try {
            String redisKey = CommonConstant.WX_MINI_QR_SCENE_PREFIX + reqParams.getScene();
            if (redisTemplate.hasKey(redisKey)) {
                String url = redisTemplate.boundValueOps(redisKey).get();
                return new OssImageUploadResp(url);
            }

            byte[] codeResult = wxMaService.getQrcodeService().createWxaCodeUnlimitBytes(
                    reqParams.getScene(),
                    reqParams.getPage(),
                    reqParams.isCheckPath(),
                    reqParams.getEnvVersion(),
                    reqParams.getWidth(),
                    reqParams.isAutoColor(),
                    reqParams.getLineColor(),
                    reqParams.isHyaline());

            long timestamp = System.currentTimeMillis();
            String randomPart = UUID.randomUUID().toString().replace("-", "").substring(0, 8);
            String fileName = timestamp + randomPart + ".png";

            commonService.minioUploadQrCodeImage(codeResult, fileName);

            String qrCodeUrl = MinioConfig.URL + "/" + MinioConfig.BUCKET + "/" +
                    MinioConfig.WX_QR_CODE_IMAGE_FOlDER + fileName;
            OssImageUploadResp result = new OssImageUploadResp(qrCodeUrl);

            log.info("创建小程序二维码成功，文件名: {}", fileName);

            redisTemplate.boundValueOps(redisKey).set(
                    result.getUrl(),
                    miniQrCodeExpireTime,
                    TimeUnit.HOURS);

            return result;
        } catch (WxErrorException e) {
            log.error("创建小程序二维码失败，错误信息: ", e);
            throw new CommonException(ResultCodeEnum.WX_MINI_QRCODE_CREATE_QRCODE_FAILED);
        }
    }
}