<?php


namespace Api\PhpServices\ShopImage;

use Api\PhpServices\Ksy\Ksyun;
use Api\PhpUtils\Ksy\Ks3Util;
use Api\PhpUtils\Log\FileLog;
use Endroid\QrCode\ErrorCorrectionLevel;
use Endroid\QrCode\QrCode;

class GetImage
{
    private $font_b = __DIR__.'/fonts/OPPOSans-B.ttf';
    private $font_m = __DIR__.'/fonts/OPPOSans-M.ttf';
    private $font_l = __DIR__.'/fonts/OPPOSans-L.ttf';
    private $font_r = __DIR__.'/fonts/OPPOSans-R.ttf';
    private $font_h = __DIR__.'/fonts/OPPOSans-H.ttf';


    /**
     * @param string $shop_name 店铺名
     * @param string $goods_name 券名
     * @param float $goods_price 券价格
     * @param string $addr 商家地址
     * @param string $goods_desc 商品描述说明
     */
    public function getCoupon(string $shop_name, string $goods_name, float $goods_price, string $addr, string $goods_desc=""){
        //创建画布
        $bg     = __DIR__.'/images/1_bg.png';
        list($bg_w,$bg_h) = getimagesize($bg);
        $im         = imagecreatetruecolor($bg_w, $bg_h);
        $bg_im      = imagecreatefrompng($bg);
        $col = imagecolorallocatealpha($im, 255,255,255,127);
        imagefill($im, 0, 0, $col);
        imagecopyresized($im, $bg_im, 0, 0, 0, 0, $bg_w, $bg_h, $bg_w, $bg_h);

        // 店名
        imagettftext($im, 27,0, 60, 90, 333333 ,$this->font_m, $this->textLength($shop_name,9, true));

        // 券名
        $color = ImageColorAllocate ($im, 255, 255, 255);
        $line_1 = mb_substr($goods_name,0,14);
        imagettftext($im, 27,0, 300, 210, $color ,$this->font_m, $line_1);
        if(mb_strlen($goods_name)>14){
            if(mb_strlen($goods_name)>22){
                $line_2 = mb_substr($goods_name,14,8)."...";
            }else{
                $line_2 = mb_substr($goods_name,14);
            }
            imagettftext($im, 27,0, 300, 260, $color ,$this->font_m, $line_2);
        }

        // 价格
        $color = ImageColorAllocate ($im, 51, 51, 51);
        imagettftext($im, 22,0, 678, 260, $color ,$this->font_m, "¥".$goods_price);

        // 备注
        if(strlen($goods_desc)){
            $line_height = 60;
            $res = $this->getTextByLine($goods_desc, 23, 3);
            if(isset($res[0])){
                $color = ImageColorAllocate ($im, 239,115,64);
                imagettftext($im, 27,0, 60, 382, $color ,$this->font_m, $res[0]);
            }
            if(isset($res[1])){
                $color = ImageColorAllocate ($im, 239,115,64);
                imagettftext($im, 27,0, 60, 382+$line_height, $color ,$this->font_m, $res[1]);
            }
            if(isset($res[2])){
                $color = ImageColorAllocate ($im, 239,115,64);
                imagettftext($im, 27,0, 60, 382+2*$line_height, $color ,$this->font_m, $res[2]);
            }
        }

        // 位置
        imagettftext($im, 24,0, 96, 636, 333333 ,$this->font_m, $this->textLength($addr,19));


        Header("Content-Type: image/png");
        imagepng ($im);
        imagedestroy($im);
    }

    /**
     * @param string $code 二维码扫描后内容
     */
    public function getLeaderShare(string $code){
        $bg     = __DIR__.'/images/2-bg.png';
        list($bg_w,$bg_h) = getimagesize($bg);
        $im         = imagecreatetruecolor($bg_w, $bg_h);
        $bg_im      = imagecreatefrompng($bg);
        imagecopyresized($im, $bg_im, 0, 0, 0, 0, $bg_w, $bg_h, $bg_w, $bg_h);


        $logo   = __DIR__.'/images/2-logo.png';
        $qr = new QR($code);
        $qr->setLogoUrl($logo);
        $qr->setLogoSize(50);
        $qr_string = $qr->get();
        $qr_img = imagecreatefromstring($qr_string);
        list($qr_w,$qr_h) = getimagesizefromstring($qr_string);
        imagecopyresized($im, $qr_img, 155, 345, 0, 0, 230, 230, $qr_w, $qr_h);

        Header("Content-Type: image/png");
        imagepng ($im);

        imagedestroy($im);
        imagedestroy($bg_im);
        imagedestroy($qr_img);
    }

    /**
     * @param string $code 二维码扫描后内容
     *
     */
    public function getShare(string $code){
        $qrCode = new QrCode($code);
        header('Content-Type: '.$qrCode->getContentType());
        echo $qrCode->writeString();die;
    }

    /**
     * @param string $head_img 头像url地址
     * @param string $goods_img 商品图片url地址
     * @param string $nickname 用户昵称
     * @param string $goods_name 商品名
     * @param string $qr_string 二维码扫描后的内容
     * @param float $price 价格
     * @param float|int $old_price 优惠前的价格
     * @param int $buy_count 购买数
     * @return bool
     */
    public function getGoods(string $head_img, string $goods_img, string $nickname, string $goods_name, string $qr_string, float $price, float $old_price = 0, int $buy_count=0){
        // 画底图
        $bg     = __DIR__.'/images/3-bg.png';
        list($bg_w,$bg_h) = getimagesize($bg);
        $im = imagecreatetruecolor($bg_w, $bg_h);
        $col = imagecolorallocatealpha($im, 255,255,255,127);
        imagefill($im, 0, 0, $col);

        $bg_im      = imagecreatefrompng($bg);
        imagecopyresized($im, $bg_im, 0, 0, 0, 0, $bg_w, $bg_h, $bg_w, $bg_h);

        // 头像
        $head_path  = $this->curlImage($head_img, '../data/tmp/',"PG_".time().$this->genUniqId());
        if(!$head_path){
            return false;
        }
        list($head_w,$head_h)   = getimagesize($head_path);
        $head_im_old = imagecreatefromstring(file_get_contents($head_path));
        $head_size = 108;
        $head_im = $this->changeImSize($head_im_old, $head_w,$head_h,$head_size,$head_size);
        imagecopyresized($im, $head_im, 57, 39, 0, 0, $head_size, $head_size,$head_size, $head_size);

        // 用户名+向你推荐
        imagettftext($im, 19,0, 183, 82, 333333 ,$this->font_m, $this->substrName($nickname)."向你推荐");
        imagettftext($im, 16,0, 183, 119, 666666 ,$this->font_m, "这个宝贝值得买，物美价廉，倾心推荐～");

        // 用户推荐
        $tuijian_path = __DIR__.'/images/3_tag.png';
        list($tuijian_w,$tuijian_h)   = getimagesize($tuijian_path);
        $tuijian_img = imagecreatefrompng($tuijian_path);
        imagecopyresized($im, $tuijian_img, 362, 54, 0, 0, $tuijian_w, $tuijian_h, $tuijian_w, $tuijian_h);

        // 商品图
        $goods_path  = $this->curlImage($goods_img, '../data/tmp/',"PG_".time().$this->genUniqId());
        if(!$goods_path){
            return false;
        }
        list($goods_w,$goods_h)   = getimagesize($goods_path);
        $goods_im_old = imagecreatefromstring(file_get_contents($goods_path));
        $goods_size = 717;
        $goods_im = $this->changeImSize($goods_im_old, $goods_w,$goods_h,$goods_size,$goods_size);
        imagecopyresized($im, $goods_im, 47, 173, 0, 0, $goods_size, $goods_size,$goods_size, $goods_size);

        // 底部二维码
        //$qr = new QR($qr_string);
        $qr_size = 170;
        // $qr->setSize($qr_size);
        // $qr->setRoundBlockSize(QrCode::ROUND_BLOCK_SIZE_MODE_MARGIN);
        // $qr_string = $qr->get();

        $qr = new QrCode($qr_string);
        $qr->setSize($qr_size);
        $qr_string = $qr->writeString();
        //$qr_string = $qr->get();
        $qr_img = imagecreatefromstring($qr_string);
        list($qr_w,$qr_h) = getimagesizefromstring($qr_string);
        imagecopyresized($im, $qr_img, 0, 1065, 0, 0, $qr_size, $qr_size, 190, 190);

        // 底部文字
        imagettftext($im, 21,0, 295, 1160, 333333 ,$this->font_m, "长按扫码快速抢券");
        imagettftext($im, 16,0, 295, 1200, 666666 ,$this->font_r, "分享自 生活圈APP");

        // 底部logo
        $logo_path = __DIR__.'/images/3_logo.png';
        list($logo_w,$logo_h)   = getimagesize($logo_path);
        $logo_im = imagecreatefrompng($logo_path);
        imagecopyresized($im, $logo_im, 662, 1097,  0, 0, $logo_w, $logo_h, $logo_w, $logo_h);

        // 价格
        $color = ImageColorAllocate ($im, 255, 62, 62);
        imagettftext($im, 25,0, 48, 957, $color ,$this->font_b, "¥".$price);

        // 老价格
        if($old_price){
            $color = ImageColorAllocate ($im, 187, 187, 187);
            imagettftext($im, 13,0, 173, 957, $color ,$this->font_h, "¥".$old_price);

            $del_path = __DIR__.'/images/3_del.png';
            list($del_w,$del_h)   = getimagesize($del_path);
            $del_im = imagecreatefrompng($del_path);
            imagecopyresized($im, $del_im, 178, 949,  0, 0,$del_w,$del_h,$del_w,$del_h);
        }

        // 商品名
        $goods_name = $this->textLength($goods_name, 20);
        imagettftext($im, 25,0, 48, 1018, 333333 ,$this->font_m, $goods_name);

        // 购买人数
        if($buy_count){
            if($buy_count/1>10000){
                $buy_count_string = number_format($buy_count/10000,1) ."万人已关注";
            }else{
                $buy_count_string = $buy_count."人已关注";
            }

            $user_path = __DIR__.'/images/3_user_count.png';
            list($user_w,$user_h)   = getimagesize($user_path);
            $user_im = imagecreatefrompng($user_path);
            $color = ImageColorAllocate ($im, 255, 62, 62);
            imagettftext($user_im, 17,0, 18, 30, $color ,$this->font_r, $buy_count_string);
            imagecopyresized($im, $user_im, 270, 924,  0, 0, $user_w,$user_h, $user_w,$user_h);
        }


        Header("Content-Type: image/png");
        imagepng ($im);

        unlink($head_path);
        unlink($goods_path);

        imagedestroy($im);
        imagedestroy($bg_im);
        imagedestroy($head_im_old);
        imagedestroy($head_im);
        imagedestroy($goods_im_old);
        imagedestroy($goods_im);
        imagedestroy($tuijian_img);
        imagedestroy($qr_img);
        imagedestroy($logo_im);
        if($old_price){
            imagedestroy($del_im);
        }
        imagedestroy($user_im);
    }

    private function changeImSize($old_im, $old_width, $old_height, $new_width, $new_height){
        $image_thump = imagecreatetruecolor ( $new_width, $new_height );
        imagecopyresampled ( $image_thump, $old_im, 0, 0, 0, 0, $new_width, $new_height, $old_width, $old_height );
        return $image_thump;
    }


    private function curlImage($url, $save_dir='',$filename='',$type=0){
        $mimes = array(
            'image/bmp'=>'bmp',
            'image/gif'=>'gif',
            'image/jpeg'=>'jpg',
            'image/png'=>'png',
            'image/tiff'=>'tiff',
            'image/x-icon'=>'ico',
            'mage/vnd.wap.wbmp'=>'wbmp',
            'image/fax'=>'fax',
            'image/pnetvue'=>'net',
            'image/vnd.rn-realpix'=>'rp'
        );

        //创建保存目录
        if(!file_exists($save_dir)&&!mkdir($save_dir,0777,true)){
            return false;
        }
  
        // 获取响应头
        if(($headers = get_headers($url, 1))!==false){
            $type = $headers['Content-Type'];
            if(isset($mimes[$type]))
            {
                $this->extension = $mimes[$type];
                $file_path = $save_dir.$filename.".".$this->extension;
                $contents = file_get_contents($url);
                if(file_put_contents($file_path , $contents))
                {
                    return $save_dir.$filename.".".$this->extension;
                }
            }
        }
    }


    private function curlImageBak($url, $save_dir='',$filename='',$type=0){
        if(trim($url)==''){
            return array('file_name'=>'','save_path'=>'','error'=>1);
        }
        if(trim($save_dir)==''){
            $save_dir='./';
        }
        $ext=strrchr($url,'.');
        if(trim($filename)==''){//保存文件名
            if($ext!='.gif'&&$ext!='.jpg'){
                return array('file_name'=>'','save_path'=>'','error'=>3);
            }
            $filename=time().$ext;
        }else{
            $filename = $filename.$ext;
        }
        if(0!==strrpos($save_dir,'/')){
            $save_dir.='/';
        }
        //创建保存目录
        if(!file_exists($save_dir)&&!mkdir($save_dir,0777,true)){
            return false;
        }
        //获取远程文件所采用的方法
        if($type){
            $ch=curl_init();
            $timeout=5;
            curl_setopt($ch,CURLOPT_URL,$url);
            curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
            curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
            $img=curl_exec($ch);
            curl_close($ch);
        }else{
            ob_start();
            readfile($url);
            $img=ob_get_contents();
            ob_end_clean();
        }
        //$size=strlen($img);
        //文件大小
        $fp2=@fopen($save_dir.$filename,'a');
        fwrite($fp2,$img);
        fclose($fp2);
        unset($img,$url);
        return $save_dir.$filename;
    }

    private function genUniqId() {
        if (function_exists("random_bytes")) {
            $bytes = random_bytes(ceil(8));
            return substr(bin2hex($bytes), 0, 16);

        } elseif (function_exists("openssl_random_pseudo_bytes")) {
            $bytes = openssl_random_pseudo_bytes(ceil(8));
            return substr(bin2hex($bytes), 0, 16);

        } else {
            $pre = rand(1, 4095);
            return uniqid(sprintf("%03x", $pre));
        }
    }

    private function substrName($name){
        if(strlen($name)>3){
            return mb_substr($name,0,1)."*".mb_substr($name,-1,1);
        }
        return $name;
    }

    private function textLength($text, $length, $del=false){
        if(mb_strlen($text) < $length){
            return $text;
        }
        if($del){
            return mb_substr($text, 0, $length-3)."...";
        }
        return mb_substr($text, 0, $length)."...";
    }

    private function getTextByLine($text, $len, $max_line){
        $res = [];

        $start = 0;
        for ($i =0; $i<$max_line; $i++){
            if($i+1 == $max_line){      // 最后一行
                if($start+$len-1 > mb_strlen($text)){
                    $res[] = mb_substr($text, $start);
                }else{
                    $res[] = mb_substr($text, $start, $len-4)."...";
                }
                break;
            }
            $res[] =  mb_substr($text, $start, $len-1);
            $start = ($len-1)*($i+1);
        }
        return $res;
    }
    public function buildShareImgByGoodsAvatarSrc($goodsAvatarSrc){
        $tmpImg = '/tmp/'.md5($goodsAvatarSrc);
        file_put_contents($tmpImg,file_get_contents($goodsAvatarSrc));
        if(!is_file($tmpImg)){
            return '';
        }
        $imgType = getimagesize($tmpImg);
        $descW = 500;
        $descH = $imgType[1]/$imgType[0] * $descW;
        if($descH > 280){
            $descH = 280;
        }
        $baseRS = imagecreatefrompng(__DIR__.DIRECTORY_SEPARATOR.'images'.DIRECTORY_SEPARATOR.'goods_share_bg.png');
        if(!$baseRS){
            unlink($tmpImg);
            return '';
        }
        switch ($imgType[2]){
            case  IMG_PNG:
                $srcRS = imagecreatefrompng($tmpImg);
                break;
            case 3:
                $srcRS = imagecreatefrompng($tmpImg);
                break;
            case IMG_JPEG:
                $srcRS = imagecreatefromjpeg($tmpImg);
                break;
            case IMG_GIF:
                $srcRS = imagecreatefromgif($tmpImg);
                break;
        }
        if(!isset($srcRS) || !$srcRS){
            unlink($tmpImg);
            return '';
        }
        unlink($tmpImg);
        $res = imagecopyresized($baseRS,$srcRS,0,0,0,0,$descW,$descH,$imgType[0],$imgType[1] );
        if(!$res){
            imagedestroy($srcRS);
            imagedestroy($baseRS);
            return '';
        }
        ob_start();
        //header('Content-type:Images/png');
        $ret = imagepng($baseRS,null,9);
//        $imgContent = file_get_contents($tmpImg);
        $imgContent = ob_get_clean();
        if($ret){
            imagedestroy($srcRS);
            imagedestroy($baseRS);
            if($imgContent){
                return $this->uploadImage($imgContent);
            }
            return '';
        }else{
            imagedestroy($srcRS);
            imagedestroy($baseRS);
        }
        return '';
    }
    private function uploadImage($fileContent){
        $appid = 'merchant-b';
        $scenario = 'id_card';
        $object = Ksyun::getObjectAndBucket($appid,$scenario);
        $bucket = $object['bucket'];
        $objectKey = $object['objectId'].'.jpeg';

        $str = Ks3Util::put_object($fileContent,$bucket,$objectKey, $timeout = 5000);
        $url = Ksyun::getUrlFromKsyn($bucket.'/'.$objectKey, $appid);
        return $url;
    }
}
