<?php

namespace APP\api\admin\api;

use APP\DI;
use APP\program\admin\Setting;
use APP\program\admin\user\Database;
use APP\program\admin\user\Notification;
use APP\program\admin\Verify;
use LyApi\core\classify\API;
use LyApi\core\error\CustomException;
use LyApi\core\request\Request;
use LyApi\tools\Launch;

class user extends API
{
    // 当前用户操作程序
    public function self()
    {

        if (!Verify::isLogin()) {
            return ['#msg' => '无访问权限'];
        }

        $do = Request::Get('do');
        $which = Request::Get('which');

        if ($do == 'update') {
            if ($which == 'password') {
                $new_password = Request::Post('newpasswd');
                if ($new_password != '') {
                    $db_connect = Setting::dbConnect();
                    $secret = $db_connect->get('users', 'secret', ['username' => $_SESSION['username']]);
                    $db_connect->update('users', [
                        'password' => Verify::encryptPwd($new_password, $secret)
                    ], ['username' => $_SESSION['username']]);
                    return 'OK';
                } else {
                    return ['#msg' => '参数不完整'];
                }
            } elseif ($which == 'userdata') {
                // 更新个人信息

                $new_username = Request::Post('username');
                $new_nickname = Request::Post('nickname');
                $new_email = Request::Post('email');

                if ($new_username != '' && $new_nickname != '' && $new_email != '') {
                    if (!filter_var($new_email, FILTER_VALIDATE_EMAIL)) {
                        return ['#code' => '400', '#msg' => '邮箱格式错误'];
                    }

                    $db_connect = Setting::dbConnect();
                    if (
                        $db_connect->has('users', ['username' => $new_username]) != true ||
                        $_SESSION['username'] == $new_username
                    ) {
                        // 如果用户名不重复，则写入新的信息
                        $result = $db_connect->update('users', [
                            'username' => $new_username,
                            'nickname' => $new_nickname,
                            'email' => $new_email
                        ], ['id' => $_SESSION['userid']]);

                        // 同时更新 Session 储存的数据
                        $_SESSION['username'] = $new_username;
                        $_SESSION['nickname'] = $new_nickname;

                        if ($result->errorCode() == '00000') {
                            return 'OK';
                        } else {
                            return ['#code' => '500', '#msg' => '数据保存失败'];
                        }
                    } else {
                        return ['#code' => '400', '#msg' => '用户名已存在'];
                    }
                } else {
                    return ['#code' => '400', '#msg' => '参数不完整'];
                }
            }
        } elseif ($do == 'outlogin') {
            unset($_SESSION['userid']);
            unset($_SESSION['username']);
            unset($_SESSION['nickname']);
            return 'OK';
        }
        return ['#msg' => '目标不存在'];
    }

    public function lists($type, $args)
    {
        if (!Verify::isLogin()) {
            return ['#code' => 401, '#msg' => '账号无访问权限...'];
        } else if (!Verify::authCheck("douser")) {
            return ['#code' => 401, '#msg' => '账号无访问权限...'];
        }

        if ($type == "API") {
            $limit = Request::Request('limit');
            $page = Request::Request('page');
        } else {
            $limit = $args['limit'];
            $page = $args['page'];
        }

        if ($limit == '' || $page == '') {
            $limit = 15;
            $page = 1;
        }

        $db_connect = Setting::dbConnect();

        // 取得读取的数据前后
        if ($page > 1) {
            $start_num = ($page * $limit) - 1;
        } else {
            $start_num = 0;
        }

        $end_num = $start_num + $limit;

        $where = [
            'LIMIT' => [$start_num, $end_num]
        ];

        // 搜索数据，如不存在则正常索引
        if (Request::Request('search') != '') {
            $cond = explode('|', Request::Request('search'));
            if (count($cond) == 1) {
                $where['username'] = $cond[0];
            } else {
                if ($cond[0] != '') {
                    $where['username'] = $cond[0];
                    $where['nickname'] = $cond[1];
                } else {
                    $where['nickname'] = $cond[1];
                }
            }
        }

        $data = $db_connect->select('users', '*', $where);

        if (count($data) == 0) {
            // 接口数据为空，无法正常读取
            return ['#msg' => '无任何接口数据..'];
        } else {
            // 预处理一些数据
            foreach ($data as $key => $value) {
                $data[$key]['createtime'] = date('Y年m月d日', $data[$key]['createtime']);
                $data[$key]['level'] = $db_connect->get('user_level', 'title', ['id' => $data[$key]['level']]);
                if ($data[$key]['usable'] == 1) {
                    $data[$key]['usable'] = '正常';
                } else {
                    $data[$key]['usable'] = '停用';
                }
            }
        }

        return $data;
    }

    // 取得用户权限级别数据
    public function ulevel($type, $args)
    {
        $do = $args['do'];

        if (!Verify::isLogin()) {
            return ['#msg' => '无访问权限...'];
        } else if (!Verify::authCheck("douser")) {
            return ['#msg' => '无访问权限...'];
        }

        $db_connect = Setting::dbConnect();

        if ($do == 'get') {
            return $db_connect->select('user_level', ['id', 'title']);
        } else if ($do == 'list') {
            return $db_connect->select('user_level', '*');
        } else if ($do == 'new') {
            // 检查参数是否完整
            if (
                array_key_exists('title', $args) && array_key_exists('douser', $args) &&
                array_key_exists('doapi', $args) && array_key_exists('doplugin', $args) &&
                array_key_exists('dosetting', $args) && array_key_exists('docoder', $args) &&
                array_key_exists('dodb', $args)
            ) {
                if (Verify::isLogin()) {
                    if (Verify::authCheck('douser')) {
                        if ($args['title'] != '') {
                            if (!$db_connect->has('user_level', ['title' => $args['title']])) {

                                if ($db_connect->count('user_level') >= 10) {
                                    return ['#msg' => '权限总数超出限制'];
                                }

                                if ($args['douser'] != '1') {
                                    $args['douser'] = '0';
                                }

                                if ($args['doapi'] != '1') {
                                    $args['doapi'] = '0';
                                }

                                if ($args['dodb'] != '1') {
                                    $args['dodb'] = '0';
                                }

                                if ($args['doplugin'] != '1') {
                                    $args['doplugin'] = '0';
                                }

                                if ($args['dosetting'] != '1') {
                                    $args['dosetting'] = '0';
                                }

                                if ($args['docoder'] != '1') {
                                    $args['docoder'] = '0';
                                }

                                $db_connect->insert('user_level', [
                                    'title' => $args['title'],
                                    'douser' => $args['douser'],
                                    'doapi' => $args['doapi'],
                                    'dodb' => $args['dodb'],
                                    'doplugin' => $args['doplugin'],
                                    'dosetting' => $args['dosetting'],
                                    'docoder' => $args['docoder']
                                ]);
                                return 'OK';
                            } else {
                                return ['#msg' => '权限名称已存在'];
                            }
                        } else {
                            return ['#code' => '400', '#msg' => '权限名称为空'];
                        }
                    } else {
                        return ['#code' => '401', '#msg' => '账号无权限'];
                    }
                } else {
                    return ['#code' => '401', '#msg' => '账号未登录'];
                }
            }
            return ['#code' => '400', '#msg' => '参数不完整'];
        } else if ($do == 'del') {
            if (Verify::isLogin()) {
                if (Verify::authCheck('douser')) {
                    if (array_key_exists('eid', $args)) {
                        if ($db_connect->has('user_level', ['id' => $args['eid']])) {
                            if ($db_connect->has('users', [''])) {
                                $db_connect->delete('user_level', ['id' => $args['eid']]);
                                return 'OK';
                            } else {
                            }
                        } else {
                            return ['#code' => '404', '#msg' => '数据不存在'];
                        }
                    }
                    return ['#code' => '400', '#msg' => '参数不完整'];
                } else {
                    return ['#code' => '401', '#msg' => '账号无权限'];
                }
            } else {
                return ['#code' => '401', '#msg' => '账号未登录'];
            }
        }
    }

    // 创建新的用户
    public function adduser($type, $args)
    {
        // 判断用户是否符合要求
        if (Verify::isLogin()) {
            if (Verify::authCheck('douser')) {

                $username = $args['username'];
                $nickname = $args['nickname'];
                $password = $args['password'];
                $ulevel = $args['ulevel'];
                $email = $args['email'];

                if ($username != '' && $nickname != '' && $password != '' && $ulevel != '' && $email != '') {
                    $db_connect = Setting::dbConnect();

                    // 确保用户名不重复
                    if ($db_connect->has('users', ['username' => $username])) {
                        return ['#msg' => '用户名已存在'];
                    }

                    // 确保等级确实存在
                    if (!$db_connect->has('user_level', ['id' => $ulevel])) {
                        return ['#msg' => '权限等级不存在'];
                    }


                    $secret = base64_encode(rand());
                    $password = Verify::encryptPwd($password, $secret);

                    // 写入数据
                    $db_connect->insert('users', [
                        'username' => $username,
                        'nickname' => $nickname,
                        'password' => $password,
                        'level' => $ulevel,
                        'secret' => $secret,
                        'email' => $email,
                        'usable' => 1,
                        'createtime' => time()
                    ]);

                    return 'OK';
                } else {
                    return ['#code' => '400', '#msg' => '参数不完整'];
                }
            } else {
                return ['#code' => '401', '#msg' => '账号无权限'];
            }
        } else {
            return ['#code' => '401', '#msg' => '账号未登录'];
        }
    }

    // 删除用户操作
    public function deluser($type, $args)
    {
        // 预留内部启动方法
        if ($type == 'API') {
            $id = Request::Post('id');
            $password = Request::Post('password');
        } else {
            return ['#msg' => '暂不支持内部启动'];
        }

        if (!Verify::isLogin()) {
            return ['#code' => '401', '#msg' => '账号未登录'];
        } else {
            if (!Verify::authCheck('douser')) {
                return ['#code' => '401', '#msg' => '账号无权限'];
            }
        }

        // 判断参数是否齐全
        if ($id != '' && $password != '') {
            $db_connect = Setting::dbConnect();

            // 验证当前身份
            $secret = $db_connect->get('users', 'secret', ['id' => $_SESSION['userid']]);
            $password = Verify::encryptPwd($password, $secret);

            if ($db_connect->has('users', ['id' => $_SESSION['userid'], 'password' => $password])) {

                // 第一账号禁止删除
                if ($id == '1') {
                    return ["#msg" => "为了系统安全，您不能删除本账号！"];
                }

                // 判定用户是否已存在
                if (!$db_connect->has('users', ['id' => $id])) {
                    return ['#msg' => '用户不存在'];
                }

                // 判断是不是最后一个账号
                if ($db_connect->count('users') <= 1) {
                    return ['#msg' => '用户需至少保留一个'];
                }

                $db_connect->delete('users', ['id' => $id]);
                return 'OK';
            } else {
                return ['#code' => '400', '#msg' => '密码验证失败'];
            }
        } else {
            return ['#code' => '400', '#msg' => '参数不完整'];
        }
    }

    // 用户数据更新接口
    public function upduser()
    {
        $userid = Request::Request('userid');
        $username = Request::Request('username');
        $nickname = Request::Request('nickname');
        $usable = Request::Request('usable');
        $email = Request::Request('email');
        $acode = Request::Request('acode');

        if ($userid != '' && $username != '' && $nickname != '' && $usable != '' && $email != '') {
            if ($acode != '') {

                // 验证输入的验证码
                $acheck = Launch::LaunchApi('APP\api\admin\api', 'acode', [
                    'from' => 'uupd:' . $_SERVER['REMOTE_ADDR'],
                    'check' => $acode
                ]);

                if ($acheck['data'] == 'OK') {
                    //  进入权限检测
                    if (Verify::isLogin()) {
                        if (Verify::authCheck('douser')) {
                            $db_connect = Setting::dbConnect();
                            if ($db_connect->has('users', ['id' => $userid])) {
                                $db_connect->update('users', [
                                    'username' => $username,
                                    'nickname' => $nickname,
                                    'usable' => $usable,
                                    'email' => $email
                                ], ['id' => $userid]);
                                return 'OK';
                            } else {
                                return ['#code' => '404', '#msg' => '用户数据不存在'];
                            }
                        } else {
                            return ['#code' => '401', '#msg' => '账号无权限'];
                        }
                    } else {
                        return ['#code' => '401', '#msg' => '账号未登录'];
                    }
                } else {
                    return ['#code' => '401', '#msg' => $acheck['message']];
                }
            } else {
                return ['#code' => '401', '#msg' => '验证码出错'];
            }
        }
        return ['#code' => '400', '#msg' => '参数不完整'];
    }

    // 用户消息操作接口
    public function message()
    {
        if (!Verify::isLogin()) {
            return ['#code' => '401', '#msg' => '账号未登录'];
        }

        $do = Request::Get('do');
        if ($do == 'heartbeat') {

            $num = Request::Get("num");
            if ($num == '') {
                $num = 0;
            }

            // 心跳包程序: 用于实时监控消息是否更新
            return Notification::newMessage(false, $num);
        } else if ($do == 'forall') {
            $type = Request::Get('type');

            if ($type == 'readed') {
                Notification::newMessage(true);
                return 'OK';
            } else if ($type == 'clean') {
                Notification::cleanAll();
                return 'OK';
            }
        } else if ($do == 'forone') {

            $type = Request::Get('type');
            $meid = Request::Get('meid');

            if ($meid != '') {
                if ($type == 'readed') {
                    Notification::readit($meid);
                    return 'OK';
                } else if ($type == 'delete') {
                    Notification::delete($meid);
                    return 'OK';
                }
            }
        }
    }
}
