<?php

namespace app\controller;

// use \Firebase\JWT\JWT;

use app\Request;
use app\View;
use app\Session;
use app\model\User;
use app\utils\RRException;
use app\utils\ParsedownExtension;

class Index extends View
{
    public function auth()
    {
        if (!Session::get('userid')) {
            echo "您未登录请登录";
            header("Location: /login", TRUE, 301);

            exit();
        }
    }

    public function index()
    {
        $this->auth();

        $request = Request::getInstance();

        $doc = $request->params['doc'];

        $doc = ltrim($doc, '/');

        if (substr($doc, -1) === '/') {
            $doc = $doc . "index.md";
        }

        $doc = empty($doc) ? 'index.md' : $doc;

        if (pathinfo($doc, PATHINFO_EXTENSION) != 'md') {
            $doc = $doc . ".md";
        }

        $filename = DATA_PATH . $doc;
        $text = "";
        $toc = "";
        $content = "";

        if ($is_file_exists = file_exists($filename)) {
            $parsedownExtension = new ParsedownExtension();
            $parsedownExtension->setTocEnabled(true);
            $text = file_get_contents($filename);
            $res = $parsedownExtension->text($text);
            $toc = $res['toc'];
            $content = $res['content'];
        }

        $this->assign('doc', $doc);
        $this->assign('is_file_exists', $is_file_exists);
        $this->assign('text', $text);
        $this->assign('toc', $toc);
        $this->assign('content', $content);

        $this->fetch();
    }

    public function editor()
    {
        $doc = $GLOBALS['doc'];
        var_dump($doc);
        exit;
        $this->fetch();
    }

    public function save()
    {
        $this->auth();

        // 获取payload json数据，转换成数组形式
        $postData = file_get_contents('php://input');
        $requests = !empty($postData) ? json_decode($postData, true) : [];

        $doc = $requests['doc'];
        $content = $requests['content'];

        $pathinfo = pathinfo($doc);

        $dir_name = DATA_PATH . $pathinfo['dirname'];

        if (!is_dir($dir_name) && !mkdir($dir_name, 0744, true)) {
            die(json_encode(['code' => 2, 'msg' => '目录创建失败']));
        }

        $filename = DATA_PATH . $doc;

        $res = file_put_contents($filename, $content);

        if ($res === false) {
            echo json_encode(['code' => 2, 'msg' => '保存失败']);
        } else {
            echo json_encode(['code' => 0, 'msg' => '保存成功, 字数:' . $res]);
        }
        die();
    }

    // private function validate ()
    // {
    //     $jwt = isset($_SERVER['HTTP_TOKEN']) ? $_SERVER['HTTP_TOKEN'] : '';
    //     if (empty($jwt)) {
    //         throw new RRException("You do not have permission to access.", 401);
    //     }

    //     try {
    //         JWT::$leeway = 60;
    //         $decoded = JWT::decode($jwt, KEY, ['HS256']);
    //         $arr = (array)$decoded;
    //         if ($arr['exp'] < time()) {
    //             throw new RRException("认证信息已过期, 请重新登录.", 401);
    //         }
    //     } catch(\Exception $e) {
    //         throw new RRException($e->getMessage(), 401);
    //     }

    //     return true;
    // }

    public function login()
    {
        if (Session::get('userid')) {
            echo "您已登录请登录";
            header("Location: /index", TRUE, 301);

            exit();
        }

        $request = Request::getInstance();

        if ($request->isPost()) {
            $username = strip_tags(htmlentities($request->params['username']));
            $password = strip_tags(htmlentities($request->params['password']));

            if (!$username || !$password) {
                throw new RRException("用户名或密码不能为空!", 1);
            }

            $user = new User();

            $info = $user->getInfoByUsername($username);

            if (!$info) {
                throw new RRException("用户名或密码错误!", 1);
            }

            if (md5($password) !== $info['password']) {
                throw new RRException("用户名或密码错误!", 1);
            }

            // // 用户名和密码正确，则签发tokon
            // $nowtime = time();
            // $jwtInfo = [
            //     'iss' => 'huwhois@163.com', //签发者
            //     'iat' => $nowtime, //签发时间
            //     'nbf' => $nowtime + 10, //在什么时间之后该jwt才可用
            //     'exp' => $nowtime + 64800, //过期时间-18h
            //     'data' => [
            //         'userid' => $user['id'],
            //         'username' => $username
            //     ]
            // ];
            // $token = JWT::encode($jwtInfo, KEY);
            // echo json_encode(['code'=>0, 'msg'=>'success', 'token'=>$token]);
            // 存 session
            Session::set('userid', $info['id']);
            Session::set('username', $info['username']);

            echo json_encode(['code' => 0, 'msg' => 'success']);
            die();
        } else {
            $this->fetch();
        }
    }

    public function logout()
    {
        Session::destroy();
        echo "登出成功.....";
        header("Location: /login", TRUE, 301);

        exit();
    }

    public function password()
    {
        $request = Request::getInstance();
        if ($request->isPost()) {
            $userid = Session::get('userid');

            if (!$userid) {
                throw new RRException('用户未登录, 请登录');
            }

            $user = new User();

            // 修改密码
            $oldpassword = isset($request->params['oldpassword']) ? (string) $request->params['oldpassword'] : '';
            $password    = isset($request->params['newpassword']) ? (string) $request->params['newpassword'] : '';
            $repassword  = isset($request->params['repassword']) ? (string) $request->params['repassword'] : '';

            if (!$password) {
                throw new RRException("密码不能为空", 1);
            }

            if ($password != $repassword) {
                throw new RRException("两次密码不一致", 1);
            }

            $userinfo = $user->getInfoById($userid);

            if (md5($oldpassword) != $userinfo['password']) {
                throw new RRException("原密码不正确", 1);
            }

            try {
                $user->updateById([
                    'id' => $userid,
                    'password' => md5($password)
                ]);
            } catch (\Exception $e) {
                throw new RRException($e->getMessage(), 1);
            }

            Session::destroy();
            echo json_encode(['code' => 0, 'msg' => "保存成功"]);
            die();
        }
    }

    public function userlist()
    {
        $list = (new User())->dataList();

        $this->assign('list', $list);

        $this->fetch();
    }

    public function userdelete()
    {
        $request = Request::getInstance();

        if ($request->isPost()) {
            $id = isset($request->params['userid']) ? (int) $request->params['userid'] : 0;

            if (!$id) {
                throw new RRException('userid 不能为空', 1);
            }

            $res = (new User())->deleteById($id);

            if ($res) {
                throw new RRException('操作成功', 0);
            } else {
                throw new RRException('操作失败', 1);
            }
        }
    }

    public function userinfo()
    {
        $request = Request::getInstance();

        $userid = isset($request->params['userid']) ? (int) $request->params['userid'] : 0;

        if ($userid !== 0) {
            $data = (new User())->getInfoById($userid);

            unset($data['password']);

            echo  json_encode(['code' => 0, 'info' => $data]);
        } else {
            throw new RRException("userid 不能为空", 1);
        }
        die();
    }

    public function usersave()
    {
        $request = Request::getInstance();

        if ($request->isPost()) {
            $id = isset($request->params['userid']) ? (int) $request->params['userid'] : 0;

            $user = new User();

            if ($id === 0) {
                // 新增
                $username = isset($request->params['username']) ? (string) $request->params['username'] : '';

                if (!$username) {
                    throw new RRException("用户名不能为空", 1);
                }

                $password = isset($request->params['password']) ? (string) $request->params['password'] : '';
                $repassword = isset($request->params['repassword']) ? (string) $request->params['repassword'] : '';

                if (!$password) {
                    throw new RRException("密码不能为空", 1);
                }

                if ($password != $repassword) {
                    throw new RRException("两次密码不一致", 1);
                }

                try {
                    $user->save([
                        'username' => $username,
                        'password' => md5($password),
                        'create_time' => time()
                    ]);
                } catch (\Exception $e) {
                    throw new RRException($e->getMessage(), 1);
                }

                echo json_encode(['code' => 0, 'msg' => "保存成功"]);
                die();
            } else {
                // 修改密码
                $password = isset($request->params['password']) ? (string) $request->params['password'] : '';
                $repassword = isset($request->params['repassword']) ? (string) $request->params['repassword'] : '';

                if (!$password) {
                    throw new RRException("密码不能为空", 1);
                }

                if ($password != $repassword) {
                    throw new RRException("两次密码不一致", 1);
                }

                // $userinfo = $user->getInfoById($id);

                // $newpassword = md5($password);

                // if ($newpassword != $userinfo['password']) {
                //     throw new RRException("原密码不正确", 1);
                // }

                try {
                    $user->updateById([
                        'id' => $id,
                        'password' => md5($password)
                    ]);
                } catch (\Exception $e) {
                    throw new RRException($e->getMessage(), 1);
                }

                echo json_encode(['code' => 0, 'msg' => "保存成功, 请重新登录."]);
                die();
            }
        }
    }
}
