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

namespace home\widgets\portlet;

use yii\helpers\Html;
use yii\base\InvalidConfigException;
use common\assets\PortletAsset;
use home\assets\MainAsset;

/**
 * Portlet基类
 * 
 * @author legendjw http://blog.u-bo.com
 * @since 0.1
 */
class BasePortlet extends \yii\base\Widget 
{
    /**
     * @param  
     * @var string 组件容器的ID
     */
    public $containerId = 'portlet';

    /**
     * @var string 组件的ID
     */
    public $portletId;

	/**
	 * @var string 组件名称
	 */
	public $title;

    /**
     * @var integer 横坐标
     */
    public $x = 0;

    /**
     * @var integer 纵坐标
     */
    public $y = 0;

	public function init() 
	{
		parent::init();
		
		$this->registerAsset();
	}

    public function run() 
    {
        $view = $this->getView();
        $content = $this->getContent();
        $js = $this->getRegisterJs($this->title, $content);

        $view->registerJs($js);
    }

	/**
	 * 注册资源
	 */
	private function registerAsset()
	{
		$view = $this->getView();
		PortletAsset::register($view);

        $mainAssetUrl = $view->getAssetManager()->getBundle(MainAsset::className())->baseUrl;
        $view->registerJsFile($mainAssetUrl . '/js/portlet.js', ['depends' => [PortletAsset::className()]]);
	}

    /**
     * 获取组件的内容，应该由子类继承实现
     */
    public function getContent()
    {
        return '';
    }

    /**
     * 获取建立组件的js
     *
     * @param string $title 组件标题
     * @param string $content 组件内容
     */
    public function getRegisterJs($title, $content)
    {
        //替换掉换行
        $content = str_replace(array("\r\n", "\r", "\n"), ' ', $content);

        $js = <<<JS
            $('#{$this->containerId}').portlet('option', 'add', {
                    position: {
                        x:{$this->x},
                        y:{$this->y}
                    },
                    portlet: {
                        attrs: {
                            'id': '{$this->portletId}',
                            'class': 'ui-portlet-item ui-widget ui-widget-content ui-helper-clearfix ui-corner-all module'
                        },
                        title: '<h3>{$title}</h3>',
                        beforeRemove: function() {
                            if (confirm('确定要删除此组件？')) {
                                removePortlet(this.attrs.id);
                                return true;
                            }
                            else {
                                return false;
                            }
                        },
                        content: {
                            type: 'text',
                            text: '{$content}'
                        }
                    }
            });
JS;
        return $js;
    }

}
