<?php
/**
 *  ╔═══════════════════════════════════════════════════╗
 *  ║                                                   ║
 *  ║     ██╗  ██╗   █████╗    ██████╗                  ║
 *  ║     ██║  ██║  ██╔══██╗  ██╔═══██╗                 ║
 *  ║     ███████║  ███████║  ██║   ██║                 ║
 *  ║     ██╔══██║  ██╔══██║  ██║   ██║                 ║
 *  ║     ██║  ██║  ██║  ██║  ╚██████╔╝   SNS           ║
 *  ║                                                   ║    
 *  ║                                                   ║    
 *  ║     © 2023 HaoSNS™ All Rights Reserved            ║
 *  ║     官方网站: https://www.haosns.com                *
 *  ║     本代码由赣州乐易网络科技有限公司®提供             *
 *  ║                                                    *
 *  ║   未经授权禁止复制、传播或用于其他商业目的            *
 *  ║                                                   ║
 *  ╚═══════════════════════════════════════════════════╝
 */

namespace app\api\controller;

use Endroid\QrCode\Builder\Builder;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\ErrorCorrectionLevel;
use Endroid\QrCode\Label\LabelAlignment;
use Endroid\QrCode\Label\Font\OpenSans;
use Endroid\QrCode\RoundBlockSizeMode;
use Endroid\QrCode\Writer\PngWriter;

use EasyWeChat\MiniApp\Application;

/**
 * 海报
 */
class Poster extends BaseShopController
{

    public array $notNeedLogin = ['code','articleShare','mpCode'];

    public function code($url)
    {
        $builder = new Builder(
            writer: new PngWriter(),
            writerOptions: [],
            validateResult: false,
            data: $url,
            encoding: new Encoding('UTF-8'),
            errorCorrectionLevel: ErrorCorrectionLevel::High,
            size: 100,
            margin: 0, // 设置为 0 去除内边距
            roundBlockSizeMode: RoundBlockSizeMode::Margin,
            logoResizeToWidth: 50,
            logoPunchoutBackground: true,
            labelFont: new OpenSans(20),
            labelAlignment: LabelAlignment::Center
        );

        $result = $builder->build();

        // Directly output the QR code
        header('Content-Type: image/jpeg');
        echo $result->getString();die;

        // Save it to a file
        // $result->saveToFile(__DIR__.'/qrcode.png');

        // // Generate a data URI to include image data inline (i.e. inside an <img> tag)
        // $dataUri = $result->getDataUri();
    }
    

    /**
     * 
     */
    public function mpCode($path)
    {

        $config = \app\common\service\WeChatConfigService::getWechatConfigByTerminal(1);

        $app = new Application($config);

        $accessToken = $app->getAccessToken();
        $accessToken->getToken(); // string

        

        // dd($accessToken->getToken());

        $url = "https://api.weixin.qq.com/wxa/getwxacode?access_token=" . $accessToken->getToken();
    
        $data = [
            'path' => $path,
            'width' => 430, // 二维码的宽度，单位 px
        ];
        
        $options = [
            'http' => [
                'method' => 'POST',
                'header' => 'Content-type: application/json',
                'content' => json_encode($data),
            ],
        ];
        
        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        
        // 判断是否是json（错误时微信会返回json）
        $json = json_decode($result, true);
        if (isset($json['errcode'])) {
            die('生成小程序码失败: ' . $json['errmsg']);
        }
        
        // 直接输出图片
        header('Content-Type: image/jpeg');
        echo $result;
        exit;
    }

    /**
     * 生成分享页面url
     * @return never
     */
    public function articleShare($id)
    {
        // $article = \app\common\model\Article::with(['user'])
        // ->find($id);

        // dd($article->toArray());
        
        //案例一：将活动背景图片和动态二维码图片合成一张图片
        //图片一
        $path_1 = 'https://sns.haodds.com/uploads/images/20250514093432caa836980.png';
        //图片二
        $path_2 = 'https://sns.haodds.com/api/poster/code?url=https://www.baidu.com';
        // 创建图片对象
        $image_1 = @imagecreatefrompng($path_1);
        $image_2 = @imagecreatefrompng($path_2);

        // 检查图片是否成功加载
        if (!$image_1 || !$image_2) {
            header('HTTP/1.1 500 Internal Server Error');
            die('无法加载图片，请检查文件路径和权限');
        }

        // 合成图片
        // 将二维码图片合并到背景图上
        imagecopymerge(
            $image_1,           // 目标图像（背景）
            $image_2,           // 源图像（二维码）
            80, 90,             // 目标位置坐标（x,y）
            0, 0,               // 源图像开始坐标
            imagesx($image_2),  // 源图像宽度
            imagesy($image_2),  // 源图像高度
            100                 // 合并程度（100表示完全覆盖）
        );
        
        // dd(ROOT_DIR);

        $blue = imagecolorallocate($image_1, 0, 0, 255);    // 蓝色
        $green = imagecolorallocate($image_1, 0, 128, 0);   // 绿色
        $gray = imagecolorallocate($image_1, 128, 128, 128); // 灰色

        //文字
        $font = ROOT_DIR."/roboto.ttf"; //字体文件
        $content = ['你好11111111111111111111ddddddddddd111111111111111111111111111111111', '11111111111111111111111111111111111111小码农'];
        $font_lposition = [10, 30]; //距左边距
        $font_tposition = [20, 80]; //距上边距
        $text_color = imagecolorallocate($image_1, 255, 0, 0); // 红色
        if (count($content) > 0) {
            for ($i = 0; $i < count($content); $i++) {
                imagettftext($image_1, 25, 0, $font_lposition[$i], $font_tposition[$i], $text_color, $font, $content[$i]);
            }
        }

        // 输出合并后的图片直接到浏览器
        
        header('Content-Type: image/jpeg');
        imagepng($image_1);

        // 释放内存
        imagedestroy($image_1);
        imagedestroy($image_2);die;
    }
    
}
