<?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;
use common\assets\TagitsAsset;

/**
 * 标签插件,使用Tagit 
 * 
 * http://webspirited.com/tagit/
 * 
 * 调用方法如下：
 * <?= Tagit::widget([
 * 'model' => $model, 
 * 'form' => $form, 
 * 'tag_names'=>$model->tag_names
 * 'attribute' => 'tag_names', 
 * 'inputConfig' => ['class' => 'form-control','id'=>'tags']//
 * 'width'=>'240'//数字
 * 
 * ]) ?>
 * 
 * @author xiaobai http://blog.u-bo.com
 * @since 0.1
 */
class Tagit extends \yii\base\Widget
{
    /**
     * @var array 标签的配置
     */
    public $tagConfig = [];

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

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

    /**
     * 循环li标签
     */
    public $tags_li;

    /**
     * 循环标签字段名
     * @var type
     */
    public $tag_value;

    /**
     * 标签表单的宽度
     * @var type
     */
    public $width;

    /**
     * ul返回值
     * @var type
     */
    public $str_ul;

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

    public function init()
    {
        parent::init();
        if ($this->attribute === null) {
            throw new InvalidConfigException('插件参数缺失');
        }
    }

    public function run()
    {
        $this->registerAsset();
        $this->inputConfig[] = "Tagit(" . $this->getOptions() . ")";
        $tag_value = explode(',', $this->tag_value);
        if (!empty($tag_value)) {
            foreach ($tag_value as $vo) {
                $this->tags_li.="<li class=''>{$vo}</li>";
            }
        }
        $str = "<ul placeholder='可输入6个标签，有提示，回车或空格确认' id='inputtags' style='width: " . $this->width . "px;'>{$this->tags_li}</ul>";
        $this->str_ul = Html::hiddenInput($this->attribute, $this->tag_value,['id'=>'tags']);
        return $str . $this->str_ul;
    }

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

    public function getOptions()
    {
        $options = json_encode($this->tagConfig);
        return $options;
    }
}