<?php
/*
|--------------------------------------------------------------------------
| 查看图片的几个方法
|--------------------------------------------------------------------------
*/
namespace Upload\Src;

use Dever;
use Upload\Src\Store\Handle;
//use Upload\Src\Lib\Img;
use Dever\Support\Img;

class View
{
    public function getFileName()
    {
        $image['file']  = Dever::input('file');
        $image['key']   = Dever::input('key');
        
        //file_put_contents(DEVER_PATH . 'web/data/upload.txt', var_export($image, true)); 
        if ($image['file']) {
            $handle = new Handle($image);

            $this->output = $handle->name();
        }
    }
    
    public function files()
    {
        $data = array();

        $key = Dever::input('key');
        $cate = Dever::input('cate');
        $name = Dever::input('name');
        $tag = Dever::input('tag');
        $data['cur'] = Dever::input('cur');
        $data['search_pg'] = Dever::input('pg', 1);

        $param = array();
        $param['upload'] = $key;
        if ($name) {
            $param['source_name'] = $name;
            $param['name'] = $name;
        }
        if ($cate && $cate > 0) {
            $param['cate'] = $cate;
        }

        $data['search_cate'] = $cate;
        $data['search_tag'] = $tag;
        $data['search_name'] = $name;
        $data['key'] = $key;

        if (strstr($key, '_')) {
            $temp = explode('_', $key);
            if (is_numeric($temp[0]) && $temp[0] > 0) {
                $key = $temp[0];
            }
        }
        if (!is_numeric($key)) {
            $data += Dever::load($key, $data);
        } else {
            $data['name'] = '文件名';
            $data['file'] = Dever::db('upload/file')->getData($param);
            $data['cate'] = Dever::db('upload/cate')->state();
            $data['config'] = Dever::db('upload/upload')->one($key);

            if ($data['config'] && isset($data['config']['yun']) && $data['config']['yun']) {
                $data['yun'] = Dever::db('upload/yun')->one($data['config']['yun']);
            }
        }
        
        $data['total'] = Dever::total();
        
        if ($data['file']) {
            $pic = Dever::config('host')->script . 'img/video.jpg';
            foreach ($data['file'] as $k => $v) {
                if (!strstr($v['file'], 'http')) {
                    if (isset($data['config']) && $data['config']['save_type'] >= 3 && isset($data['yun'])) {
                        $data['file'][$k]['url'] = $data['yun']['host'] . $v['file'];
                    } else {
                        $data['file'][$k]['url'] = Dever::upload('{uploadRes}' . $v['file']);
                    }
                    
                } else {
                    $data['file'][$k]['url'] = $v['file'];
                }
                
                if (isset($v['pic']) && $v['pic']) {
                    $data['file'][$k]['pic'] = $v['pic'];
                } elseif (!isset($v['ext'])) {
                    $data['file'][$k]['pic'] = $pic;
                } else {
                    if ($v['ext'] != '.jpg' && $v['ext'] != '.png' && $v['ext'] != '.bmp' && $v['ext'] != '.gif') {
                        $data['file'][$k]['pic'] = $pic;
                    } else {
                        $data['file'][$k]['pic'] = $data['file'][$k]['url'];
                    }
                }
                
                if (!isset($data['file'][$k]['pic'])) {
                    $data['file'][$k]['pic'] = $pic;
                }
            }
        }

        $data = Dever::render('show', $data);
        Dever::out($data);
    }

    public function kindeditorFile()
    {
        $key = Dever::input('key');
        $param['upload'] = $key;
        $file = Dever::db('upload/file')->state();
        $config = Dever::db('upload/upload')->one($key);
        $list = array();
        if ($file) {

            $i = 0;
            foreach ($file as $k => $v) {
                if ($v['name'] && $v['file']) {
                    $list[$i] = array();
                    $list[$i]['is_dir'] = false;
                    $list[$i]['has_file'] = false;
                    $list[$i]['filesize'] = $v['size'];
                    $list[$i]['dir_path'] = '';
                    $list[$i]['is_photo'] = true;
                    $list[$i]['filetype'] = str_replace('.', '', $v['ext']);
                    $list[$i]['filename'] = $v['source_name'];
                    $list[$i]['path'] = '';
                    $list[$i]['file'] = Dever::upload('{uploadRes}' . $v['file']);
                    $list[$i]['datetime'] = date('Y-m-d H:i:s', filemtime(Dever::local($list[$i]['file'])));
                    $i++;
                }
            }
        }

        $result = array();
        //相对于根目录的上一级目录
        $result['moveup_dir_path'] = $config['id'];
        //相对于根目录的当前目录
        $result['current_dir_path'] = '';
        //当前目录的URL
        $result['current_url'] = '';
        //文件数
        $result['total_count'] = count($list);
        //文件列表数组
        $result['file_list'] = $list;

        Dever::outDiy($result);
    }

    # webp
    public function webp($file)
    {
        $host = Dever::config('host')->uploadRes;
        $root = Dever::data() . 'upload/';
        $source = str_replace(array('{uploadRes}', $host), $root, $file);
        $dest = $source . '.webp';
        if (isset($_SERVER['HTTP_ACCEPT']) && strpos($_SERVER['HTTP_ACCEPT'], 'image/webp')) {
            if (!is_file($dest)) {
                Dever::run('cwebp '.$source.' -o ' . $dest . '');
                header('Content-type: image/webp');
                readfile($source);
            } else {
                header('Content-type: image/webp');
                readfile($dest);
            }
        } else {
            header('Content-type: image/webp');
            readfile($source);
        }
    }

	# 根据配置生成缩略图 暂时支持缩略图
	public function get()
	{
        $file = Dever::input('file');
        $array = $this->getFile($file);
        $source = $array[0];
        $type = $array[1];
        $id = $array[2];

        if ($id > 0) {
            $host = Dever::config('host')->uploadRes;
            $root = Dever::data() . 'upload/';
            $dest = str_replace(array('{uploadRes}', $host), $root, $file);
            $path = str_replace(array('{uploadRes}', $host), '', $file);
            if (strstr($source, $host)) {
                
                $source = $root . str_replace($host, '', $source);

                if (!is_file($source)) {
                    $source = $array[0];
                }
            }

            if ($type == 'wp') {
                $temp = explode('.', $dest);
                $dest = $temp[0] . '.webp';
                $file = str_replace($root, $host, $dest);
            }

            if (!strstr($dest, 'http://') && !is_file($dest)) {
                $temp = explode('/', $path);
                $key = $temp[0];
                $image['file']  = false;
                $image['key']   = $key;
                $handle = new Handle($image);
                $method = 'handle_' . $type;
                $file = $handle->$method($id, $source, $dest, $path);
            }
        }

		return $file;
	}

	public function source($file)
	{
		# 搜索文件信息
        $array = $this->getFile($file);
		return $array[0];
	}

    private function getFile($file)
    {
        $type = $id = false;

        if (strstr($file, '_wp')) {
            $array = explode('_wp', $file);
            $type = 'wp';
        } elseif (strstr($file, '_p')) {
            $array = explode('_p', $file);
            $type = 'p';
        } elseif (strstr($file, '_c')) {
            $array = explode('_c', $file);
            $type = 'c';
        } elseif (strstr($file, '_t')) {
            $array = explode('_t', $file);
            $type = 't';
        }

        if (isset($array)) {
            $temp = explode('.', $array[1]);
            $id = $temp[0];
            $file = $array[0] . '.' . $temp[1];
        }

        return array($file, $type, $id);
    }

	/**
     * create 生成图片
     * @param array $config
     * @param string $filename
     *
     * @return mixed
     */
	public function create($config = array(), $filename = '', $type = 'gd', $update = 2)
	{
		$this->img = isset($this->img) ? $this->img : new Img();

        /*
        $config = array
        (
            'background' => '/www/grow/data/upload/1/2018/07/19/a49fe8914df0eada4d4b7d530d7fa5ba.jpg',
            'param' => array
            (
                0 => array
                (
                    'method' => 'mark',
                    'water' => '/www/grow/data/upload/1/2018/07/19/46d5b0c5c25c800cf197ea4f64f503f2.jpg',
                    //left,top
                    'position' => array(100,200),
                    'width' => 100,
                    'height' => 100,
                ),
                1 => array
                (
                    'method' => 'txt',
                    'name' => 'test文字',
                    'color' => '#FF0000',
                    'position' => array(100,200),
                    'size' => 50,
                    'angle' => 0,
                    'font' => '/www/grow/config/fonts/simsun.ttc',
                ),
            ),
        );
        */

        if (!$filename) {
            $filename = Dever::id();
        }
        $file =  Dever::pathDay('upload/poster', false) . md5($filename) . '.jpg';

        if (!is_file($file) || $update == 1) {
            $this->img->setType($type);
            $result = $this->img->init($config['background'], $config['param'], true, $file);
            if ($result) {
                $file = array_pop($result);
            }
        } else {

        }
        $host = str_replace(DEVER_APP_NAME . '/', '', Dever::config('host')->base);
        return $host . str_replace(DEVER_PROJECT_PATH, '', $file);
        $file = Dever::pic($file);
        return $file;
	}

	public function creates($config = array(), $filename = '')
	{
		if(empty($filename)) header("content-type: image/png");
        $imageDefault = array(
            'left'=>0,
            'top'=>0,
            'right'=>0,
            'bottom'=>0,
            'width'=>100,
            'height'=>100,
            'opacity'=>100
        );
        $textDefault = array(
            'text'=>'',
            'left'=>0,
            'top'=>0,
            'fontSize'=>32,       //字号
            'fontColor'=>'255,255,255', //字体颜色
            'angle'=>0,
        );
        $background = $config['background'];//海报最底层得背景
        //背景方法
        $backgroundInfo = getimagesize($background);
        $backgroundFun = 'imagecreatefrom'.image_type_to_extension($backgroundInfo[2], false);
        $background = $backgroundFun($background);
        $backgroundWidth = imagesx($background);  //背景宽度
        $backgroundHeight = imagesy($background);  //背景高度
        $imageRes = imageCreatetruecolor($backgroundWidth,$backgroundHeight);
        $color = imagecolorallocate($imageRes, 0, 0, 0);
        imagefill($imageRes, 0, 0, $color);
        // imageColorTransparent($imageRes, $color);  //颜色透明
        imagecopyresampled($imageRes,$background,0,0,0,0,imagesx($background),imagesy($background),imagesx($background),imagesy($background));
        //处理了图片
        if (!empty($config['image'])) {
            foreach ($config['image'] as $key => $val) {
                $val = array_merge($imageDefault,$val);
                $info = getimagesize($val['url']);
                $function = 'imagecreatefrom'.image_type_to_extension($info[2], false);
                if ($val['stream']) {   //如果传的是字符串图像流
                    $info = getimagesizefromstring($val['url']);
                    $function = 'imagecreatefromstring';
                }
                if (isset($val['radius']) && $val['radius']) {
                	$res = $this->radius($val['url'], $val['radius']);
                } else {
                	$res = $function($val['url']);
                }
                
                $resWidth = $info[0];
                $resHeight = $info[1];
                //建立画板 ，缩放图片至指定尺寸
                $canvas = imagecreatetruecolor($val['width'], $val['height']);
                $color   = imagecolorallocate($background, 202, 201, 201); // 为真彩色画布创建白色背景，再设置为透明    
			    imagefill($canvas, 0, 0, $color);
			    imageColorTransparent($canvas, $color);
                //关键函数，参数（目标资源，源，目标资源的开始坐标x,y, 源资源的开始坐标x,y,目标资源的宽高w,h,源资源的宽高w,h）
                imagecopyresampled($canvas, $res, 0, 0, 0, 0, $val['width'], $val['height'],$resWidth,$resHeight);
                $val['left'] = $val['left']<0?$backgroundWidth- abs($val['left']) - $val['width']:$val['left'];
                $val['top'] = $val['top']<0?$backgroundHeight- abs($val['top']) - $val['height']:$val['top'];
                //放置图像
                imagecopymerge($imageRes,$canvas, $val['left'],$val['top'],$val['right'],$val['bottom'],$val['width'],$val['height'],$val['opacity']);//左，上，右，下，宽度，高度，透明度
            }
        }
        # 处理文字
        if (!empty($config['text'])) {
            foreach ($config['text'] as $key => $val) {
                $val = array_merge($textDefault,$val);
                list($R,$G,$B) = explode(',', $val['fontColor']);
                $fontColor = imagecolorallocate($imageRes, $R, $G, $B);
                $val['left'] = $val['left']<0?$backgroundWidth- abs($val['left']):$val['left'];
                $val['top'] = $val['top']<0?$backgroundHeight- abs($val['top']):$val['top'];
                imagettftext($imageRes,$val['fontSize'],$val['angle'],$val['left'],$val['top'],$fontColor,$val['fontPath'],$val['text']);
            }
        }
        # 生成图片
        if (!empty($filename)) {
            $res = imagepng ($imageRes,$filename,9);
            imagedestroy($imageRes);
            if(!$res) return false;
            return $filename;
        } else {
            imagepng ($imageRes, null, 9);
            imagedestroy($imageRes);
        }
	}
}
