import { getAgentShareInfo } from '@/service/agent';
import { isSuccess } from "@/utils/index";
import { genWechatQrcode, sceneZip } from "@/service/wechat";
import { APP_ENV_VERSION } from '@/config/index'
import {
  ImgLoader,
  Container,
  Image as DuduImage,
  Stage,
} from "@/libs/duducanvas/index";

// 生成微信小程序二维码
export const genQrcode = async (
  agentId: string,
  qrcodeWidth: number,
  qrcodeHeight: number,
  stage: Stage,
  container: Container
) => {
  const respnose = await getAgentShareInfo(agentId)
  if(!isSuccess(respnose.status)){
    return;
  }
  
  const sceneStr = JSON.stringify({agentId: agentId, shareKey: respnose.data.shareKey})
  

  // 压缩参数
  const zipResponse = await sceneZip(sceneStr)
  if(!isSuccess(zipResponse.status)){
    return;
  }
  // 生成小程序二维码
  const genResponse = await genWechatQrcode({
    scene: zipResponse.data.shortScene,
    page: `pages/profile/index`,
    width: qrcodeWidth,
    check_path: false,
    auto_color: true,
    is_hyaline: false,
    line_color: {r:30, g: 111, b: 248 },
    env_version: APP_ENV_VERSION,
  }, 'base64');
  if(!isSuccess(genResponse.status)){
    return
  }
  if (!genResponse.data.imgBase64) {
    return;
  }

  const loader = new ImgLoader(stage.canvas, [
    {
      id: "qrcode",
      src: `data:image/png;base64,${genResponse.data.imgBase64}`,
    },
  ]);
  await loader.load();
  
  const qrcodeTexture = loader.get("qrcode");
  if (qrcodeTexture) {
    const qrcodeImage = new DuduImage({
      image: qrcodeTexture.image,
      width: qrcodeWidth,
      height: qrcodeHeight,
    });
    container.addChild(qrcodeImage);
  }
};

export const getCanvasSize = () => {
  const designWidth = 319;
  const designHeight = 447;
  // 宽高放大一倍
  const ratio = 2;
  const canvasWidth = designWidth * ratio;
  const canvasHeight = designHeight * ratio;
  return {
    canvasWidth,
    canvasHeight,
    ratio,
    rValue: (v: number) => v * ratio,
  };
};