package com.changhu.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaQrcodeService;
import cn.binarywang.wx.miniapp.api.WxMaService;
import com.changhu.common.exception.MessageException;
import com.changhu.service.WxService;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.io.File;

/**
 * @author 20252
 * @createTime 2024/11/22 上午11:48
 * @desc WxServiceImpl...
 */
@Service
public class WxServiceImpl implements WxService {

    @Autowired
    private WxMaService wxMaService;

    @Override
    public ResponseEntity<Resource> qrCode(String path, Integer width) {
        WxMaQrcodeService qrcodeService = wxMaService.getQrcodeService();
        try {
            File qrcodeFile = qrcodeService.createQrcode(path, width);
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + qrcodeFile.getName())
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .body(new FileSystemResource(qrcodeFile));
        } catch (WxErrorException e) {
            throw new MessageException("生成表单二维码失败:{}", e.getMessage());
        }
    }
}
