<?php

/**
 * 冰雪传奇H5
 * 2022 XX信息科技有限公司
 *
 * @author    123456
 * @wx        123456
 * @qq        123456
 */

//header('content-Type: application/json; charset=utf-8');

include 'config.php';
include 'function.php';

$typeNames = [0 => '登录', 1 => '注册', 2 => '找回密码'];

$act = input('act');
$do = input('do');

switch ($act) {
    case 'reg':
        $fromMicroClient = 'microClient' == $do;

        $type = intval(input('type'));
        $account = input('account');
        $password = input('password');
        $serverId = 0;
        $email = '';
        $agent_id = 0;

        if (!in_array($type, [0, 1, 2]))
            returnJson(['code' => 1, 'msg' => '参数错误！请刷新页面重试~'], $fromMicroClient);

        if (!$account)
            returnJson(['code' => 1, 'msg' => '请输入' . $_CONFIG['account_name'] . $_CONFIG['account_name_suffix']], $fromMicroClient);
        if (6 > strlen($account) && !in_array($account, array_unique(explode(',', trim($_CONFIG['admin_account'])))) || 16 < strlen($account))
            returnJson(['code' => 1, 'msg' => $_CONFIG['account_name'] . $_CONFIG['account_name_suffix'] . '长度为6-16个字符'], $fromMicroClient);

        if (!$password)
            returnJson(['code' => 1, 'msg' => '请输入' . $_CONFIG['account_name'] . $_CONFIG['password_name_suffix']], $fromMicroClient);
        if (6 > strlen($password) || 16 < strlen($password))
            returnJson(['code' => 1, 'msg' => $_CONFIG['account_name'] . $_CONFIG['password_name_suffix'] . '长度为6-16个字符'], $fromMicroClient);

        $ip = get_ip();

        // 检查IP是否被封
        if ($_CONFIG['deny_ip']) {
            $deny_ip = array_unique(explode(',', trim($_CONFIG['deny_ip'])));
            if (!empty($deny_ip) && in_array($ip, $deny_ip)) {
                returnJson(['code' => 1, 'msg' => '当前未开放访问！'], $fromMicroClient); // 当前IP已禁用
            }
        }

        $md5Pwd = md5($password . PASSWORD_KEY);
        $time = time();

        // 做一下从微端登录/注册的兼容 start --------------------------------------------------
        if ($fromMicroClient) {
            // 关闭验证码
            $_CONFIG['code_open'] = 0;
            // 连接数据库
            $mySQLi = new mysqli($_CONFIG_DB['db_host'], $_CONFIG_DB['db_user'], $_CONFIG_DB['db_password'], $_CONFIG_DB['db_name'], $_CONFIG_DB['db_port']);
            if ($mySQLi->connect_errno)
                returnJson(['code' => 1, 'msg' => $mySQLi->connect_error], $fromMicroClient);
            $mySQLi->set_charset($_CONFIG_DB['db_charset']);
            // 先查询账号是否存在
            $stmt = $mySQLi->prepare('select password from player where username=?');
            $stmt->bind_param('s', $account);
            $stmt->execute();
            $result = $stmt->get_result();
            $row = $result->fetch_array();
            $result->free_result();
            $stmt->close();
            // 如果帐号存在但密码错误表示登录模式
            if (!empty($row)) {
                if ($md5Pwd != $row['password']) {
                    returnJson(['code' => 1, 'msg' => $_CONFIG['account_name'] . $_CONFIG['account_name_suffix'] . '或' . $_CONFIG['password_name_suffix'] . '不正确！'], $fromMicroClient);
                }
                $type = 0;
            } else { // 否则表示注册模式
                $type = 1;
                $_CONFIG['reg_code_open'] = 0;
            }
        }
        // 做一下从微端登录/注册的兼容 end --------------------------------------------------

        // 提前检查条件
        switch ($type) {
            case 1: // 注册
                // 是否开放注册
                if (!$_CONFIG['reg_open']) {
                    returnJson(['code' => 1, 'msg' => '内部测试中，未开放注册，如需体验请联系客服。'], $fromMicroClient);
                }
                // 检查保留帐号
                if ($_CONFIG['retain_account']) {
                    $retain_account = array_unique(explode(',', trim($_CONFIG['retain_account'])));
                    if (!empty($retain_account) && in_array($account, $retain_account)) {
                        returnJson(['code' => 1, 'msg' => '抱歉！此' . $_CONFIG['account_name'] . $_CONFIG['account_name_suffix'] . '已被占用，请更换。'], $fromMicroClient);
                    }
                }

                $password2 = input('password2');
                $serverId = intval(input('serverId'));
                $email = input('email');
                if ($_CONFIG['code_open'] && $_CONFIG['reg_code_open']) {
                    $code = input('code');
                }

                if (!$fromMicroClient) {
                    if (!$password2)
                        returnJson(['code' => 1, 'msg' => '请再次输入' . $_CONFIG['account_name'] . $_CONFIG['password_name_suffix']], $fromMicroClient);
                    if (6 > strlen($password2) || 16 < strlen($password2))
                        returnJson(['code' => 1, 'msg' => $_CONFIG['account_name'] . $_CONFIG['password_name_suffix'] . '长度为6-16个字符'], $fromMicroClient);
                    if ($password2 != $password)
                        returnJson(['code' => 1, 'msg' => '两次输入的' . $_CONFIG['account_name'] . $_CONFIG['password_name_suffix'] . '不一致！'], $fromMicroClient);
                }
                if (!$serverId)
                    returnJson(['code' => 1, 'msg' => '请选择区服！'], $fromMicroClient);
                if ($_CONFIG['code_open']) {
                    if ($_CONFIG['reg_code_open'] && !$email)
                        returnJson(['code' => 1, 'msg' => '请输入邮箱地址！'], $fromMicroClient);
                    if ($email && !filter_var($email, FILTER_VALIDATE_EMAIL))
                        returnJson(['code' => 1, 'msg' => '邮箱地址格式错误！'], $fromMicroClient);

                    if ($_CONFIG['reg_code_open']) {
                        if (!$code)
                            returnJson(['code' => 1, 'msg' => '请输入邮箱验证码！'], $fromMicroClient);
                        if (strlen($code) != $_CONFIG['code_length'])
                            returnJson(['code' => 1, 'msg' => '验证码长度为6位数字！'], $fromMicroClient);
                    }
                }

                $agent_id = intval(input('agent_id'));
                break;
            case 0: // 登录
                // 是否开放登录
                if (!$_CONFIG['login_open'] && !in_array($account, array_unique(explode(',', trim($_CONFIG['admin_account']))))) {
                    returnJson(['code' => 1, 'msg' => '内部测试中，未开放登录，如需体验请联系客服。'], $fromMicroClient);
                }
                break;
            case 2: // 找回密码
                if (!$_CONFIG['code_open']) {
                    returnJson(['code' => 1, 'msg' => '验证码系统尚未开启！']);
                }

                $password2 = input('password2');
                $email = input('email');
                $code = input('code');

                if (!$password2)
                    returnJson(['code' => 1, 'msg' => '请输入' . $_CONFIG['account_name'] . $_CONFIG['password_name_suffix']]);
                if (6 > strlen($password2) || 16 < strlen($password2))
                    returnJson(['code' => 1, 'msg' => $_CONFIG['account_name'] . $_CONFIG['password_name_suffix'] . '长度为6-16个字符']);
                if ($password2 != $password)
                    returnJson(['code' => 1, 'msg' => '两次输入的' . $_CONFIG['account_name'] . $_CONFIG['password_name_suffix'] . '不一致！']);

                if (!$email)
                    returnJson(['code' => 1, 'msg' => '请输入邮箱地址！']);
                if (!filter_var($email, FILTER_VALIDATE_EMAIL))
                    returnJson(['code' => 1, 'msg' => '邮箱地址格式错误！']);

                if (!$code)
                    returnJson(['code' => 1, 'msg' => '请输入邮箱验证码！']);
                if (strlen($code) != $_CONFIG['code_length'])
                    returnJson(['code' => 1, 'msg' => '验证码长度为6位数字！']);
                break;
        }

        if (!isset($mySQLi)) {
            $mySQLi = new mysqli($_CONFIG_DB['db_host'], $_CONFIG_DB['db_user'], $_CONFIG_DB['db_password'], $_CONFIG_DB['db_name'], $_CONFIG_DB['db_port']);
            if ($mySQLi->connect_errno)
                returnJson(['code' => 1, 'msg' => $mySQLi->connect_error], $fromMicroClient);
            $mySQLi->set_charset($_CONFIG_DB['db_charset']);
        }

        // 限制每日注册数量上限
        if (1 == $type && $_CONFIG['day_max_reg']) {
            $stmt2 = $mySQLi->prepare("SELECT id FROM player WHERE reg_ip = ? AND FROM_UNIXTIME(reg_time, '%Y-%m-%d') = CURDATE()");
            $stmt2->bind_param('s', $ip);
            $stmt2->execute();
            $result2 = $stmt2->get_result();
            $row2 = $result2->fetch_array();
            $regNum = $result2->num_rows;
            $result2->free_result();
            $stmt2->close();
            if ($regNum >= $_CONFIG['day_max_reg']) {
                $mySQLi->close();
                returnJson(['code' => 10, 'msg' => '您今日注册量已达上限，请明日再试~'], $fromMicroClient);
            }
        }

        if (2 != $type) {
            $field = ['id'];
            if (0 == $type) {
                $field[] = 'password';
            }
            $stmt = $mySQLi->prepare('select ' . implode(', ', $field) . ' from player where username=?');
            $stmt->bind_param('s', $account);
            $stmt->execute();
            $result = $stmt->get_result();
            $row = $result->fetch_array();
            $result->free_result();
            $stmt->close();
        }

        // 创建账号
        if (1 == $type) {
            if (!empty($row)) {
                $mySQLi->close();
                returnJson(['code' => 1, 'msg' => '此' . $_CONFIG['account_name'] . $_CONFIG['account_name_suffix'] . '已被其他勇士占用！请更换。'], $fromMicroClient);
            }

            // test
            //returnJson(['code' => 1, 'msg' => 'test register: '.$email], $fromMicroClient);

            if ($email) {
                // 检查邮箱地址是否被占用
                $stmt = $mySQLi->prepare('select id from player where email=?');
                $stmt->bind_param('s', $email);
                $stmt->execute();
                $result = $stmt->get_result();
                $row = $result->fetch_array();
                $result->free_result();
                $stmt->close();
                if (!empty($row)) {
                    $mySQLi->close();
                    returnJson(['code' => 1, 'msg' => '此邮箱地址已被其他勇士占用！请更换。', $fromMicroClient]);
                }

                // 获取验证码记录
                if ($_CONFIG['code_open'] && $_CONFIG['reg_code_open']) {
                    $stmt = $mySQLi->prepare('select id, code from verify where account=? and email=? and type=?');
                    $stmt->bind_param('ssi', $account, $email, $type);
                    $stmt->execute();
                    $result = $stmt->get_result();
                    $row = $result->fetch_array();
                    $result->free_result();
                    $stmt->close();
                    if (empty($row) || $code != $row['code']) {
                        $mySQLi->close();
                        returnJson(['code' => 1, 'msg' => '验证码无效！'], $fromMicroClient);
                    }
                }
            }

            $device = isMobile() ? 1 : 0;
            $os = getOS();
            $browse = getBrowse();

            //echo $account.', '.$md5Pwd.', '.$email.', '.$device.', '.getOS().', '.getBrowse().', '.$time.', '.$ip;exit;

            $stmt1 = $mySQLi->prepare('insert into `player` (username, password, server_id, email, agent_id, device, os, browse, reg_time, reg_ip) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
            $stmt1->bind_param('ssisiissis', $account, $md5Pwd, $serverId, $email, $agent_id, $device, $os, $browse, $time, $ip);
            $stmt1->execute();
            $rowNum = $stmt1->affected_rows;
            $stmt1->close();
            if (0 < $rowNum) {
                // 删除验证码
                if ($_CONFIG['code_open'] && $_CONFIG['reg_code_open']) {
                    $stmt = $mySQLi->prepare('DELETE FROM verify WHERE id = ? and type=?');
                    $stmt->bind_param('ii', $row['id'], $type);
                    $stmt->execute();
                    $stmt->close();
                }

                // 代理人
                if (0 < $agent_id) {
                    // 检查代理人是否存在
                    $stmt = $mySQLi->prepare('select id from `agent` where id = ?');
                    $stmt->bind_param('i', $agent_id);
                    $stmt->execute();
                    $result = $stmt->get_result();
                    $row = $result->fetch_array();
                    $result->free_result();
                    $stmt->close();
                    // 如果代理人存在
                    if (!empty($row)) {
                        // 更新代理人邀请统计
                        $stmt = $mySQLi->prepare('UPDATE `agent` SET invite_count = invite_count + 1 WHERE id = ?');
                        $stmt->bind_param('i', $agent_id);
                        $stmt->execute();
                        $stmt->close();
                    }
                }

                $mySQLi->close();

                setcookie('account', $account, $_CONFIG['session_time']);
                setcookie('password', $password, $_CONFIG['session_time']);
                setcookie('token', $md5Pwd, $_CONFIG['session_time']);
                $_SESSION['account'] = $account;
                $_SESSION['password'] = $password;
                $_SESSION['token'] = $md5Pwd;

                $msgLast = '<br/><br/>';
                $msgLast .= $_CONFIG['account_name'] . $_CONFIG['account_name_suffix'] . '：' . $account;
                $msgLast .= '<br/>';
                $msgLast .= $_CONFIG['account_name'] . $_CONFIG['password_name_suffix'] . '：' . $password;
                $msgLast .= '<br/>';
                $msgLast .= '邮箱地址：' . $email;

                $msg = '恭喜勇士！获得玛法' . $_CONFIG['account_name'] . '，请牢记' . $_CONFIG['account_name'] . $_CONFIG['password_name_suffix'] . '！准备开启玛法之旅..' . (!$fromMicroClient ? $msgLast : '');
                $resData = [
                    'code' => 0,
                    'msg' => $msg,
                    'token' => $md5Pwd
                ];
                if ($fromMicroClient) {
                    $resData['url'] = '/play?account=' . $account . '&token=' . $md5Pwd;
                }
                returnJson($resData, $fromMicroClient);
            } else {
                $mySQLi->close();
                returnJson(['code' => 1, 'msg' => $_CONFIG['account_name'] . '获取失败，请重试~'], $fromMicroClient);
            }
        } elseif (0 == $type) { // 登录
            $mySQLi->close();
            if (empty($row) || $md5Pwd !== $row['password']) {
                returnJson(['code' => 1, 'msg' => '传送员无法匹配此' . $_CONFIG['account_name'] . '，请检查！'], $fromMicroClient);
            } else {
                setcookie('account', $account, $_CONFIG['session_time']);
                setcookie('password', $password, $_CONFIG['session_time']);
                setcookie('token', $md5Pwd, $_CONFIG['session_time']);
                $_SESSION['account'] = $account;
                $_SESSION['password'] = $password;
                $_SESSION['token'] = $md5Pwd;

                $resData = ['code' => 0, 'msg' => '欢迎来到清渊传奇，正在传送…', 'token' => $md5Pwd];
                if ($fromMicroClient) {
                    $resData['url'] = '/play?account=' . $account . '&token=' . $md5Pwd;
                }
                returnJson($resData, $fromMicroClient);
            }
        } elseif (2 == $type) { // 重置密码
            if (!$_CONFIG['code_open']) {
                $mySQLi->close();
                returnJson(['code' => 1, 'msg' => '验证码系统尚未开启！']);
            }

            // 检查邮箱地址是否存在
            $stmt = $mySQLi->prepare('select email from player where username=? and email=?');
            $stmt->bind_param('ss', $account, $email);
            $stmt->execute();
            $result = $stmt->get_result();
            $row = $result->fetch_array();
            $result->free_result();
            $stmt->close();
            if (empty($row)) {
                $mySQLi->close();
                returnJson(['code' => 1, 'msg' => '传送员无法匹配此' . $_CONFIG['account_name'] . '，请检查！']);
            }

            // 检查验证码
            $stmt = $mySQLi->prepare('select id, code from verify where email=? and type=?');
            $stmt->bind_param('si', $email, $type);
            $stmt->execute();
            $result = $stmt->get_result();
            $row = $result->fetch_array();
            $result->free_result();
            $stmt->close();
            if (empty($row) || $code != $row['code']) {
                $mySQLi->close();
                returnJson(['code' => 1, 'msg' => '验证码不正确！']);
            }

            // 修改密码
            $stmt = $mySQLi->prepare('UPDATE `player` SET password = ? WHERE username=? and email=?');
            $stmt->bind_param('sss', $md5Pwd, $account, $email);
            $stmt->execute();
            $stmt->close();

            // 删除验证码
            $stmt = $mySQLi->prepare('DELETE FROM verify WHERE id = ? and type= ?');
            $stmt->bind_param('ii', $row['id'], $type);
            $stmt->execute();
            $stmt->close();

            $mySQLi->close();
            returnJson(['code' => 0, 'msg' => $_CONFIG['account_name'] . $_CONFIG['password_name_suffix'] . '修改成功！']);
        }
        break;
    case 'getCode': // 发送验证码到邮箱
        if (!$_CONFIG['code_open']) {
            returnJson(['code' => 1, 'msg' => '验证码系统尚未开启！']);
        }

        $type = intval(input('type'));
        $account = input('account');
        $email = input('email');

        if (!in_array($type, [1, 2]))
            returnJson(['code' => 1, 'msg' => '参数错误！请刷新页面重试~']);

        if (!$account)
            returnJson(['code' => 1, 'msg' => '请输入' . $_CONFIG['account_name'] . $_CONFIG['account_name_suffix']]);
        if (6 > strlen($account) && !in_array($account, array_unique(explode(',', trim($_CONFIG['admin_account'])))) || 16 < strlen($account))
            returnJson(['code' => 1, 'msg' => $_CONFIG['account_name'] . $_CONFIG['account_name_suffix'] . '长度为6-16个字符']);

        if (!$email)
            returnJson(['code' => 1, 'msg' => '请输入邮箱地址！']);
        if (!filter_var($email, FILTER_VALIDATE_EMAIL))
            returnJson(['code' => 1, 'msg' => '邮箱地址格式错误！']);

        $ip = get_ip();

        // 检查IP是否被封
        if ($_CONFIG['deny_ip']) {
            $deny_ip = array_unique(explode(',', trim($_CONFIG['deny_ip'])));
            if (!empty($deny_ip) && in_array($ip, $deny_ip)) {
                returnJson(['code' => 1, 'msg' => '当前未开放访问！']); // 当前IP已禁用
            }
        }

        if (1 == $type) {
            // 是否开放注册
            if (!$_CONFIG['reg_open']) {
                returnJson(['code' => 1, 'msg' => '内部测试中，未开放注册，如需体验请联系客服。']);
            }
            // 检查保留帐号
            if ($_CONFIG['retain_account']) {
                $retain_account = array_unique(explode(',', trim($_CONFIG['retain_account'])));
                if (!empty($retain_account) && in_array($account, $retain_account)) {
                    returnJson(['code' => 1, 'msg' => '抱歉！此' . $_CONFIG['account_name'] . $_CONFIG['account_name_suffix'] . '已被占用，请更换。']);
                }
            }
        }

        $mySQLi = new mysqli($_CONFIG_DB['db_host'], $_CONFIG_DB['db_user'], $_CONFIG_DB['db_password'], $_CONFIG_DB['db_name'], $_CONFIG_DB['db_port']);
        if ($mySQLi->connect_errno)
            returnJson(['code' => 1, 'msg' => $mySQLi->connect_error]);
        $mySQLi->set_charset($_CONFIG_DB['db_charset']);

        if (1 == $type) {
            // 限制每日注册数量上限
            if ($_CONFIG['day_max_reg']) {
                $stmt2 = $mySQLi->prepare("SELECT id FROM player WHERE reg_ip = ? AND FROM_UNIXTIME(reg_time, '%Y-%m-%d') = CURDATE()");
                $stmt2->bind_param('s', $ip);
                $stmt2->execute();
                $result2 = $stmt2->get_result();
                $row2 = $result2->fetch_array();
                $regNum = $result2->num_rows;
                $result2->free_result();
                $stmt2->close();
                if ($regNum >= $_CONFIG['day_max_reg']) {
                    $mySQLi->close();
                    returnJson(['code' => 10, 'msg' => '您今日注册量已达上限，请明日再试~']);
                }
            }
        }

        if (1 == $type) { // 注册时
            // 检查帐号是否被占用
            $stmt = $mySQLi->prepare('select id from player where username=?');
            $stmt->bind_param('s', $account);
            $stmt->execute();
            $result = $stmt->get_result();
            $row = $result->fetch_array();
            $result->free_result();
            $stmt->close();
            if (!empty($row)) {
                $mySQLi->close();
                returnJson(['code' => 1, 'msg' => '此' . $_CONFIG['account_name'] . $_CONFIG['account_name_suffix'] . '已被其他勇士占用！请更换。']);
            }
            // 检查邮箱地址是否被占用
            $stmt = $mySQLi->prepare('select id from player where email=?');
            $stmt->bind_param('s', $email);
            $stmt->execute();
            $result = $stmt->get_result();
            $row = $result->fetch_array();
            $result->free_result();
            $stmt->close();
            if (!empty($row)) {
                $mySQLi->close();
                returnJson(['code' => 1, 'msg' => '此邮箱地址已被其他勇士占用！请更换。']);
            }
        } else if (2 == $type) { // 找回密码时：检查帐号和邮箱地址是否存在
            $stmt = $mySQLi->prepare('select id from player where username=? and email=?');
            $stmt->bind_param('ss', $account, $email);
            $stmt->execute();
            $result = $stmt->get_result();
            $row = $result->fetch_array();
            $result->free_result();
            $stmt->close();
            if (empty($row)) {
                $mySQLi->close();
                returnJson(['code' => 1, 'msg' => '传送员无法匹配此' . $_CONFIG['account_name'] . '，请检查！']);
            }
        }

        // 获取验证码记录
        $stmt = $mySQLi->prepare('select id, time from verify where account=? and email=? and type=?');
        $stmt->bind_param('ssi', $account, $email, $type);
        $stmt->execute();
        $result = $stmt->get_result();
        $row = $result->fetch_array();
        $result->free_result();
        $stmt->close();

        $sendInterval = $_CONFIG['code_send_interval'];
        $nowTime = time();
        $leftTime = ($sendInterval - ($nowTime - $row['time']));

        // 检查发送时间间隔
        if (!empty($row) && $nowTime - $row['time'] < $sendInterval) {
            $mySQLi->close();
            returnJson([
                'code' => 1,
                'msg' => '操作频繁！请' . $leftTime . '秒后发送~',
                'time' => $leftTime
            ]);
        }

        $code = getRandomString($_CONFIG['code_length'], $_CONFIG['code_data_type']);

        if ('email' == $_CONFIG['code_type']) {
            // 邮件主题
            $subject = '【' . $_CONFIG['game_name'] . '】' . $typeNames[$type];
            // 邮件正文
            $message = '<div style="background: #000 url(' . $_CONFIG['web_url'] . '/resource_Publish/assets/phonebg/loading_1.jpg) no-repeat left center; padding: 50px; width: 950px; height: 700px;">';
            $message .= '<div style="background: rgba(0, 0, 0, .5); border-radius: 6px; color: #fff; padding: 25px; width: 400px; height: 250px;">';
            $message .= $subject . '<br/><br/>';
            $message .= '您的' . $_CONFIG['account_name'] . $_CONFIG['account_name_suffix'] . '：' . $account . '<br/>';
            $message .= '您的验证码：<span style="font-weight: 700; font-size: 16px; text-decoration: underline;">' . $code . '</span><br/><br/>';
            $message .= '用于' . $typeNames[$type] . '验证，5分钟内使用有效。<br/><br/>';
            $message .= '<a href="' . $_CONFIG['web_url'] . '" target="_blank" title="' . $_CONFIG['game_name'] . '">' . $_CONFIG['game_name'] . '</a> ' . $_CONFIG['game_description'] . '<br/>';
            $message .= '<a href="' . $_CONFIG['web_url'] . '" target="_blank" title="' . $_CONFIG['game_name'] . '">' . $_CONFIG['web_url'] . '</a><br/><br/>';
            $message .= '如有疑问请联系客服QQ：' . $_CONFIG['kf_qq'] . ' / 客服微信：' . $_CONFIG['kf_wx'];
            $message .= '</div>';
            $message .= '</div>';

            require_once 'php/PHPMailer/PHPMailer.php';
            require_once 'php/PHPMailer/SMTP.php';

            $mail = new PHPMailer();
            // 是否启用smtp的debug进行调试 开发环境建议开启 生产环境注释掉即可 默认关闭debug调试模式
            $mail->SMTPDebug = 0;
            // 使用smtp鉴权方式发送邮件
            $mail->isSMTP();
            // smtp需要鉴权 这个必须是true
            $mail->SMTPAuth = true;
            $mail->Host = $_CONFIG['mail_host'];
            // 设置使用ssl加密方式登录鉴权
            $mail->SMTPSecure = 'ssl';
            $mail->Port = $_CONFIG['mail_port'];
            $mail->CharSet = $_CONFIG['mail_charset'];
            $mail->FromName = $_CONFIG['game_name'];
            $mail->Username = $_CONFIG['mail_from'];
            $mail->Password = $_CONFIG['mail_password'];
            $mail->From = $_CONFIG['mail_from'];
            $mail->isHTML(true);
            // 设置收件人邮箱地址
            $mail->addAddress($email);
            // 添加多个收件人 则多次调用方法即可
            //$mail->addAddress('317743968@qq.com');
            $mail->Subject = $subject;
            $mail->Body = $message;
            //$mail->addAttachment('./example.pdf');
            $status = $mail->send();
        } elseif ('mobile' == $_CONFIG['code_type']) {
            $status = 0;
        }

        // 检查发送时间间隔
        if (!$status) {
            $mySQLi->close();
            returnJson([
                'code' => 1,
                'msg' => '验证码发送失败！请重试~',
                'time' => $leftTime
            ]);
        }

        // 插入验证记录
        if (empty($row)) {
            $stmt1 = $mySQLi->prepare('insert into `verify` (account, type, email, code, time, ip) values(?, ?, ?, ?, ?, ?)');
            $stmt1->bind_param('sisiis', $account, $type, $email, $code, $nowTime, $ip);
            $stmt1->execute();
            $rowNum = $stmt1->affected_rows;
            $stmt1->close();
            if (!$rowNum) {
                $mySQLi->close();
                returnJson(['code' => 1, 'msg' => '验证码发送失败！请重试~']);
            }
        } else {
            $stmt1 = $mySQLi->prepare('UPDATE `verify` SET code=?, time=? WHERE id=? and type=?');
            $stmt1->bind_param('siii', $code, $nowTime, $row['id'], $type);
            $stmt1->execute();
            $stmt1->close();
            $mySQLi->close();
        }

        returnJson(['code' => 0, 'msg' => '验证码已经发送到您的邮箱：' . $email . '，请查收！', 'time' => $sendInterval]);
        break;
    case 'check': // 验证帐号
        switch ($do) {
            case 'verify':
                $account = input('account');
                $token = input('token');

                if (!$account || 6 > strlen($account) && !in_array($account, array_unique(explode(',', trim($_CONFIG['admin_account'])))) || 16 < strlen($account) || !$token || 32 != strlen($token))
                    returnJson(['code' => 1, 'msg' => 'account or password error']);

                // 是否开放登录
                if (!$_CONFIG['login_open'] && !in_array($account, array_unique(explode(',', trim($_CONFIG['admin_account'])))))
                    returnJson(['code' => 1, 'msg' => '内部测试中，未开放登录，如需体验请联系客服。']);

                // 检查IP是否被封
                if ($_CONFIG['deny_ip']) {
                    $ip = get_ip();
                    $deny_ip = array_unique(explode(',', trim($_CONFIG['deny_ip'])));
                    if (!empty($deny_ip) && in_array($ip, $deny_ip)) {
                        returnJson(['code' => 1, 'msg' => '当前未开放访问！']); // 当前IP已禁用
                    }
                }

                $mySQLi = new mysqli($_CONFIG_DB['db_host'], $_CONFIG_DB['db_user'], $_CONFIG_DB['db_password'], $_CONFIG_DB['db_name'], $_CONFIG_DB['db_port']);
                if ($mySQLi->connect_errno)
                    returnJson(['code' => 1, 'msg' => $mySQLi->connect_error]);

                $mySQLi->set_charset($_CONFIG_DB['db_charset']);

                $stmt = $mySQLi->prepare('select id from player where username=? and password=?');
                $stmt->bind_param('ss', $account, $token);
                $stmt->execute();

                $result = $stmt->get_result();
                $row = $result->fetch_array();

                $result->free_result();
                $stmt->close();
                $mySQLi->close();

                if (!$row)
                    returnJson(['code' => 1, 'msg' => 'account no exist']);

                // 验证成功
                returnJson(['code' => 0]);
                break;
            default:
                echo 'success';
        }
        break;
    case 'enter_game':
        if (!isPost())
            returnJson(['code' => 1, 'msg' => 'request error']);

        $srvId = intval(input('srvId'));
        $account = input('account');
        $token = input('token');

        if (!$srvId || !$account || !$token || 32 != strlen($token))
            returnJson(['code' => 1, 'msg' => 'param error']);

        // 是否开放登录
        if (!$_CONFIG['login_open'] && !in_array($account, array_unique(explode(',', trim($_CONFIG['admin_account']))))) {
            returnJson(['code' => 1, 'msg' => '内部测试中，未开放登录，如需体验请联系客服。']);
        }

        $time = time();
        $ip = get_ip();

        // 检查IP是否被封
        if ($_CONFIG['deny_ip']) {
            $deny_ip = array_unique(explode(',', trim($_CONFIG['deny_ip'])));
            if (!empty($deny_ip) && in_array($ip, $deny_ip)) {
                returnJson(['code' => 1, 'msg' => '当前未开放访问！']); // 当前IP已禁用
            }
        }

        $mySQLi = new mysqli($_CONFIG_DB['db_host'], $_CONFIG_DB['db_user'], $_CONFIG_DB['db_password'], $_CONFIG_DB['db_name'], $_CONFIG_DB['db_port']);
        if ($mySQLi->connect_errno)
            returnJson(['code' => 1, 'msg' => $mySQLi->connect_error]);
        $mySQLi->set_charset($_CONFIG_DB['db_charset']);

        // 检查帐号是否存在
        $stmt = $mySQLi->prepare('select id from player where username=? and password=?');
        $stmt->bind_param('ss', $account, $token);
        $stmt->execute();

        $result = $stmt->get_result();
        $row = $result->fetch_array();

        $result->free_result();
        $stmt->close();

        if (empty($row)) {
            $mySQLi->close();
            returnJson(['code' => 1, 'msg' => 'account no exist']);
        }

        // 更新登录时间和登录IP
        $stmt = $mySQLi->prepare('UPDATE `player` SET login_time = ?, login_ip = ? WHERE username=?');
        $stmt->bind_param('iss', $time, $ip, $account);
        $stmt->execute();

        $stmt->close();
        $mySQLi->close();

        // TODO: login server history

        returnJson(['code' => 0]);
        break;
    case 'game': // 游戏接口
        switch ($do) {
            case 'withdraw': // 提现
                if (!isPost())
                    returnJson(['code' => 1, 'msg' => 'request error']);
                if (!in_array($_CONFIG['withdraw']['type'], array_keys($_CONFIG['currency_list'])))
                    returnJson(['code' => 1, 'msg' => 'currency error']);

                $serverId = intval(substr(input('server_id'), 1));
                $account = input('account');
                $token = input('token');
                $roleId = intval(input('role_id'));
                $roleName = input('role_name');
                $payType = intval(input('pay_type'));
                $payAccount = input('pay_account');
                $amount = intval(input('amount'));

                /* 检查参数 ---------------------------------------------------------------------------------------------------- */

                if (!$serverId || !$account || !$roleId || !$roleName || !$payAccount || !$amount)
                    returnJson(['code' => 1, 'msg' => '参数错误！']);
                if (26 < strlen($account))
                    returnJson(['code' => 1, 'msg' => '参数错误！']);
                if (!$token || 32 != strlen($token))
                    returnJson(['code' => 1, 'msg' => '参数错误！']);
                if (24 < strlen($roleName))
                    returnJson(['code' => 1, 'msg' => '参数错误！']);
                if (!in_array($payType, [0, 1]))
                    returnJson(['code' => 1, 'msg' => '收款账户类型不正确！']);
                if (30 < strlen($payAccount))
                    returnJson(['code' => 1, 'msg' => '收款账户格式不正确！']);

                // 检查是否开启提现功能
                //if($_CONFIG['withdraw']['sid'] != $serverId) returnJson(['code' => 1, 'msg' => '尚未开启提现功能！']);
                // 检查最低提现数量
                if ($_CONFIG['withdraw']['ratio'] > $amount)
                    returnJson(['code' => 1, 'msg' => '最低提现数量为' . $_CONFIG['withdraw']['ratio']]);
                // 限制一次提现人民币最低20元
                $maxNum = $_CONFIG['withdraw']['ratio'] * 20;
                if ($maxNum > $amount)
                    returnJson(['code' => 1, 'msg' => '单次提现数量不能低于' . $maxNum]);

                $time = time();
                $accountId = 0;
                $currencyName = $_CONFIG['currency_list'][$_CONFIG['withdraw']['type']];
                $currencyField = $_CONFIG['currency_field'][$_CONFIG['withdraw']['type']];

                /* 连接帐号数据库 ---------------------------------------------------------------------------------------------------- */

                $mySQLi = new mysqli($_CONFIG_DB['db_host'], $_CONFIG_DB['db_user'], $_CONFIG_DB['db_password'], $_CONFIG_DB['db_name'], $_CONFIG_DB['db_port']);
                if ($mySQLi->connect_errno)
                    returnJson(['code' => 1, 'msg' => $mySQLi->connect_error]);
                $mySQLi->set_charset($_CONFIG_DB['db_charset']);

                /* 检查帐号是否存在 ---------------------------------------------------------------------------------------------------- */

                $stmt = $mySQLi->prepare('select id from player where username=? and password=?');
                $stmt->bind_param('ss', $account, $token);
                $stmt->execute();

                $result = $stmt->get_result();
                $row = $result->fetch_array(MYSQLI_ASSOC);

                $result->free_result();
                $stmt->close();

                if (empty($row)) {
                    $mySQLi->close();
                    returnJson(['code' => 1, 'msg' => '账号不存在！']);
                }

                /* 限制提现时间间隔 ---------------------------------------------------------------------------------------------------- */

                $withdrawMinTime = 30;
                $stmt = $mySQLi->prepare('select time from withdraw where server_id = ? and role_id = ? order by id desc limit 1');
                $stmt->bind_param('ii', $serverId, $roleId);
                $stmt->execute();

                $result = $stmt->get_result();
                $row = $result->fetch_array(MYSQLI_ASSOC);

                $result->free_result();
                $stmt->close();

                // test
                //$mySQLi->close();
                //print_r($row);exit;

                if (!empty($row) && $time - $row['time'] < $withdrawMinTime) {
                    $mySQLi->close();
                    $msg = '请等待 ' . ($time - $row['time']) . ' 秒后再试~';
                    returnJson(['code' => 1, 'msg' => $msg]);
                }

                /* 连接区服数据库 ---------------------------------------------------------------------------------------------------- */

                $dbActor = new mysqli($_CONFIG_DB['db_host'], $_CONFIG_DB['db_user'], $_CONFIG_DB['db_password'], 'mir_actor_s' . $serverId, $mir_actor_s1_port);
                if ($dbActor->connect_errno)
                    exit($dbActor->connect_error);
                $dbActor->set_charset($_CONFIG_DB['db_charset']);

                /* 检查提现货币数量是否足够 ---------------------------------------------------------------------------------------------------- */

                $stmt = $dbActor->prepare("select $currencyField from actors where actorid=?");
                $stmt->bind_param('i', $roleId);
                $stmt->execute();

                $result = $stmt->get_result();
                $row = $result->fetch_array(MYSQLI_ASSOC);

                $result->free_result();
                $stmt->close();

                if (empty($row)) {
                    $mySQLi->close();
                    $dbActor->close();
                    returnJson(['code' => 1, 'msg' => '找不到角色！']);
                }
                if ($row[$currencyField] < $amount) {
                    $mySQLi->close();
                    $dbActor->close();
                    returnJson(['code' => 1, 'msg' => "您帐户的" . $currencyName . "不足！\n\n查询可能有延迟，\n请稍候再试~"]);
                }

                /* 插入提现记录 ---------------------------------------------------------------------------------------------------- */

                $money = floor($amount / $_CONFIG['withdraw']['ratio']);
                $stmt = $mySQLi->prepare('insert into `withdraw` (account, account_id, server_id, role_id, pay_type, pay_account, amount, money, time) values(?, ?, ?, ?, ?, ?, ?, ?, ?)');
                if (!$stmt) {
                    $mySQLi->close();
                    $dbActor->close();
                    returnJson(['code' => 1, 'msg' => $mySQLi->errno . '-' . $mySQLi->error]);
                }
                $stmt->bind_param('siiiisiii', $account, $accountId, $serverId, $roleId, $payType, $payAccount, $amount, $money, $time);
                $stmt->execute();
                $wid = $stmt->insert_id;
                $stmt->close();

                if (empty($wid)) {
                    writeLog('提现扣除失败：' . $amount . $currencyName . '=' . $money . '元, s' . $serverId . ' ' . $roleName . '，插入失败');
                    $mySQLi->close();
                    $dbActor->close();
                    returnJson(['code' => 1, 'msg' => '提现记录插入失败！']);
                }

                /* 扣除提现货币 ---------------------------------------------------------------------------------------------------- */

                $cmdUrl = get_http_type() . $_CONFIG['host'] . ':111/?';
                $operid = 10030;
                $command = $roleName . '|' . $_CONFIG['withdraw']['type'] . '|' . $amount;
                $post_data = ['operid' => $operid, 'server_num' => $serverId, 'user' => $account, 'spid' => $_CONFIG['spid'], 'command' => $command];
                $url = $cmdUrl . http_build_query($post_data);
                $result = curl($url, $post_data);
                //echo $url;
                //print_r($result);exit;
                $arr = $result ? explode(',', $result) : [];
                $code = !empty($arr) && 1 == $arr[0] ? 0 : 1;
                if (1 == $code) {
                    writeLog('提现扣除失败：' . $amount . $currencyName . '=' . $money . '元, s' . $serverId . ' ' . $roleName);
                    $mySQLi->close();
                    $dbActor->close();
                    returnJson(['code' => 1, 'msg' => '提现请求失败！请稍候再试~', 'result' => $result]);
                }

                writeLog('提现成功：' . $amount . $currencyName . '=' . $money . '元, s' . $serverId . ' ' . $roleName);

                /* 更新提现状态 ---------------------------------------------------------------------------------------------------- */

                $withdrawStatus = 1; // 货币扣除成功，可以打钱
                $stmt = $mySQLi->prepare('UPDATE `withdraw` SET status = ? WHERE id = ?');
                $stmt->bind_param('si', $withdrawStatus, $wid);
                $stmt->execute();

                $stmt->close();
                $mySQLi->close();
                $dbActor->close();

                returnJson(['code' => 0, 'msg' => "成功提现：$amount$currencyName\n收益人民币：{$money}元\n\n请留意您的收款账户余额。"]);
                break;
            default:
            //
        }
        returnJson(['code' => 0]);
        break;
    case 'report': // 上报信息
        switch ($do) {
            case 'game_profile':
                //
                break;
            case 'chat': // 上报聊天
                if (!isPost())
                    returnJson(['code' => 1, 'msg' => 'request error']);

                $serverId = intval(substr(input('server_id'), 1));
                $account = input('account');
                $token = input('token');
                $roleId = intval(input('role_id'));
                $channelId = intval(input('channel_id'));
                $content = input('content');
                $cross = 1 == input('cross') ? 1 : 0;

                if (!$serverId || !$account || !$roleId || !$content)
                    returnJson(['code' => 1, 'msg' => 'param error']);
                if (26 < strlen($account))
                    returnJson(['code' => 1, 'msg' => 'param error']);
                if (!$token || 32 != strlen($token))
                    returnJson(['code' => 1, 'msg' => 'param error']);
                if (10 < $channelId)
                    returnJson(['code' => 1, 'msg' => 'param error']);
                if (255 < strlen($content))
                    returnJson(['code' => 1, 'msg' => 'param error']);

                // 检查帐号是否存在
                $mySQLi = new mysqli($_CONFIG_DB['db_host'], $_CONFIG_DB['db_user'], $_CONFIG_DB['db_password'], $_CONFIG_DB['db_name'], $_CONFIG_DB['db_port']);
                if ($mySQLi->connect_errno)
                    returnJson(['code' => 1, 'msg' => $mySQLi->connect_error]);
                $mySQLi->set_charset($_CONFIG_DB['db_charset']);

                $stmt = $mySQLi->prepare('select id from player where username=? and password=?');
                $stmt->bind_param('ss', $account, $token);
                $stmt->execute();

                $result = $stmt->get_result();
                $row = $result->fetch_array();

                $result->free_result();
                $stmt->close();

                if (empty($row)) {
                    $mySQLi->close();
                    returnJson(['code' => 1, 'msg' => 'account no exist']);
                }

                $time = time();
                $accountId = 0;

                // 插入聊天记录
                $stmt = $mySQLi->prepare('insert into `chat` (account, account_id, server_id, role_id, channel_id, content, is_cross, time) values(?, ?, ?, ?, ?, ?, ?, ?)');
                if (!$stmt) {
                    $mySQLi->close();
                    returnJson(['code' => 1, 'msg' => $mySQLi->errno . '-' . $mySQLi->error]);
                }
                $stmt->bind_param('siiisssi', $account, $accountId, $serverId, $roleId, $channelId, $content, $cross, $time);
                $stmt->execute();

                $stmt->close();
                $mySQLi->close();
                break;
            default:
            //
        }
        returnJson(['code' => 0]);
        break;
    case 'misc':
        switch ($do) {
            case 'agree':
                exit($_CONFIG['agree']);
                break;
        }
    case 'bind':
        $tpType = 'linuxdo';
        $mySQLi = new mysqli($_CONFIG_DB['db_host'], $_CONFIG_DB['db_user'], $_CONFIG_DB['db_password'], $_CONFIG_DB['db_name'], $_CONFIG_DB['db_port']);
        if ($mySQLi->connect_errno)
            returnJson(['code' => 1, 'msg' => $mySQLi->connect_error]);
        $mySQLi->set_charset($_CONFIG_DB['db_charset']);
        $stmt = $mySQLi->prepare('insert into `player_connect_threeparty` (username, type, connect_id) values(?, ?, ?)');
        $stmt->bind_param('sss', input('account'), $tpType, input('connect_id'));
        $stmt->execute();
        $stmt->close();
        $stmt = $mySQLi->prepare('select password from player where username=?');
        $stmt->bind_param('s', input('account'));
        $stmt->execute();
        $result = $stmt->get_result();
        $data = $result->fetch_array();
        $result->free_result();
        returnJson($data);
        $stmt->close();
        $mySQLi->close();
        break;
    case 'link':
        $connectId = input('connect_id');
        $tpType = 'linuxdo';
        $mySQLi = new mysqli($_CONFIG_DB['db_host'], $_CONFIG_DB['db_user'], $_CONFIG_DB['db_password'], $_CONFIG_DB['db_name'], $_CONFIG_DB['db_port']);
        if ($mySQLi->connect_errno)
            returnJson(['code' => 1, 'msg' => $mySQLi->connect_error]);
        $mySQLi->set_charset($_CONFIG_DB['db_charset']);
        $stmt = $mySQLi->prepare('select username from player_connect_threeparty where type=? and connect_id=? limit 1');
        $stmt->bind_param('ss', $tpType, $connectId);
        $stmt->execute();
        $result = $stmt->get_result();
        $row = $result->fetch_array();
        if (!empty($row)) {
            $getPlayer = $mySQLi->prepare('select username,password from player where username=? limit 1');
            $getPlayer->bind_param('s', $row['username']);
            $getPlayer->execute();
            $res = $getPlayer->get_result();
            $account = $res->fetch_array();
            returnJson(['code' => 0, 'data' => $account]);
            $res->free_result();
            $getPlayer->close();
        } else {
            returnJson(['code' => '1']);
        }
        $stmt->close();
        $mySQLi->close();
        break;
    default:
        echo 'success';
}
