<?php

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

namespace common\widgets;

use yii\helpers\Html;
use yii\base\InvalidConfigException;

/**
 * 编辑器插件,用于调取编辑器
 * 
 * 调用方法如下：
 * <code>
 * <?= Editor::widget([
 * 'model' => $model, 
 * 'form' => $form, 
 * 'attribute' => 'description', 
 * 'editorConfig' => ['height' => '500px']
 * ]) ?>
 * </code>
 * 具体参数请查看下面类的属性
 * 
 * @author legendjw http://blog.u-bo.com
 * @since 0.1
 */
class Editor extends \yii\base\Widget
{

    /**
     * @var array 当前支持的编辑器信息
     * 
     * @key name string 编辑器名称
     * @key asset name 编辑器资源包
     * @key asset options 编辑器默认选项
     */
    private $_supportEditors = [
        'KindEditor' => ['name' => 'kindeditor', 'asset' => 'common\assets\KindEditorAsset', 'options' => [ 'afterBlur' => "function(){this.sync()}"]],
        'UEditor' => ['name' => 'ueditor', 'asset' => 'common\assets\UEditorAsset'],
    ];

    /**
     * @var string 调取的编辑器类型，要确保在$this->_supportEditors里存在
     */
    public $editor = 'UEditor';

    /**
     * @var string 编辑器类型，支持 simple => 简版 , normal => 正常版
     */
    public $editorType = 'normal';

    /**
     * @var int 宽度 
     */
    public $width;

    /**
     * @var int 高度 
     */
    public $height = 300;

    /**
     * @var array 编辑器的配置
     */
    public $editorConfig = [];

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

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

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

    /**
     * @var array 输入框配置 
     */
    public $inputConfig = [];

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

    /**
     * 提示标签
     */
    public $hint;

    public function init()
    {
        parent::init();
        if($this->model === null || $this->form === null){
            throw new InvalidConfigException('插件参数缺失');
        }
        if(!array_key_exists($this->editor, $this->_supportEditors)){
            throw new InvalidConfigException('不支持' . $this->editor . '类型编辑器');
        }
        $this->editor = $this->_supportEditors[$this->editor];
        $this->editorInit();
    }

    public function run()
    {
        $id = Html::getInputId($this->model, $this->attribute);

        $this->registerAsset($id);
        if(!empty($this->hint)){
            $form=$this->form->field($this->model, $this->attribute, $this->fieldConfig)->textarea($this->inputConfig)->hint($this->hint);
        }else{
            $form=$this->form->field($this->model, $this->attribute, $this->fieldConfig)->textarea($this->inputConfig);
        }
        return $form;
    }

    /**
     * 编辑器初始化
     *
     * 主要是消除编辑器之间的差异
     */
    public function editorInit()
    {
        if($this->editor['name'] == 'kindeditor'){
            if(!isset($this->editorConfig['items']) && $this->editorType == 'simple'){
                $this->editor['options']['items'] = ['fontname', 'fontsize', 'plainpaste', 'wordpaste', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline', 'removeformat', '|', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist', 'insertunorderedlist', '|', 'image', 'link', 'unlink', 'fullscreen'];
            }
            if(!empty($this->width)){
                $this->editorConfig['width'] = $this->width;
            }
            if(!empty($this->height)){
                $this->editorConfig['height'] = $this->height;
            }
        } elseif($this->editor['name'] == 'ueditor'){
            if(!isset($this->editorConfig['toolbars']) && $this->editorType == 'simple'){
                $this->editor['options']['toolbars'][] = ['fullscreen', 'source', 'undo', 'redo', 'forecolor', 'backcolor', 'bold', 'italic', 'underline', 'strikethrough', 'indent', 'fontfamily', 'fontsize', 'insertorderedlist', 'insertunorderedlist', 'preview', 'removeformat', 'simpleupload', 'link', 'emotion'];
            }
            if(!empty($this->width)){
                $this->editorConfig['initialFrameWidth'] = $this->width;
            }
            if(!empty($this->height)){
                $this->editorConfig['initialFrameHeight'] = $this->height;
            }
        }
    }

    /**
     * 注册js资源
     * @param type $id
     */
    private function registerAsset($id)
    {
        $view = $this->getView();
        //注册资源
        if(isset($this->editor['asset'])){
            call_user_func([$this->editor['asset'], 'register'], $view);
        }
        $options = $this->getOptions();
        if($this->editor['name'] == 'kindeditor'){
            $js = <<<JS
                var options = {$options}; 
				KindEditor.ready(function(K) {
					var {$this->attribute}_editor = K.create('#{$id}', options);
				});
JS;
        } elseif($this->editor['name'] == 'ueditor'){
            $js = <<<JS
                var options = {$options}; 
                var {$this->attribute}_editor = UE.getEditor('{$id}', options);
JS;
        }
        $view->registerJs($js);
    }

    /**
     * 获取编辑器选项 
     */
    private function getOptions()
    {
        if(empty($this->editorConfig) && empty($this->editor['options'])){
            $options = '{}';
        } else {
            $options = (isset($this->editor['options'])) ? array_merge($this->editor['options'], $this->editorConfig) : $this->editorConfig;
            $options = json_encode($options);
            //去除函数两边的引号
            $options = preg_replace('/"(function().*?)"/', '$1', $options);
        }
        return $options;
    }

}
