<?php namespace sc;

use PHPMailer\PHPMailer\PHPMailer;

class Helper
{
    /**
     * @var array 分页配置
     */
    public $pageNumberStyle = [
        'tags'   => [
            'home' => '',
            'last' => '',
            'prev' => 'Previous',
            'next' => 'Next',
            'jump' => ''
        ],
        'class'  => [
            'normal' => '',
            'active' => 'page_active',
            'home'   => '',
            'last'   => '',
            'prev'   => 'sc_pre',
            'next'   => 'sc_pre',
        ],
        'length' => 5
    ];

    /**
     * 分页方法
     *
     * @param string $url
     * @param int    $count
     * @param int    $size
     * @param int    $page
     *
     * @return array
     */
    public function pageNumber($url, $count, $size, $page = 1)
    {
        // 处理URL
        $len = strlen($this->url());
        $path = substr($url, $len);
        $pos = strrpos($path, '.');
        if (false !== $pos) {
            $url = substr($url, 0, $len + $pos - 1);
            $suffix = substr($path, $pos);
        } else {
            if (false !== strpos($url, '?')) {
                $url = trim(strchr($url, '?', true), '/');
                $suffix = '/'.strchr($path, '?');
            } else {
                $url = trim($url, '/');
                $suffix = '/';
            }
        }

        // 页码长度
        $len = ceil($count / $size);

        // 标签按钮
        if (1>= $page) {
            $page = 1;
            $home = implode('', [
                '<li class="', $this->pageNumberStyle['class']['home'], '"><a href="javascript:">',
                $this->pageNumberStyle['tags']['home'], '</a></li>'
            ]);
            $prev = implode('', [
                '<li class="', $this->pageNumberStyle['class']['prev'], '"><a href="javascript:">',
                $this->pageNumberStyle['tags']['prev'], '</a></li>'
            ]);
            if (1 < $len) {
                $next = implode('', [
                    '<li class="', $this->pageNumberStyle['class']['next'], '">',
                    '<a href="', $url, '_', $page + 1, $suffix, '">',
                    $this->pageNumberStyle['tags']['next'], '</a></li>'
                ]);
                $last = implode('', [
                    '<li class="', $this->pageNumberStyle['class']['last'], '">',
                    '<a href="', $url, '_', $len, $suffix, '">',
                    $this->pageNumberStyle['tags']['last'], '</a></li>'
                ]);
            } else {
                $next = implode('', [
                    '<li class="', $this->pageNumberStyle['class']['next'], '"><a href="javascript:">',
                    $this->pageNumberStyle['tags']['next'], '</a></li>'
                ]);
                $last = implode('', [
                    '<li class="', $this->pageNumberStyle['class']['last'], '"><a href="javascript:">',
                    $this->pageNumberStyle['tags']['last'], '</a></li>'
                ]);
            }
        } else if ($len <= $page) {
            $page = $len;
            if (1 < $len) {
                $home = implode('', [
                    '<li class="', $this->pageNumberStyle['class']['home'], '">',
                    '<a href="', $url, '_', 1, $suffix, '">',
                    $this->pageNumberStyle['tags']['home'], '</a></li>'
                ]);
                $prev = implode('', [
                    '<li class="', $this->pageNumberStyle['class']['prev'], '">',
                    '<a href="', $url, '_', $page - 1, $suffix, '">',
                    $this->pageNumberStyle['tags']['prev'], '</a></li>'
                ]);
            } else {
                $home = implode('', [
                    '<li class="', $this->pageNumberStyle['class']['home'], '"><a href="javascript:">',
                    $this->pageNumberStyle['tags']['home'], '</a></li>'
                ]);
                $prev = implode('', [
                    '<li class="', $this->pageNumberStyle['class']['prev'], '"><a href="javascript:">',
                    $this->pageNumberStyle['tags']['prev'], '</a></li>'
                ]);
            }
            $next = implode('', [
                '<li class="', $this->pageNumberStyle['class']['next'], '"><a href="javascript:">',
                $this->pageNumberStyle['tags']['next'], '</a></li>'
            ]);
            $last = implode('', [
                '<li class="', $this->pageNumberStyle['class']['last'], '"><a href="javascript:">',
                $this->pageNumberStyle['tags']['last'], '</a></li>'
            ]);
        } else {
            $home = implode('', [
                '<li class="', $this->pageNumberStyle['class']['home'], '">',
                '<a href="', $url, '_', 1, $suffix, '">',
                $this->pageNumberStyle['tags']['home'], '</a></li>'
            ]);
            $prev = implode('', [
                '<li class="', $this->pageNumberStyle['class']['prev'], '">',
                '<a href="', $url, '_', $page - 1, $suffix, '">',
                $this->pageNumberStyle['tags']['prev'], '</a></li>'
            ]);
            $next = implode('', [
                '<li class="', $this->pageNumberStyle['class']['next'], '">',
                '<a href="', $url, '_', $page + 1, $suffix, '">',
                $this->pageNumberStyle['tags']['next'], '</a></li>'
            ]);
            $last = implode('', [
                '<li class="', $this->pageNumberStyle['class']['last'], '">',
                '<a href="', $url, '_', $len, $suffix, '">',
                $this->pageNumberStyle['tags']['last'], '</a></li>'
            ]);
        }

        // 页码长度
        if (5 < $len && $len > $this->pageNumberStyle['length']) {
            if (3 > $page) {
                $start = 1;
                $end = $this->pageNumberStyle['length'];
            } else if ($page + $this->pageNumberStyle['length'] - 3 > $len) {
                $start = $len - $this->pageNumberStyle['length'] + 1;
                $end = $len;
            } else {
                $start = $page - 2;
                $end = $page + $this->pageNumberStyle['length'] - 3;
            }
        } else {
            $start = 1;
            $end = $len;
        }

        $page_number[] = empty($this->pageNumberStyle['tags']['home']) ? '' : $home;
        $page_number[] = empty($this->pageNumberStyle['tags']['prev']) ? '' : $prev;

        // 页码按钮
        for ($i = $start; $i <= $end; $i++) {
            if ($i == $page) {
                $page_number[] = implode('', [
                    '<li class="', $this->pageNumberStyle['class']['active'], '"><a href="javascript:">',
                    $i, '</a></li>'
                ]);
            } else {
                $page_number[] = implode('', [
                    '<li class="', $this->pageNumberStyle['class']['normal'], '">',
                    '<a href="', $url, '_', $i, $suffix, '">',
                    $i, '</a></li>'
                ]);
            }
        }

        $page_number[] = empty($this->pageNumberStyle['tags']['next']) ? '' : $next;
        $page_number[] = empty($this->pageNumberStyle['tags']['last']) ? '' : $last;

        // 页码信息
        return [
            'count' => $count,
            'size'  => $size,
            'len'   => $len,
            'html'  => implode('', $page_number)
        ];
    }

    /**
     * 获取当前URL路径方法
     */
    public function path()
    {
        $request = new Request();

        $uri = $request->server('REQUEST_URI');
        $pos = strrpos($uri, '/');

        // 获取配置
        $conf = include CONF . '/conf.php';

        return $conf['host']['protocol'] . '://' . $request->server('HTTP_HOST') . substr($uri, 0, $pos);
    }

    /**
     * 生成URL方法
     *
     * @param string $url
     * @param bool   $dir
     * @param array  $params
     *
     * @return string
     */
    public function url($url = null, $dir = true, $params = null)
    {
        // 生成GET参数
        if (null != $params) {
            $params = '?' . http_build_query($params);
        }

        $url = trim($url, '/');

        // 生成URL
        $conf = include CONF . '/conf.php';

        // 查询语种
        $lang = '';
        if (defined('LANG')) {
            $lang = (new DB($conf['database']))->table('lang')->find('l_main')->where('l_word = ?', [LANG])->one();
            if ($lang == false || $lang['l_main'] == 1) {
                $lang = '';
            } else {
                $lang = '/' . LANG;
            }
        }

        return null == $url ? implode('', [
            $conf['host']['protocol'], '://', $conf['host']['hostname'], $lang, $params
        ]) : implode('', [
            $conf['host']['protocol'], '://', $conf['host']['hostname'], $lang, '/',
            $url, $dir ? '/' : $conf['host']['suffix'], $params
        ]);
    }

    /**
     * 生成文件链接方法
     *
     * @param string $url
     * @param bool   $real
     *
     * @return string
     */
    public function to($url, $real = true)
    {
        $conf = include CONF . '/conf.php';
        $tpl = rtrim(json_decode(file_get_contents(CONF . '/template.json'), true)['template'], '/');

        $url = trim($url, '/');

        return $real ? implode('', [
            $conf['host']['protocol'], '://', $conf['host']['hostname'], '/', $url
        ]) : implode('', [
            $conf['host']['protocol'], '://', $conf['host']['hostname'], '/templates/', $tpl, '/', $url
        ]);
    }

	/**
	 * 发送邮件方法
	 *
	 * @param array        $params
	 * @param array|string $emails
	 * @param string       $content
	 */
    public function mail($params, $emails, $content) {
	    $mailer = new PHPMailer(true);
	    try {
		    ob_start();
		    $mailer->SMTPDebug = 2;
		    $mailer->isSMTP();
		    $mailer->Host = $params['smtp'];
		    $mailer->SMTPAuth = true;
		    $mailer->Username = $params['account'];
		    $mailer->Password = $params['ciphers'];
		    $mailer->SMTPSecure = 'ssl';
		    $mailer->Port = $params['port'];
		    $mailer->setFrom($params['address'], '');
		    if (is_array($emails)) {
		    	foreach ($emails as $email) {
				    $mailer->addAddress($email);
			    }
		    } else {
			    $mailer->addAddress($emails);
		    }
		    $mailer->isHTML(true);
		    $mailer->Subject = $params['subject'];
		    $mailer->Body = $content;
		    $mailer->send();
		    ob_end_clean();
	    } catch (\Exception $e) {
	    	//echo $e->getMessage();
	    }
    }

    /**
     * 迭代生成先祖树方法
     *
     * @param array $data
     * @param int   $id
     *
     * @return array
     */
    public function parentTree($data, $id = 0)
    {
        $tree = [];
        while ($id > 0) {
            foreach ($data as $datum) {
                if ($id == $datum['id']) {
                    $tree[] = $datum;
                    $id = $datum['pid'];
                }
            }
        }

        return $tree;
    }

    /**
     * 递归生成列表树方法
     *
     * @param array $data
     * @param int   $id
     * @param int   $level
     * @param bool  $clear
     *
     * @return array
     */
    function listTree($data, $id = 0, $level = 0, $clear = true)
    {
        static $tree = [];
        if ($clear) {
            $tree = [];
        }
        foreach ($data as $index => $datum) {
            if ($id == $datum['pid']) {
                $datum['level'] = $level;
                $tree[] = $datum;
                $this->listTree($data, $datum['id'], $level + 1, false);
            }
        }

        return $tree;
    }

    /**
     * 递归生成子孙树方法
     *
     * @param array $data
     * @param int   $id
     *
     * @return array
     */
    function subTree($data, $id = 0)
    {
        $tree = [];
        foreach ($data as $datum) {
            if ($datum['pid'] == $id) {
                $t = $this->subTree($data, $datum['id']);
                if ($t) {
                    $datum['sub'] = $t;
                }
                $tree[] = $datum;
            }
        }
        $return = $tree;
        unset($tree);

        return $return;
    }

    /**
     * 验证邮箱合法性方法
     *
     * @param string $input
     *
     * @return bool
     */
    public function isEmail($input)
    {
        return (bool)filter_var($input, FILTER_VALIDATE_EMAIL);
    }

    /**
     * 验证手机合法性方法
     *
     * @param string $input
     *
     * @return bool
     */
    public function isPhone($input)
    {
        return (bool)preg_match('/1(3[4-9]|4[7]|5[0-27-9]|7[08]|8[2-478])\d{8}|1(3[0-2]|4[5]|5[56]|7[0156]|8[56])\d{8}|1(3[3]|4[9]|53|7[037]|8[019])\d{8}/', $input);
    }

    /**
     * 验证日期合法性方法
     *
     * @param string $input
     *
     * @return bool
     */
    public function isDate($input)
    {
        return (bool)preg_match('/^((\d{2}(([02468][048])|([13579][26]))[\-\/\s]?((((0?[13578])|(1[02]))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\-\/\s]?((0?[1-9])|([1-2][0-9])))))|(\d{2}(([02468][1235679])|([13579][01345789]))[\-\/\s]?((((0?[13578])|(1[02]))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\-\/\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))$/', $input);
    }

    /**
     * 验证时间合法性方法
     *
     * @param string $input
     *
     * @return bool
     */
    public function isTime($input)
    {
        return (bool)preg_match('/^(((0?[0-9])|([1-2][0-3]))\:([0-5]?[0-9])((\s)|(\:([0-5]?[0-9]))))$/', $input);
    }

    /**
     * 验证完整日期合法性方法
     *
     * @param string $input
     *
     * @return bool
     */
    public function isDatetime($input)
    {
        return (bool)preg_match('/^((\d{2}(([02468][048])|([13579][26]))[\-\/\s]?((((0?[13578])|(1[02]))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\-\/\s]?((0?[1-9])|([1-2][0-9])))))|(\d{2}(([02468][1235679])|([13579][01345789]))[\-\/\s]?((((0?[13578])|(1[02]))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\-\/\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(\s(((0?[0-9])|([1-2][0-3]))\:([0-5]?[0-9])((\s)|(\:([0-5]?[0-9])))))?$/', $input);
    }
}