<?php namespace Dever\Template;

use Dever;
use Dever\Http\Url;
use Dever\Loader\Config;

class Common
{
    static $version = 0;

    /**
     * 获取文件版本号
     *
     * @return int
     */
    private static function version()
    {
        if (!self::$version) {
            self::$version = time();
        }
        return self::$version;
    }

    /**
     * 读取dom
     * @param string $value
     * @param string $index
     *
     * @return array
     */
    public static function dom($value)
    {
        return \Sunra\PhpSimple\HtmlDomParser::str_get_html($value,
            $lowercase          = true, 
            $forceTagsClosed    = true, 
            $target_charset     = DEFAULT_TARGET_CHARSET, 
            $stripRN            = false, 
            $defaultBRText      = DEFAULT_BR_TEXT, 
            $defaultSpanText    = DEFAULT_SPAN_TEXT);
    }

    /**
     * 设置循环里每行不同的值
     * @param string $value
     * @param string $index
     *
     * @return array
     */
    public static function lace($value, $index, $key = 2, $num = 0)
    {
        $value = explode(',', $value);
        if (!isset($value[1])) {
            $value[1] = '';
        }

        if ($index > 0 && $index % $key == $num) {
            return $value[0];
        } else {
            return $value[1];
        }
    }

    /**
     * 设置循环里最新一条数据的值
     * @param string $value
     * @param string $index
     *
     * @return array
     */
    public static function first($value, $index)
    {
        if ($index == 0) {
            return $value;
        }
    }

    /**
     * 设置循环里最后一条数据的值
     * @param string $value
     * @param string $index
     * @param string $total
     *
     * @return array
     */
    public static function last($value, $index, $total)
    {
        if ($index == $total) {
            return $value;
        }
    }

    /**
     * 除了最后一条
     * @param string $value
     * @param string $index
     * @param string $total
     *
     * @return array
     */
    public static function other($value, $index, $total)
    {
        if ($index != $total) {
            return $value;
        }
    }

    /**
     * 对多维数组进行排序
     * @param string $array
     * @param string $field
     * @param string $desc
     *
     * @return array
     */
    public function sort($array, $field, $desc = false)
    {
        $fieldArr = array();
        foreach ($array as $k => $v) {
            $fieldArr[$k] = $v[$field];
        }
        $sort = $desc == false ? SORT_ASC : SORT_DESC;
        array_multisort($fieldArr, $sort, $array);
    }

    /**
     * 生成html a标记 以后统一修改
     * @param string $name
     * @param string $link
     * @param string $target
     *
     * @return array
     */
    public function a($name, $link, $target = '_self')
    {
        return '<a href="' . Url::get($link) . '" target="' . $target . '">' . $name . '</a>';
    }

    /**
     * 生成html img标记 以后统一修改
     * @param string $link
     * @param string $target
     *
     * @return array
     */
    public function img($link, $target = '_self')
    {
        return self::a('<img src="' . $link . '" />', $link, $target);
    }

    /**
     * 获取assets的文件网络路径
     * @param string $value
     * @param string $type
     *
     * @return array
     */
    public static function assets($value, $type = false)
    {
        if (!$type) {
            $type = pathinfo($value, PATHINFO_EXTENSION);
        }
        return Url::https(Config::get('host')->$type . $value . '?v=' . self::version());
    }

    /**
     * 生成table 用于后台展示
     * @param string $data
     * @param string $class
     *
     * @return array
     */
    public static function table($data, $class = '', $num = 1, $id = 'dever-img', $width = '97%', $align = 'left')
    {
        if ($class) {
            $style = 'class=' . $class . ' width="'.$width.'" text-align="'.$align.'"';
        } else {
            $style = 'class="dever-img" style="margin: 10px;border: 1px solid #E8E8E8;text-align:'.$align.'" border=1 width='.$width.' height=100%';
        }

        if (!Config::get('base')->table_id_num) {
            Config::get('base')->table_id_num = 1;
        } else {
            Config::get('base')->table_id_num++;
        }

        $id = $id . '_' . Config::get('base')->table_id_num;

        $html = '<table ' . $style . '  id="'.$id.'">';

        foreach ($data as $k => $v) {
            if (is_array($v) && $num == 2) {
                $tbody = array($k);
                foreach ($v as $j) {
                    array_push($tbody, $j);
                }
                $html .= self::tbody($tbody);
            } else {
                if (is_array($v)) {
                    $v = self::table($v, $class);
                    //$v = var_export($v, true);
                }
                if (is_numeric($k)) {
                    $html .= self::tbody(array($v));
                } else {
                    $html .= self::tbody(array($k, $v));
                }
            }
        }

        $html .= '</table>';

        return $html;
    }

    /**
     * 生成tbody
     * @param string $data
     * @param string $class
     *
     * @return array
     */
    public static function tbody($data)
    {
        $html = '<tr>';
        foreach ($data as $k => $v) {
            if ($k == 0) {
                $html .= '<td style="padding-left:10px;line-height:1.75;font-weight:bold">' . $v . '</td>';
            } elseif ($k == 1) {
                $html .= '<td style="padding-left: 10px;word-break:break-all;word-wrap:break-word;">' . $v . '</td>';
            } else {
                $html .= '<td style="word-break:break-all;word-wrap:break-word;">' . $v . '</td>';
            }
        }

        $html .= '</tr>';

        return $html;
    }

    /**
     * dever tag parsing
     * @param string $content
     *
     * @return string
     */
    public static function tag($content)
    {
        $parsing = array();
        if (strpos($content, '<dever') !== false && strpos($content, '</dever>') !== false) {
            preg_match_all('/<dever(.*?)>([\s\S]*?)<\/dever>/i', $content, $matches);
            if (isset($matches[2][0]) && $matches[2][0]) {
                $parsing = self::parsing($matches[2][0]);
            }
        }

        return $parsing;
    }

    /**
     * dever parsing
     * @param string $content
     *
     * @return string
     */
    public static function parsing($content, $api = false)
    {
        $parsing = array();
        #提取每行开头为$的字符串
        preg_match_all('/(?:^|\n)\$\("(.*?)"\).(.*?)\("(.*?)"([\s\S]*?)\);/i', $content, $matches);
        if (isset($matches[2][0]) && $matches[2][0]) {
            foreach ($matches[2] as $k => $v) {
                $parsing[$k]['method'] = $v;
                $parsing[$k]['param'][0] = $matches[1][$k];
                $parsing[$k]['param'][1] = $matches[3][$k];
                if (isset($matches[4][$k]) && $matches[4][$k]) {
                    $matches[4][$k] = ltrim($matches[4][$k], ',');
                    $parsing[$k]['param'][2] = json_decode($matches[4][$k], true);
                }
                if ($api) {
                    self::parsingApi($parsing[$k]['param'][1], isset($matches[4][$k]) ? $matches[4][$k] : false);
                }
            }
        }
        return $parsing;
    }

    /**
     * parsingApi
     * @param string $content
     * @param string $url
     *
     * @return string
     */
    private static function parsingApi($url, $content)
    {
        $api = array();
        if (strpos($url, '/') && (strpos($url, '.') || strpos($url, '-') || strpos($url, '!'))) {
            $api[$url] = array();
            if ($content) {
                preg_match_all('/(\|)\$v\.(.*?)"([\s\S]*?)[\}]/i', $content, $parent);
                preg_match_all('/\$v\.(.*?)["|.]/i', $content, $current);
                foreach ($current[1] as $k => $v) {
                    $api[$url][$v] = $k;
                }
                foreach ($parent[3] as $k => $v) {
                    preg_match_all('/\$v([0-9]+)\.(.*?)["|.]/i', $v, $child);
                    $api[$url][$parent[2][$k]] = array_flip($child[2]);
                }
            }

            if (!Config::get('base')->ai) {
                Config::get('base')->ai = array();
            }

            Config::get('base')->ai = array_merge(Config::get('base')->ai, $api);
        }
    }

    /**
     * fetch
     * @param string $content
     * @param array $fetch
     *
     * @return string
     */
    public static function fetch($content, $parsing)
    {
        $dom = new Dom($content, new Parsing());
        foreach ($parsing as $k => $v) {
            $k = $v['method'];
            $dom->$k($v['param']);
        }
        return $dom->get();
    }

    /**
     * show
     * @param string $name
     * @param array $head
     * @param array $body
     *
     * @return string
     */
    public static function show($head, $body, $foot = false, $css = true, $class = '')
    {
        $html = '';
        if (!$css) {
            $html .= '<link rel="stylesheet" type="text/css" href="'.self::assets('lib/layui/css/layui.css', 'script').'" />
<link rel="stylesheet" href="'.self::assets('lib/layui/admin/style/admin.css?v9', 'script').'" media="all"><style>.layui-input,.xm-select-parent
    {
      width: 50%;
    }
    @media screen and (max-width: 1024px) {
        .layui-input,.xm-select-parent
        {
          width: 90%;
        }
    }</style>';
        }
        if (is_array($head)) {
            $html .= self::show_head($head, 1, true);
        } else {
            $html .= $head;
        }
        if (is_array($body)) {
            $html .= '<div class="layui-card-body order-box '.$class.'">';
            
            $i = 0;
            if (isset($body['tab'])) {
                $tab = $body['tab'];
                unset($body['tab']);
            }
            foreach ($body as $k => $v) {
                $method = 'show_' . $v['type'];
                $html .= self::$method($k, $v['content'], isset($v['total']) ? $v['total'] : false, isset($v['head']) ? $v['head'] : false, isset($v['pic']) ? $v['pic'] : '', $i);
                $i++;
            }
            if (isset($tab)) {
                $tab_title = '<ul class="layui-tab-title">';
                $tab_content = '<div class="layui-tab-content">';

                $tab_state = false;
                foreach ($tab as $k => $v) {
                    if (isset($v['show']) && $v['show']) {
                        $tab_state = true;
                    }
                }
                $i = 0;
                foreach ($tab as $k => $v) {
                    $tab_title_class = '';
                    $tab_content_class = '';
                    if ((!$tab_state && $i == 0) || ($tab_state && isset($v['show']) && $v['show'])) {
                        $tab_title_class = 'layui-this';
                        $tab_content_class = 'layui-show';
                    }
                    $tab_title .= '<li class="'.$tab_title_class.'">'.$k.'</li>';
                    $method = 'show_' . $v['type'];
                    $tab_content .= '<div class="layui-tab-item  '.$tab_content_class.'">' . self::$method('', $v['content'], isset($v['total']) ? $v['total'] : false, isset($v['head']) ? $v['head'] : false, isset($v['pic']) ? $v['pic'] : '', $i) . '</div>';
                    $i++;
                }
                $tab_title .= '</ul>';
                $tab_content .= '</div>';
                $html .= '<div class="layui-tab layui-tab-brief" style="margin-top:10px">'.$tab_title.$tab_content.'</div>';
            }
            $html .= '</div>';
        } else {
            $html .= $body;
        }
        if ($foot) {
            if (isset($foot[0])) {
                foreach ($foot as $k => $v) {
                    $html .= self::show_foot($v);
                }
            } else {
                $html .= self::show_foot($foot);
            }
        }
        return '<div class="layui-col-md12" style="padding-left: 10px;
    padding-top: 10px;
    padding-right: 10px;
    padding-bottom: 10px;"><div class="layui-card order-detail">'.$html.'</div></div>';
    }

    public static function show_foot($foot)
    {
        $class = '';
        $html = '<div class="'.$class.' detail-header">';

        if (isset($foot['btn']) && $foot['btn']) {
            $html .= '<div class="btns" style="margin: 10px;">';
            foreach ($foot['btn'] as $k => $v) {
                $html .= self::show_btn($v);
            }
            $html .= '</div>';
        }
        $html .= '</div>';

        return $html;
    }

    public static function show_html($name, $content, $total = false, $head = false, $pic = '', $index = 0)
    {
        $html = '<section>';
        $html .= '<h3>'.$name.'</h3>';

        $html .= $content;

        $html .= '</section>';
        return $html;
    }

    /**
     * show_info
     * @param string $name
     * @param array $head
     * @param array $body
     *
     * @return string
     */
    public static function show_info($name, $content, $total = false, $head = false, $pic = '', $index = 0)
    {
        $html = '<section class="order-info">';
        $html .= '<h3>'.$name.'</h3>';

        if ($head) {
            $html .= self::show_head($head, 2);
        }
        if (!is_array($content[0][0])) {
            $content = array($content);
        }
        foreach ($content as $k => $v) {
            $html .= '<ul>';
            $n = count($v);
            foreach ($v as $k1 => $v1) {
                if (!isset($v1[0])) {
                    $v1[0] = '';
                }
                if (!isset($v1[1])) {
                    $v1[1] = '';
                }
                if (!isset($v1[2])) {
                    $v1[2] = '';
                }
                if (is_array($v1[1])) {
                    $v1[1] = '<span style="'.$v1[1]['style'].'">' . $v1[1]['name'] . '</span>';
                } else {
                    $v1[1] = '<span>' . $v1[1] . '</span>';
                }
                $style = '';
                if ($n == 1) {
                    $style = 'width:' . 100/$n . '%';
                }
                if (strstr($v1[1], 'img')) {
                    $v1[1] = '<div class="dever-img" id="dever-img-'.$index . '-' . $k.'">' . $v1[1] . '</div>';
                }
                if ($v1[0]) {
                    $v1[0] .= '：';
                }
                $html .= '<li style="'.$style.'"><label for="">'.$v1[0].'</label>'.$v1[1].''.$v1[2].'</li>';
            }
            $html .= '</ul>';
        }
        $html .= '</section>';
        return $html;
    }

    /**
     * show_user
     * @param string $name
     * @param array $head
     * @param array $body
     *
     * @return string
     */
    public static function show_user($name, $content, $total = false, $head = false, $pic = '', $index = 0)
    {
        $html = '<section class="dls-user-info">';
        $html .= '<h3>'.$name.'</h3>';

        if ($head) {
            $html .= self::show_head($head, 2);
        }
        $html .= '<dl>';
        if ($pic) {
            $html .= '<dt>
                      <img src="'.$pic.'" alt="" srcset="">
                    </dt>';
        }
        $html .= '<dd class="tit">';
        foreach ($content as $k => $v) {
            if (is_array($v)) {

                if (is_array($v[0])) {
                    foreach ($v as $k1 => $v1) {
                        if (!isset($v1[2])) {
                            $v1[2] = '';
                        }
                        if (is_array($v1[1])) {
                            $v1[1] = '<span style="'.$v1[1]['style'].'">' . $v1[1]['name'] . '</span>';
                        } else {
                            $v1[1] = '<span>' . $v1[1] . '</span>';
                        }
                        $html .= '<p><label for="">'.$v1[0].'：</label>'.$v1[1].''.$v1[2].'</p>';
                    }
                } else {
                    if (!isset($v[2])) {
                        $v[2] = '';
                    }
                    if (is_array($v[1])) {
                        $v[1] = '<span style="'.$v[1]['style'].'">' . $v[1]['name'] . '</span>';
                    } else {
                        $v[1] = '<span>' . $v[1] . '</span>';
                    }
                    $html .= '<p><label for="">'.$v[0].'：</label>'.$v[1].''.$v[2].'</p>';
                }
                
            } else {
                $html .= '<h4>'.$v.'</h4>';
            }
        }
        $html .= '</dd>';
        $html .= '</dl>';
        $html .= '</section>';
        return $html;
    }

    /**
     * show_a
     * @param string $name
     * @param array $head
     * @param array $body
     *
     * @return string
     */
    public static function show_a($name, $content, $total = false, $head = false, $pic = '', $index = 0)
    {
        $html = '<section class="order-info">';
        $html .= '<h3>'.$name.'</h3>';
        if ($head) {
            $html .= self::show_head($head, 2);
        }
        $html .= '<div class="btns">';
        foreach ($content as $k => $v) {
            $html .= self::show_btn($v);
        }
        $html .= '</div>';
        $html .= '</section>';
        return $html;
    }

    /**
     * show_list
     * @param string $name
     * @param array $content
     *
     * @return string
     */
    public static function show_list($name, $content, $total = false, $head = false, $pic = '', $index = 0)
    {
        if (!$content) {
            return '';
        }
        $html = '<section style="width: 100%;">';
        $html .= '<h3>'.$name.'</h3>';
        if ($head) {
            $html .= self::show_head($head, 2);
        }

        $html .= '<section class="goods-list">';

        foreach ($content as $k => $v) {
            $html .= '<dl>';

            if (isset($v['pic']) && $v['pic']) {
                $html .= '<dt>';
                $html .= '<img src="'.$v['pic'].'" alt="" srcset="">';
                $html .= '</dt>';
            }

            $html .= '<dd>';
            $html .= '<div>';
            $html .= '<p>'.$v['name'].'</p>';
            if (isset($v['sku']) && $v['sku']) {
                $html .= '<i>'.$v['sku'].'</i>';
            }
            
            $price = '';
            if (isset($v['price'])) {
                $price = '¥ ' . $v['price'] . ' ';
                $html .= '<em>'.$price.'<span>x '.$v['num'].'</span></em>';
            } else {
                $html .= '<em>x '.$v['num'].'</em>';
            }
            
            $html .= '</div>';
            
            $table = array();
            if (isset($v['goods'])) {
                foreach ($v['goods'] as $v1) {
                    $table[$v1['name']] = $v1['num'] . $v1['unit'];
                }
            }

            $html .= self::table($table, '', 1, 'dever-img', '50%', 'center');

            if (isset($v['status'])) {
                $html .= $v['status'];
            }
            $html .= '</dd>';
            $html .= '</dl>';
        }
        $html .= '</section>';
        $html .= '</section>';

        if ($total) {
            $html .= self::total($total);
        }
        return $html;
    }

    /**
     * ul
     * @param array $head
     * @param array $body
     *
     * @return string
     */
    public static function show_table($name, $content, $total = false, $head = false, $pic = '', $index = 0)
    {
        $html = '<section style="width: 100%;">';
        if ($name && is_string($name)) {
            $html .= '<h3>'.$name.'</h3>';
        }
        
        if ($head) {
            $html .= self::show_head($head, 2);
        }
        $html .= '<table class="layui-table">';

        $html .= '<thead><tr>';
        foreach ($content['head'] as $k => $v) {
            $html .= '<th>'.$v.'</th>';
        }
        $html .= '</tr></thead>';

        $html .= '<tbody>';
        if (count($content['body']) != count($content['body'], 1)) {
            foreach ($content['body'] as $k => $v) {
                if (is_array($v)) {
                    $html .= '<tr>';
                    foreach ($v as $k1 => $v1) {
                        if (is_array($v1)) {
                            $s = '';
                            foreach ($v1 as $k2 => $v2) {
                                $s .= $v2 . '&nbsp;&nbsp;&nbsp;&nbsp;';
                            }
                            $v1 = $s;
                        }
                        $html .= '<td>'.$v1.'</td>';
                    }
                    $html .= '</tr>';
                }
            }
        } else {
            $html .= '<tr>';
            foreach ($content['body'] as $k => $v) {
                $html .= '<td>'.$v.'</td>';
            }
            $html .= '</tr>';
        }

        $html .= '</tbody>';

        $html .= '</table>';

        if ($total) {
            $html .= self::total($total);
        }

        $html .= '</section>';

        return $html;
    }

    public static function show_head($head, $type = 1, $style = false)
    {
        $class = '';
        $html = '';
        if ($style) {
            $style_value = 'margin-left: 87px;position: fixed;top: 14px;z-index: 999;';
        } else {
            $style_value = 'margin-left: 0px;';
        }
        if (isset($head['btn']) && $head['btn']) {
            $html .= '<div class="btns" style="'.$style_value.'">';
            foreach ($head['btn'] as $k => $v) {
                $html .= self::show_btn($v);
            }
            $html .= '</div>';
        }
        if ($type == 1) {
            $class = 'layui-card-header';
        }
        if ($head['name']) {
            $html .= '<div class="'.$class.' detail-header" style="justify-content:normal;font-weight:bold">&nbsp;&nbsp;';
            $html .= $head['name'];
            $html .= '</div>';
        }
        

        return $html;
    }

    private static function show_btn($v)
    {
        $html = '';
        if (isset($v['auth'])) {
            if (!isset($v['auth'][2])) {
                $name = $v['name'];
            } else {
                $name = $v['auth'][2];
            }
            if (!Dever::load('manage/auth')->checkFunc($v['auth'][0], $v['auth'][1], $name)) {
                return $html;
            }
        }
        if (isset($v['link']) && $v['link'] == 'refer') {
            $refer = Dever::input('refer');
            if ($refer) {
                $v['link'] = Dever::decode($refer);
            }
        }
        if (isset($v['link']) && $v['link'] && !strstr($v['link'], 'manage/')) {
            $v['link'] .= '&manage_oper=' . $v['name'];
            if (isset($v['log'])) {
                if ($v['log']) {
                    $v['link'] .= '&manage_log=update.' . $v['log'];
                }
            } elseif (isset($v['auth'])) {
                $v['link'] .= '&manage_log=update.' . $v['auth'][0];
            }
        }
        
        if ($v['type'] == 'link') {
            $html .= '<a class="layui-btn layui-btn-primary" href="'.$v['link'].'">'.$v['name'].'</a>';
        } elseif ($v['type'] == 'alert') {
            $html .= '<a class="layui-btn layui-btn-primary" onclick="showAlert(\''.$v['content'].'\')">'.$v['name'].'</a>';
        } elseif ($v['type'] == 'edit') {
            $html .= '<a class="layui-btn layui-btn-primary" onclick="fastEdit($(this), \''.$v['link'].'\', \''.$v['name'].'\', \'\', 1)">'.$v['name'].'</a>';
        } elseif ($v['type'] == 'action') {
            $html .= '<a class="layui-btn layui-btn-primary" onclick="load(\''.$v['link'].'\')">'.$v['name'].'</a>';
        } elseif ($v['type'] == 'cancel') {
            $html .= '<a class="layui-btn layui-btn-primary" onclick="cancel(\''.$v['link'].'\')">'.$v['name'].'</a>';
        } elseif ($v['type'] == 'click') {
            $html .= '<a class="layui-btn layui-btn-primary" onclick="'.$v['content'].'">'.$v['name'].'</a>';
        } else {
            $html .= '<a class="layui-btn layui-btn-primary" onclick="showAlert(\''.$v['content'].'\')">'.$v['name'].'</a>';
        }

        return $html;
    }

    public static function total($total)
    {
        $html = '<section class="order-sumary border-b">';
        if (is_array($total)) {
            $price = isset($total['price']) ? '，金额：¥ '.$total['price'] : '';
            $html .= '<b>合计数量：'.$total['num'].'件'.$price.'</b>';
        } else {
            $html .= '<b>'.$total.'</b>';
        }
        $html .= '</section>';
        return $html;
    }

    public static function timeline($name, $data = array())
    {
        $html = '';

        if ($data) {
            $html .= '<ul class="layui-timeline">';
            foreach ($data as $k => $v) {
                $html .= '<li class="layui-timeline-item">
                <i class="layui-icon layui-timeline-axis"></i>
                <div class="layui-timeline-content layui-text">
                  <div class="layui-timeline-title">'.$v.'</div>
                </div>
              </li>';
            }
            $html .= '</ul>';
        }

        $html = self::card($name, $html);

        return $html;
    }

    public static function card($name, $body)
    {
        $html = '<div class="layui-card"><div class="layui-card-header">'.$name.'</div>';

        if ($body) {
            $html .= '<div class="layui-card-body">' . $body . '</div>';
        }

        $html .= '</div>';
        return $html;
    }
}