<?php
/*
 本代码由 焕岱科技 创建
 技术支持 WX：15285007200
 严禁反编译、逆向等任何形式的侵权行为，违者将追究法律责任
*/

namespace app\common\model\bbfxshop;

use think\Model;
use think\Db;
use app\common\model\bbfxshop\User;
use app\common\model\bbfxshop\Weixin;
use app\common\model\QRcode;

class Poster extends Model
{
    public static function createPoster($id,$user_id,$platform="wxapp"){
        $user = User::getUser($user_id);
        if(empty($user)){
            return false;
        }
        
        if(is_array($id)){
            $poster = $id;
        }
        else{
            $poster = Db::name("bbfx_fenxiao_poster")->where(['id'=>$id])->find();
        }
        
        if(empty($poster)){
            return false;
        }
        
        if(empty($platform)){
            $platform = "wxapp";
        }

        $content = iunserializer($poster['content']);
        if(strstr($content['bg'], 'poster-bg.png')){
            $content['bg'] = request()->domain()."/assets/images/poster-bg.png";
        }
        $content['bg'] = cdnurl($content['bg']);
        if(empty($content['list'])){
            $content['list'] = [];
        }
        $items = $content['list'];
        
        
        set_time_limit(0);
        @ini_set("memory_limit", "256M");
        $path = ROOT_PATH . "public/data/poster_wxapp/" . UNIACID . "/";
        if(!is_dir($path)) {
            mkdir($path, 0777, true);
        }

        $filename = "poster_user_".$poster['id']."_".$user['id'].".png";
        $filename_thumb = "poster_user_".$user['id'] . "_thumb.png";
        $filepath = $path . $filename;
        $filepath_thumb = $path . $filename_thumb;
        if(is_file($filepath)){
            // return array( "thumb" => self::getImgUrl($filename_thumb), "poster" => self::getImgUrl($filename) );
        }
        
        $bgimg = self::createImage($content['bg']);
        $bgsize = array( imagesx($bgimg), imagesy($bgimg) );
        $bg_width = 640;
        
        $rate = $bg_width / $bgsize[0];
        $bgimg = self::imageZoom($bgimg,$rate);
        
        $c = $bgsize[0] / $bg_width;
        $bgsize[0] = $bg_width;
        $bgsize[1] = $bgsize[1] / $c;
        // print_r($bgsize[0].",".$bgsize[1]);die;
        
        $target = imagecreatetruecolor($bgsize[0], $bgsize[1]);
        imagecopy($target, $bgimg, 0, 0, 0, 0, $bgsize[0], $bgsize[1]);
        imagedestroy($bgimg);
         
        $jump_type = intval($poster['jump_type']);
        
        foreach($items as $item){
            if(empty($item) || empty($item["type"]) || ($item["show"] != 1 && $item["show"] !== null)){
                continue;
            }
            
            $item['width'] = $item['width'] * 2;
            $item['height'] = $item['height'] * 2;
            $item['left'] = $item['left'] * 2;
            $item['top'] = $item['top'] * 2;
            switch($item["type"]){
                case "qrcode":

                    $page = "pages/index/index";
                    if($jump_type == 1){
                        $page = "pages/user/index";
                    }

                    if($platform == 'wxapp'){

                        $result = Weixin::getUnlimitedQRCode("{$page}?sup_uid={$user['id']}&jump_type={$jump_type}", "share_{$user['uniacid']}_".$user['id'],1);
                        
                        if($result['code'] != 1){
                            break;
                        }
                        $qrcode = cdnurl($result['data']['url'],true);
                    }
                    else{
                        $result = QRcode::create(request()->domain()."/mobile/#/{$page}?sup_uid={$user['id']}&jump_type={$jump_type}&source={$platform}&i=".UNIACID,"qrcodeshare_{$user['uniacid']}_".$user['id']);
                        if($result['code'] != 1){
                            break;
                        }
                        $qrcode = cdnurl($result['data']['url'],true);
                    }
                    $target = self::mergeImage($target, $item, $qrcode);
                    break;
                case "avatar":

                    $domain = $_SERVER['HTTP_HOST'];
                    if(strstr($user["avatar"], 'http')){
                        if(strstr($user["avatar"], $domain) && !strstr($user["avatar"], '.jpeg')){
                            $avatar = replaceSiteroot($avatar);
                        }
                        else{
                            if(strstr($user["avatar"], 'thirdwx.qlogo.cn') || strstr($user["avatar"], '.jpeg')){
                                $extension = "jpg";
                            }
                            else{
                                $parts = explode('.', $user["avatar"]);
                                $extension = end($parts);
                            }
                            $avatar = "/data/avatar_".$user['id'].".".$extension;
                            if(!is_file(ROOT_PATH."public".$avatar)){
                                saveFile($user["avatar"],ROOT_PATH."public/data/avatar_".$user['id'].".".$extension);
                            }
                            
                        }  
                    }
                    
                    $avatar = resizeImage(ROOT_PATH."public".$avatar,200,200);
                    
                    $avatar = cdnurl(str_replace(ROOT_PATH."public","",$avatar));
                    
                    $target = self::mergeImage($target, $item, $avatar);
                    break;
                case "nickname":
                case "sup_code":
                case "mobile":
                case "text":
                    if($item["type"] == 'nickname'){
                        $text = $user['nickname'];
                    }
                    else if($item["type"] == 'sup_code'){
                        $text = "推荐码：".$user['id'];
                    }
                    else if($item["type"] == 'mobile'){
                        if(!empty($user['mobile'])){
                            if($item['show_intact'] == 1){
                                $text = "手机号：".$user['mobile'];
                            }
                            else{
                                $text = "手机号：".secret($user['mobile'],false,3,4);
                            }
                        }
                        else{
                            $text = "";
                        }
                    }
                    else{
                        $text = $item['content'];
                    }
                    if(!empty($text)){
                        $item['fontSize'] = $item['fontSize'] * 2;
                        $target = self::mergeText($target, $item, $text);
                    }
                    break;
            }
        }
        // imagepng($target, $filepath);
        imagejpeg($target, $filepath,30);
        /*
        list($width_thumb, $height_thumb) = $bgsize;
        $final_width = 640;
        $final_height = round(($final_width * $height_thumb) / $width_thumb);
        $target_thumb = imagecreatetruecolor($final_width, 1135);
        imagecopyresized($target_thumb, $target, 0, 0, 0, 0, $final_width, $final_height, $width_thumb, $height_thumb);
        imagepng($target_thumb, $filepath_thumb);
        imagedestroy($target_thumb);
        */
        
        
        imagedestroy($target);
        
        // return ["thumb" => self::getImgUrl($filename_thumb), "poster" => self::getImgUrl($filename)];
        return self::getImgUrl($filename);
    }
    
    private static function getImgUrl($filename){
        return request()->domain() . "/data/poster_wxapp/" . UNIACID . "/" . $filename . "?v=" . time();
    }
    
    private static function createImage($imgUrl){
        if( empty($imgUrl)){
            return "";
        }

        $resp = ihttp_request($imgUrl);
        if(isset($resp["errno"])){
            $urlArr = explode(":", $imgurl);
            if($urlArr[0] == "https"){
                $imgurl = "http:" . $urlArr[1];
                $resp = ihttp_request($imgurl);
            }
        }

        if($resp["code"] == 200 && !empty($resp["content"])){
            return imagecreatefromstring($resp["content"]);
        }

        for($i = 0; $i < 3; $i++){
            $resp = ihttp_request($imgurl);
            if($resp["code"] == 200 && !empty($resp["content"])){
                return imagecreatefromstring($resp["content"]);
            }

        }
        return "";
    }
    
    /**
     * 合并图片
     * @param $target
     * @param $data
     * @param $imgurl
     */

    private static function mergeImage($target = false, $data = [], $imgUrl = "", $local = false){
        if(empty($data) || empty($imgUrl)){
            return $target;
        }

        if(empty($local)){
            $image = self::createImage($imgUrl);
        }
        else{
            $image = imagecreatefromstring($imgUrl);
        }

        $sizes_default = array( "width" => imagesx($image), "height" => imagesy($image) );
        

        $image = self::imageZoom($image, 2);
        if($data["style"] == "circle" || $data["style"] == "radius"){
            $image = self::imageRadius($image, $data["style"] == "circle");
        }

        imagecopyresampled($target, $image, intval($data["left"]), intval($data["top"]), 0, 0, $data["width"], $data["height"], $sizes_default["width"]*2, $sizes_default["height"]*2);
        imagedestroy($image);
        return $target;
    }

    /**
     * 图片缩放
     * @param bool $image
     * @param int $zoom
     * @return resource
     */

    private static function imageZoom($image = false, $zoom = 2)
    {
        $width = imagesx($image);
        $height = imagesy($image);
        $target = imagecreatetruecolor($width * $zoom, $height * $zoom);
        // print_r($zoom.",".$width * $zoom.",". $height * $zoom.",". $width.",". $height);die;
        imagecopyresampled($target, $image, 0, 0, 0, 0, $width * $zoom, $height * $zoom, $width, $height);
        imagedestroy($image);
        return $target;
    }

    /**
     * 图片圆角
     * @param bool $target
     * @param bool $circle
     * @return resource
     */

    private static function imageRadius($target = false, $circle = false)
    {
        $w = imagesx($target);
        $h = imagesy($target);
        $w = min($w, $h);
        $h = $w;
        $img = imagecreatetruecolor($w, $h);
        imagesavealpha($img, true);
        $bg = imagecolorallocatealpha($img, 255, 255, 255, 127);
        imagefill($img, 0, 0, $bg);
        $radius = ($circle ? $w / 2 : 20);
        $r = $radius;
        for( $x = 0; $x < $w; $x++ ) 
        {
            for( $y = 0; $y < $h; $y++ ) 
            {
                $rgbColor = imagecolorat($target, $x, $y);
                if( $radius <= $x && $x <= $w - $radius || $radius <= $y && $y <= $h - $radius ) 
                {
                    imagesetpixel($img, $x, $y, $rgbColor);
                }
                else
                {
                    $y_x = $r;
                    $y_y = $r;
                    if( ($x - $y_x) * ($x - $y_x) + ($y - $y_y) * ($y - $y_y) <= $r * $r ) 
                    {
                        imagesetpixel($img, $x, $y, $rgbColor);
                    }

                    $y_x = $w - $r;
                    $y_y = $r;
                    if( ($x - $y_x) * ($x - $y_x) + ($y - $y_y) * ($y - $y_y) <= $r * $r ) 
                    {
                        imagesetpixel($img, $x, $y, $rgbColor);
                    }

                    $y_x = $r;
                    $y_y = $h - $r;
                    if( ($x - $y_x) * ($x - $y_x) + ($y - $y_y) * ($y - $y_y) <= $r * $r ) 
                    {
                        imagesetpixel($img, $x, $y, $rgbColor);
                    }

                    $y_x = $w - $r;
                    $y_y = $h - $r;
                    if( ($x - $y_x) * ($x - $y_x) + ($y - $y_y) * ($y - $y_y) <= $r * $r ) 
                    {
                        imagesetpixel($img, $x, $y, $rgbColor);
                    }

                }

            }
        }
        return $img;
    }

    /**
     * 合并文字
     * @param $target
     * @param $data
     * @param $text
     */

    private static function mergeText($target = false, $data = array(  ), $text = "")
    {
        if(empty($data) || empty($text)){
            return $target;
        }

        $font = ROOT_PATH . "public/assets/fonts/poster.ttf";
        if(!is_file($font)){
            return $target;
        }

        $colors = self::hex2rgb($data["color"]);
        $color = imagecolorallocate($target, $colors["red"], $colors["green"], $colors["blue"]);
        
        $fontsize = $data['fontSize'];
        
        $textbox = imagettfbbox($fontsize, 0, $font, $text);
        $textwidth = $textbox[4] - $textbox[6];
        $left = intval($data["left"]);
        if($data["align"] == "center"){
            $left = imagesx($target) / 2 - $textwidth / 2;
        }

        imagettftext($target, $fontsize, 0, $left, intval($data["top"]) + $fontsize * 1.5, $color, $font, $text);
        return $target;
    }

    /**
     * hex转rgb
     * @param $colour
     * @return array|bool
     */

    private static 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] );
        }
        else
        {
            if( 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 );
    }
}
?>