<?php
/**
 * @link      http://www.u-bo.com
 * @copyright 南京友博网络科技有限公司 
 * @license   http://www.u-bo.com/license/
 */

namespace common\widgets;

use Yii;
use yii\helpers\Html;
use yii\base\InvalidConfigException;
use home\assets\MainAsset;
use common\assets\ArtDialogAsset;
use yii\helpers\Url;
use home\models\Attachment;
use common\components\Image;

/**
 * 上传附件插件
 * 
 * 调用方法如下：
 * <?= 
 * Uploader::widget([
 * 'model' => $model,
 * 'form' => $form,
 * 'attribute' => 'attach_ids',
 * 'type' => 'files']) 
 * ?>
 * 
 * @author legendjw http://blog.u-bo.com
 * @since 0.1
 */
class Uploader extends \yii\base\Widget 
{
    /**
     * @var array 支持的上传类型 分别为单图片，单文件，多图片，多文件 
     */
    private $_supportUploader = [
        'image' => ['uploadNum' => 1],
        'file' => ['uploadNum' => 1],
        'images' => ['uploadNum' => 10],
        'files' => ['uploadNum' => 10],
    ];

    /**
     * @var array 附件上传首页路由，无需修改
     */
    public $attachIndexRoute = ['/attachment/index'];

    /**
     * 上传类型 默认为单图片
     * @var string ('image','file','images','files')
     */
    public $type='image';

    /**
     * @var array 允许上传的文件后缀
     */
    public $allowExt;

    /**
     * @var int 允许上传的数量
     */
    public $uploadNum;

	/**
	 * @var array 日期选择器的配置
	 */
	public $dateConfig = [];

    /**
	 * @var string 模型属性
	 */
	public $attribute;

	/**
	 * @var object 表单插件对象
	 * 用于调取生成input元素
	 */
	public $form;

	/**
	 * @var array 字段配置
	 */
	public $fieldConfig = [];

	/**
	 * @var array input配置 
	 */
	public $inputConfig = [];

	/**
	 * @var object 当前操作表单的模型
	 * 用于获取当前模型的值和一些验证规则
	 */
	public $model;

	public function init() 
	{
		parent::init();
		if ($this->model === null || $this->form === null || $this->attribute === null) {
            throw new InvalidConfigException('插件参数缺失');
		}
		if (!isset($this->_supportUploader[$this->type])) {
            throw new InvalidConfigException('当前上传类型不支持');
		}
		$uploader = $this->_supportUploader[$this->type];
		$this->attachIndexRoute = (is_string($this->attachIndexRoute)) ? $this->attachIndexRoute : Url::to($this->attachIndexRoute);
		$this->uploadNum = (empty($this->uploadNum)) ? $uploader['uploadNum'] : $this->uploadNum ;

	}

	public function run() 
	{
		$this->registerAsset();


		//return $this->form->field($this->model, $this->attribute, $this->fieldConfig)->textInput($this->inputConfig);

        $method = $this->type . 'Render';

        return call_user_func(array($this,$method));
	}

	/**
	 * 注册js资源
	 */
	private function registerAsset()
	{
		$view = $this->getView();
		//注册资源
		ArtDialogAsset::register($view);
        $assetUrl = $view->getAssetManager()->getBundle(MainAsset::className())->baseUrl;
        $view->registerJsFile($assetUrl.'/js/attach.upload.js', ['depends' => [ ArtDialogAsset::className()]]);
	}

	/**
	 * 渲染单张图片
	 */
    private function imageRender()
    {
        $id = Html::getInputId($this->model, $this->attribute);
        $hiddenInput = Html::activeHiddenInput($this->model, $this->attribute, []);
        $web = Yii::getAlias('@web');
		$route = $this->getRoute();
        $imgSrc = (!empty($this->model->{$this->attribute})) ? $this->model->{$this->attribute} : $web . '/static/images/upload-pic.png';

        $tpl = <<<TPL
                {$hiddenInput}
                <a href='javascript:;' onclick="swfUpload({attachIndexUrl:'{$this->attachIndexRoute}', route:'{$route}', title:'图片', type:'image', fieldId:'{$id}', uploadNum:1, allowExt:'{$this->allowExt}'}); return false;"> <img src='{$imgSrc}' id='{$id}_preview' width='100px' height='80px' style='cursor:hand;' /></a>

TPL;
        return $tpl;

    }

	/**
	 * 渲染单文件 
	 */
	private function fileRender()
	{
		return $this->imageRender();
	}

	 /**
     * 渲染多图片
     */
    public function imagesRender()
	{
		$id = Html::getInputId($this->model, $this->attribute);
        $hiddenInput = Html::activeHiddenInput($this->model, $this->attribute, []);
        $web = Yii::getAlias('@web');
		$route = $this->getRoute();

        //编辑时显示多图
		$imagesStr = '';
		if (!empty($this->model->{$this->attribute})) {
			$value = $this->model->{$this->attribute};
			$images = Attachment::getAttachByDot($value);
            if (!empty($images)) {
				$randId = mt_rand(1000, 9999);
                foreach ($images as $k => $img) {
                    $imagesStr .= "<li id='image{$randId}'> <input type='text' name='{$this->attribute}' value= '{$img['file_name']}' style='width:300px;' disabled='disabled' class='input' data-id='{$img['attach_id']}' data-path='{$img['file_path']}' />&nbsp;&nbsp;<a href=\"javascript:imagePriview('{$img['file_path']}')\" >预览</a>&nbsp;&nbsp;<a href=\"javascript:removeDiv('image{$randId}','{$id}')\" >移除</a> </li>";
                }
            }
        }

        $htmlStr = <<<STR
				{$hiddenInput}
                <fieldset class="upload-fieldset" >
                    <div id="{$id}_show">{$imagesStr}</div>
                </fieldset>
                <a class="btn btn-xs" onclick="swfUpload({attachIndexUrl:'{$this->attachIndexRoute}', route:'{$route}', title:'图片', type:'images', name:'{$this->attribute}', fieldId:'{$id}', uploadNum:{$this->uploadNum}, allowExt:'{$this->allowExt}'}); return false;" herf="javascript:;"><span class="add"></span>选择图片 </a>
STR;
        return $htmlStr;
    }

    /**
     * 渲染多文件
     */
    public function filesRender()
	{

        $id = Html::getInputId($this->model, $this->attribute);
        $hiddenInput = Html::activeHiddenInput($this->model, $this->attribute, []);
        $web = Yii::getAlias('@web');
		$route = $this->getRoute();
		$downUrl = Url::to(['/attachment/download']);

        //编辑时显示文件
		$filesStr = '';
		if (!empty($this->model->{$this->attribute})) {
			$value = $this->model->{$this->attribute};
			$files = Attachment::getAttachByDot($value);
            if (!empty($files)) {
				$randId = mt_rand(1000, 9999);
                foreach ($files as $k => $file) {
					$fileDownUrl = $downUrl . ((false === strpos($downUrl, '?')) ? '?' : '&') . 'id='. $file['attach_id'] ;
                    $filesStr .=  "<li id='file{$randId}'> " . (($file['is_image'] == 1) ? '<a href="javascript:imagePriview( \'' . $file['file_path'] . '\' )" title="点击预览"><img src="' . Image::thumb3($file['file_path'], 40, 40) . '" width="40" height="40" /></a>' : '<img src="/static/images/ext/' . $file['file_ext'] .'.png" width="40" height="40" />' ). " <input type='text' name='{$this->attribute}' value= '{$file['file_name']}' style='width:300px;' disabled='disabled' class='input' data-id='{$file['attach_id']}' data-path='{$file['file_path']}' />&nbsp;&nbsp;<a href=\"{$fileDownUrl}\" >下载</a>&nbsp;&nbsp;<a href=\"javascript:removeDiv('file{$randId}','{$id}')\" >移除</a> </li>";
                }
            }
        }

        $htmlStr = <<<STR
				{$hiddenInput}
                <fieldset class="upload-fieldset" >
                    <div id="{$id}_show">{$filesStr}</div>
                </fieldset>
                <a class="btn btn-xs" onclick="swfUpload({attachIndexUrl:'{$this->attachIndexRoute}', downUrl:'{$downUrl}', route:'{$route}', title:'文件', type:'files', name:'{$this->attribute}', fieldId:'{$id}', uploadNum:{$this->uploadNum}, allowExt:'{$this->allowExt}'}); return false;" herf="javascript:;"><span class="add"></span>选择文件 </a>
STR;
        return $htmlStr;
    }

	/**
	 * 获取当前操作的路由信息
	 * 
	 * @return string
	 */
	private function getRoute()
	{
		$view = $this->getView();
		$controller = $view->context;
		$route = $controller->module->id . '/' . $controller->id . '/' .$controller->action->id;

		return $route;
	}


}
