package co.yixiang.yshop.module.infra.controller.app.qrcode;

import cn.binarywang.wx.miniapp.api.WxMaQrcodeService;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaCodeLineColor;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import co.yixiang.yshop.framework.common.exception.ServiceException;
import co.yixiang.yshop.framework.common.pojo.CommonResult;
import co.yixiang.yshop.module.infra.controller.app.qrcode.vo.QrCodeGenerateDTO;
import co.yixiang.yshop.module.infra.controller.app.qrcode.vo.QrCodeGenerateMiniDTO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Base64;

import static cn.hutool.core.img.ImgUtil.IMAGE_TYPE_JPG;

/**
 * @author pepis
 * @apiNote
 **/
@Tag(name = "用户 APP - 二维码")
@RestController
@RequestMapping("/infra/QrCode")
@Validated
@Slf4j
public class QrCodeController {

    @Resource
    private WxMaService wxMaService;

    @PostMapping("generate")
    @Operation(summary = "生成二维码")
    public CommonResult<String> generate(@RequestBody QrCodeGenerateDTO dto) {
        String content = dto.getContent();
        if (StrUtil.isBlank(content)) {
            throw new ServiceException();
        }
        String base64 = QrCodeUtil.generateAsBase64(content, QrConfig.create(), IMAGE_TYPE_JPG);
        return CommonResult.success(base64);
    }

    @PostMapping("generate-mini")
    @Operation(summary = "生成小程序码")
    public CommonResult<String> generateMini(@RequestBody QrCodeGenerateMiniDTO dto) {
        try {
            WxMaQrcodeService wxMaQrcodeService = wxMaService.getQrcodeService();
            /* 获取二维码字节数组 */
            byte[] bytes = wxMaQrcodeService.createWxaCodeUnlimitBytes
                    (dto.getName(), dto.getPath(), false, "trial", 430, true,
                            new WxMaCodeLineColor("0", "0", "0"), true);
            return CommonResult.success(Base64.getEncoder().encodeToString(bytes));

        } catch (Exception ex) {
            log.info("生成小程序码失败，message:{}", ex.getMessage());
            return CommonResult.success(null);
        }

    }

}
