<?php
namespace Gm\Controller;
/**
 * Class User
 * Desc  用户类
 */

use Framework\Lib\Utils;
use Gm\Comm\CommFunc;
use Gm\Config\Config;
use Gm\Config\ErrorCode;
use Gm\Model\Users;
use Gm\Model\Logs;
use Gm\Lib\Jwt;

class User {

    use CommFunc;

    public function __construct() {

    }

    const USER_LOG_TYPE = 1;

    // 登录
    public function Login() {
        $params = json_decode(file_get_contents("php://input"));
        if(is_null($params)) {
            return ;
        }
        $username = $params->username;
        if (strlen($params->password) == 32) {
            $password = $params->password;
        } else {
            $password = md5($params->password);
        }
//        var_dump($password);
        $user = Users::Login($username, $password);

        if(empty($user)) {
            $this->ReturnErr(400, '账号或密码错误');
            return ;
        }

// 过期时间 24小时 60*60*24
        $jwt_info = array(
            'iss'=>'system',
            'info' => $user,
            'iat'=>Utils::getServerTimestamp(),
            'exp'=>Utils::getServerTimestamp() + Config::TOKEN_TIMEOUT,
            'jti'=>md5(uniqid('JWT', true).Utils::getServerTimestamp())
        );
        $jwt_token = Jwt::getToken($jwt_info);
        $token = ['token' => $jwt_token];
        // 存储token
        Users::SaveToken($user['id'], $jwt_token);

        $this->ReturnSucc(ErrorCode::SUCCESS, '登录成功',$token);
    }

    // 用户信息
    public function UserInfo() {
        $user = Jwt::verifyToken();
        if(!$user) {
            $this->ReturnErr(400, '账号token已过期，请重新登录');
        } else {
            if(isset($_GET['id'])) {
                $uid = $_GET['id'];
            } else {
                $uid = $user['info']['id'];
            }
            $menu = [];
            $menuid = Users::GetUserMenuIdByUid($uid);
            if(!empty($menuid)) {
                foreach ($menuid as $k) {
                    $menu[] = $k['menu_id'];
                }
            }

            $r = [
                'menus' => $menu,
                'userinfo' => $user['info']
            ];

            $this->ReturnSucc(ErrorCode::SUCCESS, 'success',$r);
        }
    }

    // 用户列表
    public function List() {
        $search = $_GET['search'];
        $page = $_GET['page'];
        $limit = $_GET['limit'];

        $data = Users::GetUserList($search, $page, $limit);
        $count = Users::GetUserCount($search);
        $r = [
            "data" => $data,
            "count" => (int)$count
        ];
        $this->ReturnSucc(ErrorCode::SUCCESS, '查询成功',$r);
    }

    // 新增和修改用户
    public function Save() {
        $params = json_decode(file_get_contents("php://input"));
        $id = $params->id;
        $username = $params->username;
        if (strlen($params->password) == 32) {
            $password = $params->password;
        } else {
            $password = md5($params->password);
        }
        $avatar = $params->avatar;
        $status = $params->status;
        $desc = $params->desc;
        $checkeds = $params->checkeds;
        $user_data = Jwt::verifyToken();
        if(empty($id)) {
            // 判断用户是否存在
            if($this->userIsHave($username)) {
                $this->ReturnErr(ErrorCode::ERROR_GM_INTERNAL, "用户已经存在，请勿重复添加！");
                return ;
            }

            // 存储用户数据
            if(Users::AddUser($username, $password, $avatar, $status, $desc)) {
                // 增加权限
                $user = Users::GetUserByUsername($username);
                if(!empty($checkeds)) {
                    foreach ($checkeds as $v) {
                        Users::AddUserMenuID($user['id'], $v);
                    }
                }

                $log_info = $user_data['info']['username']. ' 增加了用户 '. $username. ', 赋予了菜单权限 '. json_encode($checkeds);
                $log_data = [
                    'username' => $username,
                    'password' => $params->password,
                    'avatar'   => $avatar,
                    'status'   => $status,
                    'desc'     => $desc
                ];

                Logs::InsData(User::USER_LOG_TYPE, $user_data['info']['username'], $log_info, json_encode($log_data));
                $this->ReturnSucc(ErrorCode::SUCCESS);
            } else {
                $this->ReturnErr(ErrorCode::ERROR_GM_INTERNAL, "用户创建失败");
            }
        } else {
            $beforeUser = Users::GetUserById($id);

            $menu = [];
            $menuid = Users::GetUserMenuIdByUid($id);
            if(!empty($menuid)) {
                foreach ($menuid as $k) {
                    $menu[] = $k['menu_id'];
                }
            }
            $beforeUser['menu'] = $menu;
            // 修改用户数据
            if(Users::UpdateUser($id, $username, $password, $avatar, $status, $desc)) {
                // 删除权限
                Users::DeleteUserMenuID($id);

                // 增加权限
                if(!empty($checkeds)) {
                    foreach ($checkeds as $v) {
                        Users::AddUserMenuID($id, $v);
                    }
                }

                $log_info = $user_data['info']['username']. ' 修改了用户 '. $beforeUser['username'] . ' 为 ' . $username
                    . ', 修改菜单权限 '. json_encode($menu). ' 为 '. json_encode($checkeds);
                $log_data = [
                    'before' => $beforeUser,
                    'after'   => [
                        'username' => $username,
                        'password' => $params->password,
                        'avatar'   => $avatar,
                        'status'   => $status,
                        'desc'     => $desc,
                        'menu'     => $menu
                    ]
                ];

                Logs::InsData(User::USER_LOG_TYPE, $user_data['info']['username'], $log_info, json_encode($log_data));
                $this->ReturnSucc(ErrorCode::SUCCESS);
            } else {
                $this->ReturnErr(ErrorCode::ERROR_GM_INTERNAL, "用户更新失败");
            }
        }
    }

    public function userIsHave($username) {
        $user = Users::GetUserByUsername($username);
        if(empty($user)) {
            return false;
        }
        return true;
    }

    public function Delete() {
        $params = json_decode(file_get_contents("php://input"));
        $id = $params->id;
        $user_data = Jwt::verifyToken();
        $user = Users::GetUserById($id);

        $log_info = $user_data['info']['username'] . ' 删除了用户 '. $user['username'];


        if(Users::DeleteUserById($id)) {
            Logs::InsData(User::USER_LOG_TYPE, $user_data['info']['username'], $log_info, $log_info);
            $this->ReturnSucc(ErrorCode::SUCCESS, '删除成功');
        } else {
            $this->ReturnErr(ErrorCode::ERROR_GM_INTERNAL, "删除用户失败");
        }
    }


    public function Detail() {
        $id = $_GET['id'];
        $user = Users::GetUserById($id);
        if(empty($user)) {
            $this->ReturnErr(ErrorCode::ERROR_GM_INTERNAL, '操作失败');
        } else {
            $menu = [];
            $menuid = Users::GetUserMenuIdByUid($id);
            if(!empty($menuid)) {
                foreach ($menuid as $k) {
                    $menu[] = $k['menu_id'];
                }
            }
            $this->ReturnSucc(ErrorCode::SUCCESS, $user);
        }
    }

}