<?php
namespace app\common\controller;
use app\common\variable\MsgCode;
use app\common\model\Jobs as JobsModel;
use app\common\model\CompanyContent as CompanyContentModel;
use app\common\model\Posters as PostersModel;
use app\common\model\JobsPosters as JobsPostersModel;
use app\common\model\WechatQrcode as WechatQrcodeModel;
use app\common\QrcodeUtil;
use app\common\UploadFile;
use think\Image;
use helper\Dir;
use helper\Wechat;
class Posters extends Base
{
    public static function getList($G)
    {
        $where=[];
        $where[]=['poster.status','=',1];
        if(isset($G['is_company']))
        $where[]=['poster.is_company','=',$G['is_company']];
        $Data=PostersModel::alias('poster')->where($where)
            ->join('vip vip','vip.level=poster.level AND vip.is_company=1')
            ->order('poster.sort asc,poster.id desc')->field('poster.*,vip.title as vip_name')->paginate(10)->each(function($v){
                $v->url=config('web.imgurl').$v->path;
            });
        if ($Data->items()) {
            return parent::ajaxReturn('',MsgCode::$success,$Data);
        }else{
            return parent::ajaxReturn('暂无数据~',MsgCode::$error);
        }
    }
    public static function getPoster($D)
    {
        if (!empty($D['poster'])){
            if(count($D['poster'])>5)
                return parent::ajaxReturn('最大同时生成五张',MsgCode::$error);
            $Field=[
                'jobs.id,jobs.company_id,jobs.title,jobs.salary_min,jobs.salary_max,jobs.salary_year',
                'contacts.contacts,contacts.contacts_type',
                'company.title as company_name,company.stitle as company_sname,company.logo as company_logo',
                'education.title as education_level',
                'exp_level.title as exp_level',
                'province.title as jobs_province,city.title as jobs_city,area.title as jobs_area',
                'jobs_cate.title as jobs_cate_text'
            ];

            $where=['jobs.id'=>$D['jobs_id'],'jobs.company_id'=>$D['company_id']];
            $JobsModel=JobsModel::alias('jobs')
            ->where($where)
            ->whereNull('jobs.delete_time')
            ->where(['education.alias'=>'jobs/education_level'])
            ->where(['exp_level.alias'=>'jobs/exp_level'])
            ->join('company company','company.id=jobs.company_id')
            ->join('jobs_cate jobs_cate','jobs_cate.id=jobs.jobs_cate3')
            ->join('jobs_contacts contacts','contacts.jobs_id=jobs.id','LEFT')
            ->join('status_alias education','education.value=jobs.education_level')
            ->join('status_alias exp_level','exp_level.value=jobs.exp_level','LEFT')
            ->join('area province','province.id = jobs.jobs_area1','LEFT')
            ->join('area city','city.id = jobs.jobs_area2','LEFT')
            ->join('area area','area.id = jobs.jobs_area3','LEFT')
            ->field(implode(',',$Field))->find();
            if ($JobsModel) {
                $company_content=CompanyContentModel::alias('content')->where(['content.cid'=>$JobsModel->company_id])->field('content.contacts')
                ->find();
                if ($JobsModel->contacts_type)
                    $JobsModel->contacts            =$company_content->contacts;

                if(!$JobsModel->company_logo)
                    $JobsModel->company_logo=config('xy_default_avatar.company_logo');
            }
            if(!$JobsModel)
                return parent::ajaxReturn('职位不存在',MsgCode::$error);
            $PostersModel=PostersModel::where('id','in',$D['poster'])->select();
            $JobsPostersModel=JobsPostersModel::where(['jobs_id'=>$JobsModel->id])->where('pid','in',$D['poster'])->select();
            $JobsPoster=[];
            $Data=[];
            if($JobsPostersModel)
                $Data=$JobsPostersModel->toArray();
            $i=0;
            foreach ($PostersModel as $item) {
            	$Posters=self::createPoster($JobsModel,$item);
            	if(is_array($Posters)){
	            	$id=0;
	            	foreach ($Data as $k => $v) {
	            		if($v['pid']==$item->id){
	            			$id=$v['id'];
	            			break;
	            		}
	            	}
	            	$JobsPoster[$i]=[
						'pid'		=>	$item->id,
						'jobs_id'	=>	$JobsModel->id,
						'path'		=>	$Posters['path'],
	            	];
	            	if($id)
	            		$JobsPoster[$i]['id']=$id;
            		$i++;
            	}
            }
            if (!empty($JobsPoster)) {
            	$JobsPostersNew=new JobsPostersModel;
            	if(!$JobsPostersNew->saveAll($JobsPoster))
            		return parent::ajaxReturn('生成失败',MsgCode::$error);
            }
        }
        return self::getJobsPoster($D);
    }
    public static function getJobsPoster($D)
    {
        $JobsModel=JobsModel::where(['id'=>$D['jobs_id'],'company_id'=>$D['company_id']])->find();
        if(!$JobsModel)
            return parent::ajaxReturn('职位不存在',MsgCode::$error);
        $JobsPostersModel=JobsPostersModel::where(['jobs_id'=>$JobsModel->id])->withAttr('path',function($v,$data){
            return config('web.imgurl').$v;
        })->order('update_time desc')->select();
        $Data=[];
        foreach ($JobsPostersModel as $v) {
            $Data[]=$v->path;
        }
        return parent::ajaxReturn('',MsgCode::$success,$Data);
    }
    public static function createPoster($JobsModel,$PostersModel)
    {
        $qrcode=self::CreateJobsQRCode($JobsModel,$PostersModel);
        if(!$qrcode){
            return '生成二维码失败';
        }
    	$posterFilename='jobs_id_'.$JobsModel->id.'_poster_id_'.$PostersModel->id.'.jpg';
    	$poster='/uploads/jobs/poster/'.$posterFilename;
		if(!file_exists('.'.$PostersModel->path)){
			self::downImage(config('web.imgurl').$PostersModel->path,'.'.$PostersModel->path);
            if (!file_exists('.'.$PostersModel->path))
                return '海报不存在';
		}
    	chmod('.'.$PostersModel->path,0755);
    	$PosterObj=Image::open('.'.$PostersModel->path);
    	$width=$PosterObj->width();
    	$height=$PosterObj->height();
    	$paddingTop=50;
    	$paddingLeft=20;
    	$salary='';
    	if ($JobsModel->salary_min<=0) {
    		$salary='面议';
    	}else{
    		$salary=$JobsModel->salary_min.'~'.$JobsModel->salary_max.'K';
    	}
    	if($JobsModel->salary_year>12)
    		$salary=$salary.' · '.$JobsModel->salary_year.'薪';
    	$PosterObj->text($salary,'static/plugin/Ttf/PingFang_SC_Regular.ttf',32,'#6187ED',[$PostersModel->position_x+$paddingLeft,$PostersModel->position_y+$paddingTop]);
    	$PosterObj->text($JobsModel->title.'【'.$JobsModel->jobs_cate_text.'】','static/plugin/Ttf/PingFang_SC_Regular.ttf',26,'#000000',[$PostersModel->position_x+$paddingLeft,$PostersModel->position_y+110]);
    	$jobs_info='';
    	if($JobsModel->jobs_city)
    		$jobs_info.=$JobsModel->jobs_city.' · ';
    	if($JobsModel->exp_level)
    		$jobs_info.=$JobsModel->exp_level.' · ';
    	if($JobsModel->education_level)
    		$jobs_info.=$JobsModel->education_level;
    	$PosterObj->text($jobs_info,'static/plugin/Ttf/PingFang_SC_Regular.ttf',18,'#343434',[$PostersModel->position_x+$paddingLeft,$PostersModel->position_y+160]);
    	$company_logo='./uploads/company/logo_thumb/company_id_'.$JobsModel->company_id.'.png';
        if(!file_exists('.'.$JobsModel->company_logo)){
            self::downImage(config('web.imgurl').$JobsModel->company_logo,'.'.$JobsModel->company_logo);
            if (!file_exists('.'.$JobsModel->company_logo))
                $JobsModel->company_logo=config('xy_default_avatar.company_logo');
        }
        chmod('.'.$JobsModel->company_logo,0755);
        $companyLogoObj=Image::open('.'.$JobsModel->company_logo);
        $companyLogoObj->thumb(100,100,Image::THUMB_CENTER);
        Dir::create(dirname($company_logo));
        $companyLogoObj->save($company_logo);
        $imgg = self::radius_img($company_logo, 50);
        imagepng($imgg,$company_logo);
        imagedestroy($imgg);
    	$PosterObj->water($company_logo,[$PostersModel->position_x+$paddingLeft,$PostersModel->position_y+220]);
    	$PosterObj->text($JobsModel->contacts,'static/plugin/Ttf/PingFang_SC_Regular.ttf',26,'#000000',[$PostersModel->position_x+$paddingLeft+120,$PostersModel->position_y+230]);
    	$company_name=$JobsModel->company_name;
    	if ($JobsModel->company_sname)
    		$company_name=$JobsModel->company_sname;
    	$PosterObj->text($company_name,'static/plugin/Ttf/PingFang_SC_Regular.ttf',18,'#343434',[$PostersModel->position_x+$paddingLeft+120,$PostersModel->position_y+280]);
    	$PosterObj->water('.'.$qrcode,[$width-($PostersModel->position_x+$paddingLeft+$PostersModel->size+30),$PostersModel->position_y+180]);
        $PosterObj->text(config('web.name').' '.strtoupper(config('web.domain')),'static/plugin/Ttf/PingFang_SC_Regular.ttf',20,'#FFFFFF',Image::WATER_SOUTH,[0,-10]);
    	Dir::create(dirname('.'.$poster));
    	$PosterObj->save('.'.$poster);
    	$status=self::UploadOss($poster,$posterFilename);
    	if($status===1){
	    	return [
	    		'path'	=>	$poster,
	    		'qrcode'=>	$qrcode,
	    	];
    	}else{
    		return '上传对象储存失败';
    	}
    }
    public static function CreateJobsQRCode($JobsModel,$PostersModel)
    {
        $jobs_qr_type=config('xy_company.jobs_qr_type');
        $qrcodePath='/uploads/jobs/'.$jobs_qr_type;
        if (!file_exists('.'.$qrcodePath))
            mkdir('.'.$qrcodePath, 0777, true);
        $qrcodeFilename='jobs_id_'.$JobsModel->id.'_'.$PostersModel->size;
        $qrcode=$qrcodePath.'/'.$qrcodeFilename.'.png';
        if (!file_exists('.'.$qrcode)) {
            switch ($jobs_qr_type) {
                case 'mpqrcode':
                    $WechatQrcodeModel=WechatQrcodeModel::where(['type'=>'jobs','qr_type'=>0,'alias_id'=>$JobsModel->id])->whereTime('expire_time','>',time())->find();
                    if(!$WechatQrcodeModel){
                        $WechatQrcodeModel=new WechatQrcodeModel;
                        $WechatQrcodeModel->type='jobs';
                        $WechatQrcodeModel->qr_type=0;
                        $WechatQrcodeModel->alias_id=$JobsModel->id;
                        $Data=[
                            'scene'=>[
                                'scene_str'=>'jobs_'.$JobsModel->id
                            ]
                        ];
                        $ret=Wechat::createQrScene($Data);
                        if(empty($ret['url']))
                            return false;
                        $WechatQrcodeModel->ticket=$ret['ticket'];
                        $WechatQrcodeModel->expire_seconds=$ret['expire_seconds'];
                        $WechatQrcodeModel->url=$ret['url'];
                        $WechatQrcodeModel->expire_time=time()+$ret['expire_seconds'];
                        $WechatQrcodeModel->save();
                    }
                    $url=$WechatQrcodeModel->url;
                    $logo_url=str_replace('/public/','/',config('web.icon'));
                    $logo_url=str_replace('/uploads','uploads',$logo_url);
                    $qrObj=new QrcodeUtil([
                        'generate'  =>  'writefile',
                        'size'      =>  $PostersModel->size,
                        'logo'      =>  true,
                        'logo_size' =>  round($PostersModel->size/10),
                        'logo_url'  =>  $logo_url,
                        'file_path' =>  '.'.$qrcodePath,
                        'file_name' =>  $qrcodeFilename,
                    ]);
                    if(!$qrObj->createServer($url)){
                        return false;
                    }
                    break;
                case 'miniprogramqrcode':
                    $Data=[
                        'scene'     =>  $JobsModel->id,
                        'page'      =>  'pageA/pages/personal/jobs/jobs',
                        'width'     =>  $PostersModel->size
                    ];
                    $image=Wechat::createWxaQrcode($Data);
                    $ret=json_decode($image);
                    if($ret)
                    	return false;
                    if($image)
                        file_put_contents('.'.$qrcode,$image);
                    if (file_exists('.'.$qrcode)
                        &&$PostersModel->size<280) {
                        $ImageObj=Image::open('.'.$qrcode);
                        $ImageObj->thumb($PostersModel->size,$PostersModel->size+15,Image::THUMB_CENTER);
                        $ImageObj->save('.'.$qrcode);
                    }
                    break;
                default:
                    $url=config('web.url').'/jobs/'.$JobsModel->id.'.html';
                    $logo_url=str_replace('/public/','/',config('web.icon'));
                    $logo_url=str_replace('/uploads','uploads',$logo_url);
                    $qrObj=new QrcodeUtil([
                        'generate'  =>  'writefile',
                        'size'      =>  $PostersModel->size,
                        'logo'      =>  true,
                        'logo_size' =>  round($PostersModel->size/10),
                        'logo_url'  =>  $logo_url,
                        'file_path' =>  '.'.$qrcodePath,
                        'file_name' =>  $qrcodeFilename,
                    ]);
                    if(!$qrObj->createServer($url)){
                        return false;
                    }
                    break;
            }
            $status=self::UploadOss($qrcode,$qrcodeFilename.'.png');
            if (!$status)
                return false;
        }
        return $qrcode;
    }
    public static function CreateCompanyQRCode($CompanyModel,$PostersModel)
    {
        $jobs_qr_type=config('xy_company.jobs_qr_type');
        $qrcodePath='/uploads/company/'.$jobs_qr_type;
        if (!file_exists('.'.$qrcodePath))
            mkdir('.'.$qrcodePath, 0777, true);
        $qrcodeFilename='company_id_'.$CompanyModel->id.'_'.$PostersModel->size;
        $qrcode=$qrcodePath.'/'.$qrcodeFilename.'.png';
        if (!file_exists('.'.$qrcode)) {
            switch ($jobs_qr_type) {
                case 'mpqrcode':
                    $WechatQrcodeModel=WechatQrcodeModel::where(['type'=>'company','qr_type'=>0,'alias_id'=>$CompanyModel->id])->whereTime('expire_time','>',time())->find();
                    if(!$WechatQrcodeModel){
                        $WechatQrcodeModel=new WechatQrcodeModel;
                        $WechatQrcodeModel->type='company';
                        $WechatQrcodeModel->qr_type=0;
                        $WechatQrcodeModel->alias_id=$CompanyModel->id;
                        $Data=[
                            'scene'=>[
                                'scene_str'=>'company_'.$CompanyModel->id
                            ]
                        ];
                        $ret=Wechat::createQrScene($Data);
                        if(empty($ret['url']))
                            return false;
                        $WechatQrcodeModel->ticket=$ret['ticket'];
                        $WechatQrcodeModel->expire_seconds=$ret['expire_seconds'];
                        $WechatQrcodeModel->url=$ret['url'];
                        $WechatQrcodeModel->expire_time=time()+$ret['expire_seconds'];
                        $WechatQrcodeModel->save();
                    }
                    $url=$WechatQrcodeModel->url;
                    $logo_url=str_replace('/public/','/',config('web.icon'));
                    $logo_url=str_replace('/uploads','uploads',$logo_url);
                    $qrObj=new QrcodeUtil([
                        'generate'  =>  'writefile',
                        'size'      =>  $PostersModel->size,
                        'logo'      =>  true,
                        'logo_size' =>  round($PostersModel->size/10),
                        'logo_url'  =>  $logo_url,
                        'file_path' =>  '.'.$qrcodePath,
                        'file_name' =>  $qrcodeFilename,
                    ]);
                    if(!$qrObj->createServer($url)){
                        return false;
                    }
                    break;
                case 'miniprogramqrcode':
                    $Data=[
                        'scene'     =>  $CompanyModel->id,
                        'page'      =>  'pageA/pages/common/company/company',
                        'width'     =>  $PostersModel->size
                    ];
                    $image=Wechat::createWxaQrcode($Data);
                    $ret=json_decode($image);
                    if($ret)
                    	return false;
                    if($image)
                        file_put_contents('.'.$qrcode,$image);
                    if (file_exists('.'.$qrcode)
                        &&$PostersModel->size<280) {
                        $ImageObj=Image::open('.'.$qrcode);
                        $ImageObj->thumb($PostersModel->size,$PostersModel->size+15,Image::THUMB_CENTER);
                        $ImageObj->save('.'.$qrcode);
                    }
                    break;
                default:
                    $url=config('web.url').'/company/'.$CompanyModel->id.'.html';
                    $logo_url=str_replace('/public/','/',config('web.icon'));
                    $logo_url=str_replace('/uploads','uploads',$logo_url);
                    $qrObj=new QrcodeUtil([
                        'generate'  =>  'writefile',
                        'size'      =>  $PostersModel->size,
                        'logo'      =>  true,
                        'logo_size' =>  round($PostersModel->size/10),
                        'logo_url'  =>  $logo_url,
                        'file_path' =>  '.'.$qrcodePath,
                        'file_name' =>  $qrcodeFilename,
                    ]);
                    if(!$qrObj->createServer($url)){
                        return false;
                    }
                    break;
            }
            $status=self::UploadOss($qrcode,$qrcodeFilename.'.png');
            if (!$status)
                return false;
        }
        return $qrcode;
    }
    public static function CreateArticleQRCode($ArticleModel,$PostersModel)
    {
        $jobs_qr_type=config('xy_company.jobs_qr_type');
        $qrcodePath='/uploads/article/'.$jobs_qr_type;
        if (!file_exists('.'.$qrcodePath))
            mkdir('.'.$qrcodePath, 0777, true);
        $qrcodeFilename='article_id_'.$ArticleModel->id.'_'.$PostersModel->size;
        $qrcode=$qrcodePath.'/'.$qrcodeFilename.'.png';
        if (!file_exists('.'.$qrcode)) {
            switch ($jobs_qr_type) {
                case 'mpqrcode':
                    $WechatQrcodeModel=WechatQrcodeModel::where(['type'=>'article','qr_type'=>2,'alias_id'=>$ArticleModel->id])->find();
                    if(!$WechatQrcodeModel){
                        $WechatQrcodeModel=new WechatQrcodeModel;
                        $WechatQrcodeModel->type='article';
                        $WechatQrcodeModel->qr_type=2;
                        $WechatQrcodeModel->alias_id=$ArticleModel->id;
                        $Data=[
                            'scene'=>[
                                'scene_str'=>'article_'.$ArticleModel->id
                            ]
                        ];
                        $ret=Wechat::createQrLimit($Data);
                        if(empty($ret['url']))
                            return false;
                        $WechatQrcodeModel->ticket=$ret['ticket'];
                        $WechatQrcodeModel->url=$ret['url'];
                        $WechatQrcodeModel->save();
                    }
                    $url=$WechatQrcodeModel->url;
                    $logo_url=str_replace('/public/','/',config('web.icon'));
                    $logo_url=str_replace('/uploads','uploads',$logo_url);
                    $qrObj=new QrcodeUtil([
                        'generate'  =>  'writefile',
                        'size'      =>  $PostersModel->size,
                        'logo'      =>  true,
                        'logo_size' =>  round($PostersModel->size/10),
                        'logo_url'  =>  $logo_url,
                        'file_path' =>  '.'.$qrcodePath,
                        'file_name' =>  $qrcodeFilename,
                    ]);
                    if(!$qrObj->createServer($url)){
                        return false;
                    }
                    break;
                case 'miniprogramqrcode':
                    $Data=[
                        'scene'     =>  $ArticleModel->id,
                        'page'      =>  'pageA/pages/common/article/content',
                        'width'     =>  $PostersModel->size
                    ];
                    $image=Wechat::createWxaQrcode($Data);
                    $ret=json_decode($image);
                    if($ret)
                    	return false;
                    if($image)
                        file_put_contents('.'.$qrcode,$image);
                    break;
                default:
                    $url=config('web.url').'/article/content/'.$ArticleModel->id.'.html';
                    $logo_url=str_replace('/public/','/',config('web.icon'));
                    $logo_url=str_replace('/uploads','uploads',$logo_url);
                    $qrObj=new QrcodeUtil([
                        'generate'  =>  'writefile',
                        'size'      =>  $PostersModel->size,
                        'logo'      =>  true,
                        'logo_size' =>  round($PostersModel->size/10),
                        'logo_url'  =>  $logo_url,
                        'file_path' =>  '.'.$qrcodePath,
                        'file_name' =>  $qrcodeFilename,
                    ]);
                    if(!$qrObj->createServer($url)){
                        return false;
                    }
                    break;
            }
            $status=self::UploadOss($qrcode,$qrcodeFilename.'.png');
            if (!$status)
                return false;
        }
        $ArticleModel->qrcode=$qrcode;
        $ArticleModel->save();
        return $qrcode;
    }
    public static function UploadOss($saveFile,$saveName)
    {
    	$status=1;
        if (config('xy_oss.status')) {
        	switch (config('xy_oss.service_provider')) {
        		case 'aliyun':
		            $status=UploadFile::updateAliyunOss($saveFile,$saveName);
        			break;
        		case 'qcloud':
		            $status=UploadFile::updateTencentQcloud($saveFile);
        			break;
        		case 'qiniu':
		            $status=UploadFile::updateQiniu($saveFile,$saveName);
        			break;
        	}
        }
        return $status;
    }
    /**
	 * blog:http://www.zhaokeli.com
	 * 处理圆角图片
	 * @param  string  $imgpath 源图片路径
	 * @param  integer $radius  圆角半径长度默认为15,处理成圆型
	 * @return [type]           [description]
	 */
	public static function radius_img($imgpath = '', $radius = 15) {
		$ext     = pathinfo($imgpath);
		$src_img = null;
		switch ($ext['extension']) {
		case 'jpg':
			$src_img = imagecreatefromjpeg($imgpath);
			break;
		case 'png':
			$src_img = imagecreatefrompng($imgpath);
			break;
		}
		$wh = getimagesize($imgpath);
		$w  = $wh[0];
		$h  = $wh[1];
		// $radius = $radius == 0 ? (min($w, $h) / 2) : $radius;
		$img = imagecreatetruecolor($w, $h);
		//这一句一定要有
		imagesavealpha($img, true);
		//拾取一个完全透明的颜色,最后一个参数127为全透明
		$bg = imagecolorallocatealpha($img, 255, 255, 255, 127);
		imagefill($img, 0, 0, $bg);
		$r = $radius; //圆 角半径
		for ($x = 0; $x < $w; $x++) {
			for ($y = 0; $y < $h; $y++) {
				$rgbColor = imagecolorat($src_img, $x, $y);
				if (($x >= $radius && $x <= ($w - $radius)) || ($y >= $radius && $y <= ($h - $radius))) {
					//不在四角的范围内,直接画
					imagesetpixel($img, $x, $y, $rgbColor);
				} else {
					//在四角的范围内选择画
					//上左
					$y_x = $r; //圆心X坐标
					$y_y = $r; //圆心Y坐标
					if (((($x - $y_x) * ($x - $y_x) + ($y - $y_y) * ($y - $y_y)) <= ($r * $r))) {
						imagesetpixel($img, $x, $y, $rgbColor);
					}
					//上右
					$y_x = $w - $r; //圆心X坐标
					$y_y = $r; //圆心Y坐标
					if (((($x - $y_x) * ($x - $y_x) + ($y - $y_y) * ($y - $y_y)) <= ($r * $r))) {
						imagesetpixel($img, $x, $y, $rgbColor);
					}
					//下左
					$y_x = $r; //圆心X坐标
					$y_y = $h - $r; //圆心Y坐标
					if (((($x - $y_x) * ($x - $y_x) + ($y - $y_y) * ($y - $y_y)) <= ($r * $r))) {
						imagesetpixel($img, $x, $y, $rgbColor);
					}
					//下右
					$y_x = $w - $r; //圆心X坐标
					$y_y = $h - $r; //圆心Y坐标
					if (((($x - $y_x) * ($x - $y_x) + ($y - $y_y) * ($y - $y_y)) <= ($r * $r))) {
						imagesetpixel($img, $x, $y, $rgbColor);
					}
				}
			}
		}
		return $img;
	}
	public static function downImage($url,$filename)
	{
        if(!config('xy_oss.status'))
            return;
        $ch = curl_init($url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$content = curl_exec($ch);
		curl_close($ch);
        file_put_contents($filename, $content);
	}
}