/**
 * Copyright (C) 2018-2022
 * All rights reserved, Designed By www.yixiang.co
 * 注意：
 * 本软件为www.yixiang.co开发研制，未经购买不得使用
 * 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
 * 一经发现盗用、分享等行为，将追究法律责任，后果自负
 */
package co.yixiang.yshop.module.mp.controller.app.mini;


import cn.binarywang.wx.miniapp.api.WxMaQrcodeService;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaCodeLineColor;
import co.yixiang.yshop.framework.common.pojo.CommonResult;
import co.yixiang.yshop.framework.common.util.collection.CollectionUtils;
import co.yixiang.yshop.framework.security.core.annotations.PreAuthenticated;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Base64;

import static co.yixiang.yshop.framework.common.pojo.CommonResult.success;


/**
 * <p>
 * 小程序
 * </p>
 *
 * @author moxiangrong
 * @since 2024-01-21
 */
@Slf4j
@RestController
@Tag(name = "用户 APP - 小程序")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@RequestMapping("/mini")
public class AppMiniProgramController {

    @Autowired
    private WxMaService wxMaService;

    /**
     * 获取小程序二维码
     */
    @PostMapping("/getQRCode")
    @Operation(summary = "获取小程序二维码")
    @PreAuthenticated
    public CommonResult<String> getQRCode(HttpServletResponse response) {
        OutputStream outputStream = null;
        try {
            WxMaQrcodeService wxMaQrcodeService = wxMaService.getQrcodeService();
            /* 获取二维码字节数组 */
            byte[] bytes = wxMaQrcodeService.createWxaCodeUnlimitBytes
                    ("hello,test", "", false, "release", 430, true,
                            new WxMaCodeLineColor("0", "0", "0"), true);
            /* 设置返回文件类型，不设置前端识别不了 */
            response.setContentType(MediaType.IMAGE_JPEG_VALUE);
            outputStream = response.getOutputStream();
            outputStream.write(bytes);
            outputStream.flush();
        } catch (Exception ex) {
            log.info("生成小程序码失败，message:{}", ex.getMessage());
        } finally {
            try {
                outputStream.close();
            } catch (Exception ex) {
                log.error("关闭IO流失败,msg:{}", ex.getMessage());
            }
        }
        return success("");
    }
}

