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

import com.seer.teach.common.enums.ResultCodeEnum;
import com.seer.teach.common.exception.CommonException;
import com.seer.teach.mp.app.controller.req.MpGenerateQrCodeReq;
import com.seer.teach.mp.app.controller.resp.MpQrCodeResp;
import com.seer.teach.mp.factory.MpServiceFactory;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpQrcodeService;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpQrCodeTicket;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import jakarta.validation.Valid;

@Slf4j
@Service
@RequiredArgsConstructor
public class AppOfficialQrCodeService {

    private final MpServiceFactory mpServiceFactory;

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

    public MpQrCodeResp generateQrCode(@Valid MpGenerateQrCodeReq req) {
        try {
            WxMpService wxMpService = mpServiceFactory.getRequiredMpService(req.getAppId());

            Integer expireSeconds = mpQrCodeExpireTime * 60 *60;

            WxMpQrcodeService qrcodeService = wxMpService.getQrcodeService();
            WxMpQrCodeTicket ticket;
            if(req.getType() == 1) {
                ticket = qrcodeService.qrCodeCreateTmpTicket(req.getSceneStr(), expireSeconds);
            }else{
                ticket = qrcodeService.qrCodeCreateLastTicket(req.getSceneStr());
            }
            String qrCodeUrl = wxMpService.getQrcodeService().qrCodePictureUrl(ticket.getTicket());

            MpQrCodeResp resp = new MpQrCodeResp();
            resp.setQrCodeUrl(qrCodeUrl);
            resp.setTicket(ticket.getTicket());
            resp.setExpireSeconds(ticket.getExpireSeconds());
            return resp;
        } catch (WxErrorException e) {
            log.error("生成微信服务号二维码， req: {}",req, e);
            throw new CommonException(ResultCodeEnum.MP_QRCODE_CREATE_TMP_TICKET_ERROR);
        }
    }
}