<?php

namespace addons\poster\library;

use think\Db;

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

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


    /**
     * 创建海报
     * @author Created by Xing <464401240@qq.com>
     */
    public function createPosterImage($poster, $member)
    {
        $path = $this->model->getDirs($poster['id']);
        if (!is_dir($path)) {
            $this->mkdirs($path);
        }
        $md5 = md5(json_encode(array(
            'user_id'   => $member['id'],
            'bg'        => $poster['bg_image'],
            'data'      => $poster['data'],
            'poster_id' => $poster['id']
        )));
        $file = $md5 . '.png';
        $this->poster_url = $path . $file;
        if (is_file($this->poster_url)) {
            return $this->poster_url; //文件存在则直接返回
        }

        set_time_limit(0);
        @ini_set('memory_limit', '256M');
        $this->target = imagecreatetruecolor(640, 1008);

        $white = imagecolorallocate($this->target, 255, 255, 255);
        imagefill($this->target, 0, 0, $white);
        $bg = $this->createImage($poster['bg_image']);
        if (!empty($bg)) {
            $bgWidth = imagesx($bg);
            $bgHeight = imagesy($bg);
            $ratio = 640 / $bgWidth;
            $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);
        }
        $data = json_decode(str_replace('&quot;', '\'', $poster['data']), true);

        foreach ($data as $d) {
            $d = $this->getRealData($d);
            if ($d['type'] == 'head') {
                $avatar = preg_replace('/\\/0$/i', '/96', $member['avatar']);
                $this->mergeImage($d, $avatar);
            } elseif ($d['type'] == 'img' && isset($d['src'])) {
                $this->mergeImage($d, $d['src']);
            } elseif ($d['type'] == 'qr' && isset($d['qr_table']) && isset($d['qr_relation']) && isset($d['qr_field'])) {
                $exist = Db::query('show tables like "' . $d['qr_table'] . '"');
                if ($exist) {
                    $fields = Db::getConnection()->getFields($d['qr_table']); //传入数据表名称 $tablename
                    if (isset($fields[$d['qr_relation']])) {
                        $qrimg = Db::table($d['qr_table'])->where([$d['qr_relation'] => $member['id']])->value($d['qr_field']);
                        $this->mergeImage($d, $qrimg);
                    }
                }
            } elseif ($d['type'] == 'nickname') {
                $this->mergeText($d, $member['nickname']);
            }
        }

        imagepng($this->target, $path . $file);
        imagedestroy($this->target);

        $params['poster_id'] = $poster['id'];
        $params['user_id'] = $member['id'];
        $params['image'] = $this->poster_url;
        $posterLog = new \app\admin\model\PosterLog();
        $posterLog->save($params);
        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);
    }
}