<?php

namespace addons\poster\library;

use think\Db;

class Image2
{
    protected $target;      //图像资源
    protected $poster_url;  //海报url
    protected $model;       //海报模型

    public function __construct()
    {
        $this->model = new \app\admin\model\Poster;
    }


    /**
     * 创建海报
     * @author Created by lizhen
     */
    public function createPosterImage($background,$qrcode_url,$text,$new_file_name)
    {
        $this->poster_url = $new_file_name;

        set_time_limit(0);
        @ini_set('memory_limit', '256M');

        $this->target = imagecreatetruecolor(723, 881); //背景图尺寸
        $white = imagecolorallocate($this->target, 255, 255, 255);
        imagefill($this->target, 0, 0, $white);

        $bg = $this->createImage($background);
        if (!empty($bg)) {
            $bgWidth = imagesx($bg);
            $bgHeight = imagesy($bg);
            $ratio = 640 / $bgWidth;
            $ratio = 1;
            $newWidth = imagesx($bg) * $ratio;
            $newHeight = imagesy($bg) * $ratio;

            $bgClone = imagecreatetruecolor($newWidth, $newHeight);
            imagecopyresampled($bgClone, $bg, 0, 0, 0, 0, $newWidth, $newHeight, $bgWidth, $bgHeight);

            imagecopy($this->target, $bgClone, 0, 0, 0, 0, $newWidth, $newHeight);

            imagedestroy($bg);
            imagedestroy($bgClone);
        }



        $poster = [

            [
                "left"=> "125px",
                "top"=> "300px",
                "type"=> "img",
                "width"=> "90px",
                "height"=> "90px",
                "src"=> $qrcode_url,
            ]
        ];

        //写字
        //$text = '一二三四五六七八九十一二三四五';
        $text_len = mb_strlen($text);
        if($text_len > 10){
            $poster[] = [
                "left"=> "100px",
                "top"=> "145px",
                "type"=> "nickname",
                "width"=> "80px",
                "height"=> "40px",
                "size"=> "14px",
                "color"=> "#FFFFFF",
                "text"=> mb_substr($text,0,10),
            ];
            $poster[] = [
                "left"=> "100px",
                "top"=> "175px",
                "type"=> "nickname",
                "width"=> "80px",
                "height"=> "40px",
                "size"=> "14px",
                "color"=> "#FFFFFF",
                "text"=> mb_substr($text,10,10),
            ];
        }else{
            $poster[] = [
                "left"=> "140px",
                "top"=> "220px",
                "type"=> "nickname",
                "width"=> "80px",
                "height"=> "40px",
                "size"=> "14px",
                "color"=> "#FF0000",
                "text"=> $text,
            ];
        }
        //写字


        foreach ($poster as $d) {
            $d = $this->getRealData($d);
            if ($d['type'] == 'img' && isset($d['src'])) {
                $this->mergeImage($d, $d['src']);
            } elseif ($d['type'] == 'nickname') {
                $this->mergeText($d, $d['text']);
            }
        }

        imagepng($this->target, $this->poster_url);
        imagedestroy($this->target);

        return $this->poster_url;
    }

    public function mergeImage($data, $imgurl)
    {
        $img = $this->createImage($imgurl);
        if (!$img) {
            return false;
        }
        $w = imagesx($img);
        $h = imagesy($img);
        imagecopyresized($this->target, $img, $data['left'], $data['top'], 0, 0, $data['width'], $data['height'], $w, $h);
        imagedestroy($img);
    }

    public function mergeText($data, $text)
    {
        $font = ROOT_PATH . '/public/assets/fonts/SourceHanSansK-Regular.ttf';
        if (!isset($data['color'])) {
            $data['color'] = '#000';
        }
        $colors = $this->hex2rgb($data['color']);
        $color = imagecolorallocate($this->target, $colors['red'], $colors['green'], $colors['blue']);
        imagettftext($this->target, $data['size'], 0, $data['left'], $data['top'] + $data['size'], $color, $font, $text);
    }

    public function createImage($imgurl)
    {
        if (strpos($imgurl, 'data:image') !== false) {
            $imgurl = '/assets/addons/poster/images/head.jpg';
        }
        if (strpos($imgurl, '://') === false) {
            $imgurl = ROOT_PATH . '/public' . $imgurl;
            if (!is_file($imgurl)) {
                return '';
            }
        } else {
            $domain = 'thirdwx.qlogo.cn';
            if (strpos($imgurl, $domain) !== false) {
                $ip = gethostbyname($domain);
                if ($ip) {
                    $imgurl = str_replace($domain, $ip, $imgurl);
                }
            }
        }
        @$content = file_get_contents($imgurl);
        if ($content) {
            return imagecreatefromstring($content);
        }
        return '';
    }

    private function getRealData($data)
    {
        $data['left'] = isset($data['left']) ? intval(str_replace('px', '', $data['left'])) * 2 : 0;
        $data['top'] = isset($data['top']) ? intval(str_replace('px', '', $data['top'])) * 2 : 0;
        $data['width'] = isset($data['width']) ? intval(str_replace('px', '', $data['width'])) * 2 : 0;
        $data['height'] = isset($data['height']) ? intval(str_replace('px', '', $data['height'])) * 2 : 0;
        $data['size'] = isset($data['size']) ? intval(str_replace('px', '', $data['size'])) * 2 : 0;
        return $data;
    }

    /**
     * 递归创建文件夹
     * @author Created by Xing <464401240@qq.com>
     */
    private function mkdirs($path)
    {
        if (!is_dir($path)) {
            $this->mkdirs(dirname($path));
            mkdir($path);
        }
        return is_dir($path);
    }

    /**
     * hex转rgb
     * @param $colour
     * @return array|bool
     */
    private function hex2rgb($colour)
    {
        if ($colour[0] == '#') {
            $colour = substr($colour, 1);
        }
        if (strlen($colour) == 6) {
            list($r, $g, $b) = array($colour[0] . $colour[1], $colour[2] . $colour[3], $colour[4] . $colour[5]);
        } elseif (strlen($colour) == 3) {
            list($r, $g, $b) = array($colour[0] . $colour[0], $colour[1] . $colour[1], $colour[2] . $colour[2]);
        } else {
            return false;
        }
        $r = hexdec($r);
        $g = hexdec($g);
        $b = hexdec($b);
        return array('red' => $r, 'green' => $g, 'blue' => $b);
    }
}
