<?php
namespace Frontend\Controller;

use Think\Controller;
use Common\Logic\Wechat\WechatWebApi;

class IndexController extends Controller
{
    public function __construct()
    {
        parent::__construct();
    }

    public function index()
    {

        session_start();
        if (!$_SESSION["headimgurl"]) {
            redirect('http://mallapp.guoguodz.com/h5_pic/appwww/index.php/WxAuthorize');
            return;
        }
        if($_SERVER['QUERY_STRING']){
            $url = '?'.$_SERVER['QUERY_STRING'];
        }
        $link = 'http://'.$_SERVER["HTTP_HOST"].'/h5_pic/appwww/index.php'.$url;

        $this->assign('link',$link);
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $nonceStr = "";
        for ($i = 0; $i < 16; $i++) {
            $nonceStr .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        $weChatApi = WechatWebApi::getInstance();
        $wxToken = S('wx_token');
        if (!$wxToken) {
            $_data = $weChatApi->getToken();
            if (!$_data) $this->error(var_export($weChatApi->getError(), true));
            S('wx_token', $_data['access_token'], 6800);

            $wxToken = $_data['access_token'];
        }

        $jsapi_ticket = S('jsapi_ticket');
        if(!$jsapi_ticket){
            $_data = $weChatApi->getJsTicket($wxToken);
            if (!$_data) $this->error(var_export($weChatApi->getError(), true));
            S('jsapi_ticket', $_data['ticket'], 6800);
            $jsapi_ticket = $_data['ticket'];
        }
        $argu = array();
        $argu['appId'] = $weChatApi->getAppId();
        $argu['url'] = $link;
        $argu['nonceStr'] = $nonceStr;
        $argu['headimg'] = $_SESSION["headimgurl"];
        $argu['wx_name'] = $_SESSION["wx_name"];
        $argu['timestamp'] = NOW_TIME;
        $wxToken = $wxToken;
        $argu['jsapi_ticket'] = $jsapi_ticket;
        $string = "jsapi_ticket=".$argu['jsapi_ticket']."&noncestr=".$argu['nonceStr']."&timestamp=".$argu['timestamp']."&url=".$argu['url'];
        $argu['signature'] = sha1(trim($string));
        $this->assign($argu);

        $this->display('index');
    }

    //上传图片
    public function upload (){
        $link = 'http://mallapp.guoguodz.com/h5_pic/appwww/';
//        $link = 'www.h5_pic.net/';
        $mo = I('post.mo'); //mo=1 点击切换生成 mo=2 自由填写
        $mtxt = I('post.mtxt');
        $txt1 = I('post.txt1');
        $txt2 = I('post.txt2');
        $txt3 = I('post.txt3');
        $txt4 = I('post.txt4');
        $sign_pic = I('post.sign_pic');
        $pimg = I('post.pimg');
        $user = I('post.user');
        //主图
        $pic_url = $link.$this->get_base64_img($pimg);
//        $pic_url = 'http://www.h5_pic.net/H5/pimg/1576225374.png';
        //水印图
        $mtxt = 'http://mallapp.guoguodz.com/h5_pic/appwww/Assets/Admin/images/m'.$mtxt.'.png';

        //logo
        $logo = 'http://mallapp.guoguodz.com/h5_pic/appwww/Assets/Admin/images/logo.png';

        //二维码
        $qr_code = 'http://mallapp.guoguodz.com/h5_pic/appwww/Assets/Admin/images/qr_code.png';

        //微信名称
        $user_str = 'Via:'.$user;

        //指定要缩放到的宽度
        $maxW = 640;

        //指定要缩放到的高度
        $maxH = 1048;

        //mo=1 点击切换生成 mo=2 自由填写
        $bg = imagecreatetruecolor($maxW, $maxH);
        $background = imagecolorallocate($bg, 255, 255, 255);
        imagefill($bg,0,0,$background);

        $im = imagecreatefromjpeg($pic_url);

//        $im = imagecreatefrompng($pic_url);
        imagefilter($im,IMG_FILTER_GRAYSCALE);
        $oldW = imagesx($im);
        $oldH = imagesy($im);
        $source_ratio = $oldW / $oldH;
        $target_ratio = 1028 / 620;
        $source_width = $oldW;
        $source_height = $oldH;
        if ($source_ratio > $target_ratio){
            // image-to-height
            $newW = $source_width;
            $newH = $source_width * $target_ratio;
        }elseif ($source_ratio < $target_ratio){
            //image-to-widht
            $newW = $source_height / $target_ratio;
            $newW = $newW - 30;
            $newH = $source_height;
        }else{
            //image-size-ok
            $newW = $source_width;
            $newH = $source_height;
        }

//        //判断那个边比较长，利用较长的边求得比例
//        if($oldW>$oldH){
//        //求得比例
//            $b = $oldW/$maxW;
//        //获取缩放之后的宽高
//            $newW = $oldW/$b*0.2;
//            $newH = $oldH/$b*0.2;
//        }else{
//        //求得比例
//            $b = $oldH/$maxH;
//        //获取缩放之后的宽高
//            $newW = $oldW/$b*0.2;
//            $newH = $oldH/$b*0.2;
//
//        }

        imagecopyresampled($bg, $im, 10, 10, 0, 0, 620, 1028, $newW, $newH);
        if($mo == 1){
            $stamp = imagecreatefrompng($mtxt);
            $code = imagecreatefrompng($qr_code);
            $logo = imagecreatefrompng($logo);

            // 利用图像的宽度和水印的外边距计算位置，并且将水印复制到图像上
            imagecopymerge($bg, $stamp, 0, 0, 0, 0, 640, 261, 100);
            imagecopymerge($bg, $code, 5, 880, 0, 0, 130, 130, 100);
            imagecopymerge($bg, $logo, 0, 930, 0, 10, 640, 180, 100);

            $text_str = PROJECT_PATH.'appwww/msyh.ttf';
            $textcolor = imagecolorallocate($bg, 255, 255, 255);
            imagettftext($bg, 24, 0, 10, 298, $textcolor, $text_str, mb_convert_encoding($user_str, "utf-8"));
            // 输出图像并释放内存
            //header('Content-type: image/png');
        }else{
            $code = imagecreatefrompng($qr_code);
            $logo = imagecreatefrompng($logo);
            imagecopymerge($bg, $code, 5, 880, 0, 0, 130, 130, 100);
            imagecopymerge($bg, $logo, 0, 930, 0, 10, 640, 180, 100);
            $text_str = PROJECT_PATH.'appwww/msyh.ttf';
            $textcolor = imagecolorallocate($bg, 255, 255, 255);
            
            $t1 = mb_convert_encoding($txt1, "utf-8");
            $t2 = mb_convert_encoding($txt2, "utf-8");
            $t3 = mb_convert_encoding($txt3, "utf-8");
            $t4 = mb_convert_encoding($txt4, "utf-8");
            $rectangle_color = imagecolorallocate($bg, 255, 0, 0);
            imagefilledrectangle($bg, 0, 135, strlen($t3)*18.5, 187, $rectangle_color);
            imagefilledrectangle($bg, 0, 195, strlen($t4)*18.5, 245, $rectangle_color);
            
            
            imagettftext($bg, 38, 0, 10, 66, $textcolor, $text_str, mb_convert_encoding($txt1, "utf-8"));
            imagettftext($bg, 38, 0, 10, 126, $textcolor, $text_str, mb_convert_encoding($txt2, "utf-8"));
            imagettftext($bg, 38, 0, 10, 180, $textcolor, $text_str, mb_convert_encoding($txt3, "utf-8"));
            imagettftext($bg, 38, 0, 10, 238, $textcolor, $text_str, mb_convert_encoding($txt4, "utf-8"));
            imagettftext($bg, 24, 0, 10, 288, $textcolor, $text_str, mb_convert_encoding($user_str, "utf-8"));
        }
        $text_c = imagecolorallocate($bg, 255, 255, 255);
        imagettftext($bg, 12, 0, 10, 1030, $text_c, $text_str, mb_convert_encoding('识别二维码参与H5互动', "utf-8"));
        $path = "H5/pic/";
        if (!is_dir($path)){
            mkdir($path,0777,true);
        }
        imagepng($bg,$path.$sign_pic.'.png');
        imagedestroy($bg);

        //返回处理后的水印图片
        $url = 'http://mallapp.guoguodz.com/h5_pic/appwww/H5/pic/'.$sign_pic.'.png';
        $data = ['url'=>$url,'msg'=>'ok'];
        $this->ajaxReturn($data);
    }

    //base64转图片
    function get_base64_img($base64){
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64, $result)){
            $type = $result[2];
            $path = "H5/pimg/";
            if (!is_dir($path)){
                mkdir($path,0777,true);
            }
            $new_file = $path.time().".{$type}";
            $data = file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64)));
            if ($data){
                return $new_file;
            }else{
                return  false;
            }
        }
    }
}
