<?php
/**
 * 人人站CMS
 * ============================================================================
 * 版权所有 2015-2030 山东康程信息科技有限公司，并保留所有权利。
 * 网站地址: http://www.rrzcms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 */

namespace think\template\taglib;

use think\template\TagLib;


class Html extends Taglib
{
    // 标签定义
    protected $tags = [
        // 标签定义： attr 属性列表 close 是否闭合（0 或者1 默认1） alias 标签别名 level 嵌套层次
        'editor' => ['attr' => 'id,name,style,width,height,type', 'close' => 1],
        'imgspace' => ['attr' => 'id,width,height,class,src,value', 'close' => 0],
        'select' => ['attr' => 'id,name,value,class,placeholder', 'close' => 1],
    ];

    static $_ui_id = 0;

    /**
     * 生成domid
     * @return string
     */
    private function newDomId() {
        return 'dom_el_' . substr(md5(microtime()), 0, 6) . intval(self::$_ui_id++);
    }

    /**
     * editor标签解析 插入可视化编辑器
     * 格式： <html:editor id="editor" name="remark" type="FCKeditor" style="" >{$vo.remark}</html:editor>
     * @param array $tag 标签属性
     * @param string $content 标签内容
     * @return string
     */
    public function tagEditor(array $tag, string $content) {
        $id = !empty($tag['id']) ? $this->varOrvalue($tag['id']) : $this->newDomId();
        $name = $this->varOrvalue($tag['name']);
        $style = !empty($tag['style']) ? $tag['style'] : '';
        $width = !empty($tag['width']) ? $tag['width'] : '100%';
        $height = !empty($tag['height']) ? $tag['height'] : '320';
        $config = [];
        $height and $config['initialFrameHeight'] = $height;
        $width and $config['initialFrameWidth'] = $width;
        $config and $config = htmlentities(json_encode($config));
        //   $content    =   $tag['content'];
        $type = $tag['type'];
        switch (strtoupper($type)) {
            case 'UEDITOR':
                $parseStr = '<textarea id="' . $id . '" name="' . $name . '" data-config="' . ($config ?: '') . '" style="' . $style . '">' . $content . '</textarea><div class="pt5 pb15"><button type="button" data-id="' . $id . '" data-type="imgrtol" class="layui-btn layui-btn-sm ueditor_footbtn">远程图片本地化</button><button type="button" data-id="' . $id . '" data-type="clearlink" class="layui-btn layui-btn-sm ueditor_footbtn">清除非本站链接</button></div><script type="text/javascript">(function(){ $.getEditor("' . $id . '"); })();</script>';
                break;
            default :
                $parseStr = '<textarea id="' . $id . '" style="' . $style . '" name="' . $name . '" >' . $content . '</textarea>';
        }

        return $parseStr;
    }

    /**
     * imgspace 标签解析 插入图片空间 控件
     * 格式<html:imgspace name="" src="" value="" />
     * @param array $tag
     * @param string $content
     * @return string
     */
    public function tagImgspace(array $tag, string $content) {
        $t = $tag;
        $attr = $this->attrFromTag($tag);
        $vars = $this->getInputAttr('title,class,name,value,src,width,height,style,clear,type', $tag, $attr);

        $width = $vars['width'] ? 'width:' . $vars['width'] . ';' : '';
        $height = $vars['height'] ? 'height:' . $vars['height'] . ';' : '';
        $type = $vars['type'] ?: 'input';
        $clear = $vars['clear'] ?: 0;
        $vars['src'] or $vars['src'] = $vars['value'];

        $parseStr = '<div ' . ($type ? 'lay-type-' . $type : '') . ($type == 'img' ? ' lay-up' : '') . ' class="imgspace ' . $vars['class'] . '" style="' . $width . $height . $vars['style'] . '" ' . implode(' ', array_values($attr)) . '>';
        if ($type == 'img') {
            $clear and $parseStr .= '<span class="close-modal">×</span>';
            $parseStr .= '<img src="' . $vars['src'] . '" lay-upsrc/>';
            $parseStr .= '<input type="hidden" name="' . $vars['name'] . '" value="' . $vars['value'] . '" lay-upvalue/>';
        } else {
            $t['src'] = $t['src'] ?? $t['value'];
            $src = $this->varOrvalue($t['src'], 'javascript:;');

            $parseStr .= '<a class="layui-icon layui-icon-picture tips-img" href="' . $src . '" target="_blank" src="' . $vars['src'] . '" lay-uphref lay-upsrc></a>';
            $parseStr .= '<input type="text" name="' . $vars['name'] . '" value="' . $vars['value'] . '" placeholder="' . $vars['title'] . '" autocomplete="off" class="layui-input" lay-upvalue/>';
            $parseStr .= '<button class="layui-btn layui-btn-normal" type="button" lay-up><i class="layui-icon">&#xe67c;</i>上传图片</button>';
        }
        $parseStr .= '</div>';
        unset($t, $tag, $attr, $vars);
        return $parseStr;
    }

    public function tagSelect(array $tag, string $content) {
        $attr = $this->attrFromTag($tag);
        $vars = $this->getInputAttr('name,class,value,placeholder', $tag, $attr);

        $parseStr = '<div class="layui-unselect layui-form-select layui-dropdown-select ' . $vars['class'] . '">' . "\r\n";
        $parseStr .= '    <div class="layui-select-title">' . "\r\n";
        $parseStr .= '       <input type="text" placeholder="' . $vars['placeholder'] . '" readonly="" class="layui-input layui-unselect" /><i class="layui-edge"></i>' . "\r\n";
        $parseStr .= '      <input type="hidden" name="' . $vars['name'] . '" value="' . $vars['value'] . '" />' . "\r\n";
        $parseStr .= '       <textarea class="hide">' . trim($content) . '</textarea>' . "\r\n";
        $parseStr .= '    </div>' . "\r\n";
        $parseStr .= '</div>' . "\r\n";
        return $parseStr;
    }

    /**
     * 自动识别构建变量，传值可以使变量也可以是值
     * @access private
     * @param string $value 值或变量
     * @return string
     */
    private function varOrvalue($value, $def = '') {
        $flag = substr($value, 0, 1);
        if ('$' == $flag || ':' == $flag) {
            if ($def) {
                $value = '<?php echo( (' . $this->autoBuildVar($value) . ')?:"' . $def . '" ); ?>';
            } else {
                $value = '<?php echo ' . $this->autoBuildVar($value) . ' ?>';
            }
        }
        return $value;
    }

    /**
     * 格式化标签属性
     * @param $tag
     * @return array
     */
    private function attrFromTag(&$tag) {
        $attr = array();
        foreach ($tag as $key => $val) {
            $val = $this->varOrvalue(trim($val));
            $attr[$key] = $key . '="' . $val . '"';
            if (is_numeric($val)) {
                $val = $val + 0;
            }
            if (strtolower($val) === 'true') {
                $val = true;
            }
            if (strtolower($val) === 'false') {
                $val = false;
            }
            $tag[$key] = $val;
        }
        return $attr;
    }

    /**
     * 获取标签属性，不存在的属性赋值空
     * @param $keys 要获取的属性集合
     * @param $tag 标签
     * @param $attr 属性
     * @param bool $isR 是否删除取过的属性
     * @return array 返回属性数组
     */
    private function getInputAttr($keys, $tag, &$attr, $isR = true) {
        is_string($keys) and $keys = explode(',', $keys);
        $arry = array();
        foreach ((array)$keys as $key) {
            if (!$key) continue;
            $arry[$key] = isset($tag[$key]) ? $tag[$key] : '';
            if ($isR && isset($attr[$key])) unset($attr[$key]);
        }
        return $arry;
    }

}