<?php

namespace Sdk\Controller;

use Think\Controller;
use User\Api\MemberApi;
use Org\XiguSDK\Xigu;
use Org\UcenterSDK\Ucservice;
use Com\WechatAuth;
use App\Model\UserModel;
use App\Model\PointShopRecordModel;
use Qiniu\json_decode;
use Think\Log;

class UserController extends BaseController
{

    /**
     *SDK用户登录
     */
    public function user_login()
    {
        #获取SDK上POST方式传过来的数据 然后base64解密 然后将json字符串转化成数组
        $user = json_decode(base64_decode(file_get_contents("php://input")), true);
        #判断数据是否为空
        if (empty($user)) {

            $this -> set_message(1001, "fail", "登录数据不能为空");

        }

        /*是否开启Ucenter*/
        if (C('UC_OPEN') == 1) {
            $userApi = new MemberApi();
            $username = $user['account'];
            $password = $user['password'];
            //Ucenter登录
            list($uc_uid, $uc_username, $uc_password, $uc_email) = uc_user_login($username, $password);
            if ($uc_uid > 0) {
                //1.登录成功,验证在本地是否有此账号
                $user_res = M('user', 'tab_') -> where(['account' => $uc_username]) -> find();
                if (!empty($user_res)) {//本地存在账号,验证密码直接登录
                    $result = $userApi -> login_sdk($user["account"], $user['password'], 1, $user["game_id"], get_game_name($user["game_id"]), $user['sdk_version'],$user['unique_code']);#调用登录
                    $res_msg = array();
                    switch ($result) {
                        case - 1:
                            $this -> set_message(1004, "fail", "用户不存在或被禁用");
                            break;
                        case - 2:
                            $this -> set_message(1005, "fail", "密码错误");
                            break;
                        default:
                            if (is_array($result)) {
                                $user["user_id"] = $result['user_id'];
                                $this -> add_user_play($user);
                                $platform = $this -> get_platform($user['user_id']);
                                $small_list = $this -> small_list($user['user_id'], $user['game_id']);
                                $small_list[] = array('is_platform' => $platform, 'user_id' => $user['user_id'], 'account' => $user['account'], 'user_account' => $user['account']);
                                $unread_count = 0;
                                $unread_count += M('share_record', 'tab_') -> where(['invite_id' => $user['user_id'], 'award_coin' => ['gt', 0], 'read' => 0]) -> count();
                                $unread_count += M('point_record', 'tab_') -> where(['type_id' => 6, 'user_id' => $user['user_id'], 'point' => ['gt', 0], 'read' => 0]) -> count();
                                $notice_count = $unread_count;
                                $buddies_request = get_buddies_unagree_count($user['user_id']);
                                $unread_count += $buddies_request;
                                M('nearby', 'tab_') -> where(['user_id' => $user['user_id']]) -> setField(['game_status' => 1, 'update_time' => time(), 'user_nickname' => $user_res['nickname'], 'head_img' => $user_res['head_img']]);
                                $res_msg = array(
                                        "status" => 200,
                                        "return_code" => "success",
                                        "return_msg" => "登录成功",
                                        "user_id" => $user["user_id"],
                                        "account" => $user["account"],
                                        "nickname" => $user_res["nickname"] ? $user_res["nickname"] : $user["account"],
                                        "sex" => $user_res['sex'] ?: 0,
                                        "token" => $result['token'],
                                        "OTP_token" => think_encrypt(json_encode(array('uid' => $user["user_id"], 'time' => time())), 1),
                                        'is_uc' => 0,
                                        "is_open_small_account" => C('IS_OPEN_SMALL_ACCOUNT'),
                                        'url' => 'http://' . str_replace(array('http://'), '', C('WEB_SITE')) . '/mobile.php',
                                        'small_list' => $small_list,
                                        'ios_packagename' => C('WEB_IOS_PACKAGENAME'),
                                        'android_packagename' => C('WEB_AND_PACKAGENAME'),
                                        'site_status' => C('SDK_SITE_STATUS'),
                                        'head_img' => !empty($user_res['head_img']) ? $user_res['head_img'] : '',
                                        'unread_count' => $unread_count,
                                        'request_count' => $buddies_request,
                                        'notice_count' => $notice_count,
                                );
                            } else {
                                $this -> set_message(1028, "fail", "未知错误");
                            }
                            break;
                    }
                    echo base64_encode(json_encode($res_msg));
                    die;

                } else {//本地不存在账号,新增账号并登录
                    $resdata = array();
                    $resdata['account'] = trim($username);
                    $resdata['nickname'] = trim($username);
                    $resdata['password'] = $password;
                    $resdata['register_way'] = 1;
                    $resdata['register_type'] = 1;
                    $resdata['promote_id'] = 0;
                    $resdata['promote_account'] = 'UC用户';
                    $resdata['parent_id'] = 0;
                    $resdata['parent_name'] = '';
                    $resdata['phone'] = '';
                    $resdata['real_name'] = '';
                    $resdata['idcard'] = '';
                    $resdata['sex'] = 0;
                    $res = $userApi -> sdk_register($resdata);
                    if ($res > 0) {


                        $result = $userApi -> login_sdk($user["account"], $user['password'], 1, $user["game_id"], get_game_name($user["game_id"]), $user['sdk_version'],$user['unique_code']);#调用登录
                        $res_msg = array();
                        switch ($result) {
                            case - 1:
                                $this -> set_message(1004, "fail", "用户不存在或被禁用");
                                break;
                            case - 2:
                                $this -> set_message(1005, "fail", "密码错误");
                                break;
                            default:
                                if (is_array($result)) {
                                    $user["user_id"] = $result['user_id'];
                                    $this -> add_user_play($user);
                                    $platform = $this -> get_platform($user['user_id']);
                                    $small_list = $this -> small_list($user['user_id'], $user['game_id']);
                                    $small_list[] = array('is_platform' => $platform, 'user_id' => $user['user_id'], 'account' => $user['account'], 'user_account' => $user['account']);
                                    $unread_count = 0;
                                    $unread_count += M('share_record', 'tab_') -> where(['invite_id' => $user['user_id'], 'award_coin' => ['gt', 0], 'read' => 0]) -> count();
                                    $unread_count += M('point_record', 'tab_') -> where(['type_id' => 6, 'user_id' => $user['user_id'], 'point' => ['gt', 0], 'read' => 0]) -> count();
                                    $notice_count = $unread_count;
                                    $buddies_request = get_buddies_unagree_count($user['user_id']);
                                    $unread_count += $buddies_request;
                                    M('nearby', 'tab_') -> where(['user_id' => $user['user_id']]) -> setField(['game_status' => 1, 'update_time' => time(), 'user_nickname' => $resdata['account']]);
                                    $res_msg = array(
                                            "status" => 200,
                                            "return_code" => "success",
                                            "return_msg" => "登录成功",
                                            "user_id" => $user["user_id"],
                                            "account" => $user["account"],
                                            "nickname" => $resdata["nickname"] ? $resdata["nickname"] : $user["account"],
                                            "token" => $result['token'],
                                            "sex" => 0,
                                            "OTP_token" => think_encrypt(json_encode(array('uid' => $user["user_id"], 'time' => time())), 1),
                                            'is_uc' => 0,
                                            "is_open_small_account" => C('IS_OPEN_SMALL_ACCOUNT'),
                                            'url' => 'http://' . str_replace(array('http://'), '', C('WEB_SITE')) . '/mobile.php',
                                            'small_list' => $small_list,
                                            'ios_packagename' => C('WEB_IOS_PACKAGENAME'),
                                            'android_packagename' => C('WEB_AND_PACKAGENAME'),
                                            'site_status' => C('SDK_SITE_STATUS'),
                                            'head_img' => '',
                                            'unread_count' => $unread_count,
                                            'notice_count' => $notice_count,
                                            'request_count' => $buddies_request,
                                    );
                                } else {
                                    $this -> set_message(1028, "fail", "未知错误");
                                }
                                break;
                        }
                        echo base64_encode(json_encode($res_msg));
                        die;

                    } else {
                        $this -> set_message(1004, "账号已存在");
                    }

                }

            } elseif ($uc_uid == - 1) {
                //用户不存在,验证本地用户账号密码
                $result = $userApi -> login_sdk($user["account"], $user['password'], 1, $user["game_id"], get_game_name($user["game_id"]), $user['sdk_version'],$user['unique_code']);#调用登录
                $res_msg = array();
                switch ($result) {
                    case - 1:
                        $this -> set_message(1004, "fail", "用户不存在或被禁用");
                        break;
                    case - 2:
                        $this -> set_message(1005, "fail", "密码错误");
                        break;
                    default:
                        if (is_array($result)) {
                            $user["user_id"] = $result['user_id'];
                            $this -> add_user_play($user);
                            $user_res = M('User', 'tab_') -> where(['account' => $user['account']]) -> find();
                            $unread_count = 0;
                            $unread_count += M('share_record', 'tab_') -> where(['invite_id' => $user['user_id'], 'award_coin' => ['gt', 0], 'read' => 0]) -> count();
                            $unread_count += M('point_record', 'tab_') -> where(['type_id' => 6, 'user_id' => $user['user_id'], 'point' => ['gt', 0], 'read' => 0]) -> count();
                            $notice_count = $unread_count;
                            $buddies_request = get_buddies_unagree_count($user['user_id']);
                            $unread_count += $buddies_request;
                            M('nearby', 'tab_') -> where(['user_id' => $user['user_id']]) -> setField(['game_status' => 1, 'update_time' => time(), 'user_nickname' => $user_res['nickname'], 'head_img' => $user_res['head_img']]);
                            $res_msg = array(
                                    "status" => 200,
                                    "return_code" => "success",
                                    "return_msg" => "登录成功",
                                    "user_id" => $user["user_id"],
                                    "account" => $user["account"],
                                    "nickname" => $user_res["nickname"] ? $user_res["nickname"] : $user["account"],
                                    "sex" => $user_res["sex"] ? $user_res["sex"] : 0,
                                    "token" => $result['token'],
                                    "OTP_token" => think_encrypt(json_encode(array('uid' => $user["user_id"], 'time' => time())), 1),
                                    'is_uc' => 0,
                                    "is_open_small_account" => C('IS_OPEN_SMALL_ACCOUNT'),
                                    'url' => 'http://' . str_replace(array('http://'), '', C('WEB_SITE')) . '/mobile.php',
                                    'small_list' => $small_list,
                                    'ios_packagename' => C('WEB_IOS_PACKAGENAME'),
                                    'android_packagename' => C('WEB_AND_PACKAGENAME'),
                                    'site_status' => C('SDK_SITE_STATUS'),
                                    'head_img' => !empty($user_res['head_img']) ? $user_res['head_img'] : '',
                                    'unread_count' => $unread_count,
                                    'notice_count' => $notice_count,
                                    'request_count' => $buddies_request,
                            );
                        } else {
                            $this -> set_message(1028, "fail", "未知错误");
                        }
                        break;
                }
                //同步ucenter注册
                cus_uc_register($username, $password, $username . '@vlcms.com');
                echo base64_encode(json_encode($res_msg));
                die;


            } elseif ($uc_uid == - 2) {
                //密码错误
                $this -> set_message(1005, "fail", "密码错误");
            } else {
                //登录失败
            }
        }
        #实例化用户接口
        $userApi = new MemberApi();
        $result = $userApi -> login_sdk($user["account"], $user['password'], 1, $user["game_id"], get_game_name($user["game_id"]), $user['sdk_version'],$user['unique_code']);#调用登录
        $res_msg = array();
        switch ($result) {

            case - 1:
                $this -> set_message(1004, "fail", "用户不存在或被禁用");
                break;
            case - 2:
                $this -> set_message(1005, "fail", "密码错误");
                break;
            default:
                if (is_array($result)) {

                    $user["user_id"] = $result['user_id'];
                    $user['puid'] = 0;
                    $this -> add_user_play($user);
                    $platform = $this -> get_platform($user['user_id']);
                    $small_list = $this -> small_list($user['user_id'], $user['game_id']);
                    $small_list[] = array('is_platform' => $platform, 'user_id' => $user['user_id'], 'account' => $user['account'], 'user_account' => $user['account']);
                    $user_res = M('User', 'tab_') -> where(['account' => $user['account']]) -> find();
                    $unread_count = 0;
                    $unread_count += M('share_record', 'tab_') -> where(['invite_id' => $user['user_id'], 'award_coin' => ['gt', 0], 'read' => 0]) -> count();
                    $unread_count += M('point_record', 'tab_') -> where(['type_id' => 6, 'user_id' => $user['user_id'], 'point' => ['gt', 0], 'read' => 0]) -> count();
                    $notice_count = $unread_count;
                    $buddies_request = get_buddies_unagree_count($user['user_id']);
                    $unread_count += $buddies_request;
                    M('nearby', 'tab_') -> where(['user_id' => $user['user_id']]) -> setField(['game_status' => 1, 'update_time' => time(), 'user_nickname' => $user_res['nickname'], 'head_img' => $user_res['head_img']]);
                    $res_msg = array(
                            "status" => 200,
                            "return_code" => "success",
                            "return_msg" => "登录成功",
                            "user_id" => $user["user_id"],
                            "account" => $user["account"],
                            "nickname" => $user_res["nickname"] ? $user_res["nickname"] : $user["account"],
                            "sex" => $user_res["sex"] ? $user_res["sex"] : 0,
                            "is_platform" => $platform,
                            "token" => $result['token'],
                            "OTP_token" => think_encrypt(json_encode(array('uid' => $user["user_id"], 'time' => time())), 1),
                            'is_uc' => 0,
                            "is_open_small_account" => C('IS_OPEN_SMALL_ACCOUNT'),
                            'url' => 'http://' . str_replace(array('http://'), '', C('WEB_SITE')) . '/mobile.php',
                            'small_list' => $small_list,
                            'ios_packagename' => C('WEB_IOS_PACKAGENAME'),
                            'android_packagename' => C('WEB_AND_PACKAGENAME'),
                            'site_status' => C('SDK_SITE_STATUS'),
                            'head_img' => !empty($user_res['head_img']) ? $user_res['head_img'] : '',
                            'unread_count' => $unread_count,
                            'notice_count' => $notice_count,
                            'request_count' => $buddies_request,
                    );

                } else {

                    $this -> set_message(1028, "fail", "未知错误");

                }
                break;

        }
        echo base64_encode(json_encode($res_msg));


    }


    /**
     * 第三方登录
     */
    public function oauth_login()
    {

        $request = json_decode(base64_decode(file_get_contents("php://input")), true);
        if (empty($request)) {

            $this -> set_message(1001, "fail", "登录数据不能为空");

        }
        $openid = $request['openid'];
        if ($request['login_type'] == "wx") {

            $param_set = get_game_wxlogin_param($request['game_id']);
            if (empty($param_set['wx_appid'])) {

                $result['status'] = 1083;
                $result['message'] = '微信登录appid/appsecret为空';
                echo base64_encode(json_encode($result));
                exit;


            }
            Vendor("WxPayPubHelper.WxPayPubHelper");
            // 使用jsapi接口
            $jsApi = new \JsApi_pub();
            $wx = $jsApi -> create_openid($param_set['wx_appid'], $param_set['appsecret'], $request['code']);
            //unionid如果开发者有在多个公众号,或在公众号、移动应用之间统一用户帐号的需求,需要前往微信开放平台(open.weixin.qq.com)绑定公众号后,才可利用UnionID机制来满足上述需
            if (empty($wx['unionid'])) {

                echo base64_encode(json_encode(array("status" => 1071, "message" => "请到微信开放平台(open.weixin.qq.com)绑定公众号")));
                exit();

            }
            $openid = $wx['unionid'];
            $wx_param_set = get_game_wxlogin_param($request['game_id']);
            $auth = new WechatAuth($wx_param_set['wx_appid'], $wx_param_set['appsecret'], $wx['access_token']);
            $userInfo = $auth -> getUserInfo($wx['openid']);
            $register_type = 3;
            $head_img = $userInfo['headimgurl'];

        } elseif ($request['login_type'] == "bd") {

            if (empty($request['accessToken'])) {

                $res['status'] = - 1;
                $res['message'] = '用户不存在或被禁用';
                echo base64_encode(json_encode($res));
                exit();

            }
            $url = "https://openapi.baidu.com/rest/2.0/passport/users/getLoggedInUser?access_token=" . $request['accessToken'];
            $baidu_url = json_decode(file_get_contents($url), true);
            $register_type = 5;
            $openid = $baidu_url['uid'];
            $head_img = "http://tb.himg.baidu.com/sys/portrait/item/" . $baidu_url['portrait'];

        } elseif ($request['login_type'] == "qq") {

            $register_type = 4;
            $qq_parm['access_token'] = $request['accessToken'];
            $qq_parm['oauth_consumer_key'] = C('qq_login.appid');
            $qq_parm['openid'] = C('qq_login.key');
            $qq_parm['format'] = "json";
            $openid = get_union_id($request['accessToken']);
            if (empty($openid)) {

                $res['status'] = - 1;
                $res['message'] = '腾讯公司应用未打通 未将所有appid设置统一unionID';
                echo base64_encode(json_encode($res));
                exit();

            }
            $url = "https://graph.qq.com/user/get_user_info?" . http_build_query($qq_parm);
            $qq_url = json_decode(file_get_contents($url), true);
            $head_img = $qq_url['figureurl_qq_1 '];

        } elseif ($request['login_type'] == "wb") {

            $register_type = 6;
            $head_img = $request['head_img '];

        } elseif ($request['login_type'] == "yk") {

            $register_type = 0;
            $head_img = "http://" . $_SERVER['HTTP_HOST'] . '/Public/Sdk/logoo.png';

        } elseif ($request['login_type'] == "fb") {

            $register_type = 7;

        } elseif ($request['login_type'] == "gg") {

            $register_type = 8;

        }
        $map['openid'] = $openid;
        if ($request['login_type'] == "yk" && isset($request['account'])) {

            unset($map['openid']);
            $map['account'] = $request["account"];
            $map['register_type'] = 0;

        } elseif ($request['login_type'] == "yk") {

            $map['id'] = - 1;

        }
        $data = M('user', 'tab_') -> where($map) -> find();
        if (empty($data)) {//注册
            do {
                $data['account'] = $request['login_type'] . '_' . sp_random_string();
                $account = M('user', 'tab_') -> where(['account' => $data['account']]) -> find();

            } while (!empty($account));
            $data['password'] = sp_random_string(8);
            $data['nickname'] = $data['account'];
            $data['openid'] = $openid;
            $data['game_id'] = $request['game_id'];
            $data['head_img'] = !empty($head_img) ? $head_img : '';//头像
            $data['game_name'] = get_game_name($request['game_id']);
            $data['promote_id'] = $request['promote_id'];
            $data['promote_account'] = get_promote_name($request['promote_id']);
            $data['register_way'] = 1;
            $data['register_type'] = $register_type;
            $data['sdk_version'] = $request['sdk_version'];
            $data['game_appid'] = $request['game_appid'];
            $data['device_type'] = $request['device_type'];
            $data['unique_code'] = $request['unique_code'];
            $userApi = new MemberApi();
            $uid = $userApi -> tr_register($data);
            if ($uid < 0) {

                $res['status'] = 1023;
                $res['message'] = '注册失败';
                echo base64_encode(json_encode($res));
                exit;

            }

        }
        //登录
        $userApi = new MemberApi();
        $result = $userApi -> login_sdk($data["account"], $data['account'], 1, $request["game_id"], get_game_name($request['game_id']), $request['sdk_version']);
        if ($result == - 1) {

            $res['status'] = 1004;
            $res['message'] = '用户不存在或被禁用';

        } else {

            $request["user_id"] = $result['user_id'];
            $request['puid'] = 0;
            $this -> add_user_play($request);
            $platform = $this -> get_platform($request['user_id']);
            $small_list = $this -> small_list($result['user_id'], $request['game_id']);
            $small_list[] = array('is_platform' => $platform, 'user_id' => $result['user_id'], 'account' => $data['account'], 'user_account' => $data['account']);
            $user_res = M('User', 'tab_') -> where(['account' => $data['account']]) -> find();
            $unread_count = 0;
            $unread_count += M('share_record', 'tab_') -> where(['invite_id' => $result['user_id'], 'award_coin' => ['gt', 0], 'read' => 0]) -> count();
            $unread_count += M('point_record', 'tab_') -> where(['type_id' => 6, 'user_id' => $result['user_id'], 'point' => ['gt', 0], 'read' => 0]) -> count();
            $notice_count = $unread_count;
            $buddies_request = get_buddies_unagree_count($result['user_id']);
            $unread_count += $buddies_request;
            M('nearby', 'tab_') -> where(['user_id' => $result['user_id']]) -> setField(['game_status' => 1, 'update_time' => time(), 'user_nickname' => $user_res['nickname'], 'head_img' => $user_res['head_img']]);
            $res['status'] = 200;
            $res['message'] = '登录成功';
            $res['user_id'] = $result['user_id'];
            $res['account'] = $data['account'];
            $res['token'] = $result['token'];
            $res['password'] = $data['account'];
            $res['nickname'] = $data['nickname'] ? $data['nickname'] : $data['account'];
            $res['sex'] = $user_res['sex'] ? $user_res['sex'] : 0;
            $res['small_list'] = $small_list;
            $res['is_platform'] = $platform;
            $res["is_open_small_account"] = C('IS_OPEN_SMALL_ACCOUNT');
            $res['url'] = 'http://' . str_replace(array('http://'), '', C('WEB_SITE')) . '/mobile.php';
            $res['ios_packagename'] = C('WEB_IOS_PACKAGENAME');
            $res['android_packagename'] = C('WEB_AND_PACKAGENAME');
            $res['site_status'] = C('SDK_SITE_STATUS');
            $res['head_img'] = !empty($user_res['head_img']) ? $user_res['head_img'] : '';
            $res['unread_count'] = $unread_count;
            $res['notice_count'] = $notice_count;
            $res['request_count'] = $buddies_request;

        }
//        echo M('user','tab_')->getLastSql();die;
        echo base64_encode(json_encode($res));

    }




    /**
     *第三方登录设置
     */
    public function thirdparty()
    {

        $request = json_decode(base64_decode(file_get_contents("php://input")), true);
        if (empty($request)) {

            $this -> set_message(1001, "fail", "登录数据不能为空");

        }
        $map['game_id'] = $request['game_id'];
        $select = M('param', 'tab_') -> field('type,status') -> where($map) -> select();
        if (!empty($select)) {

            foreach ($select as $key => $val) {

                if ($val['type'] == 1 && $val['status'] == 1) {

                    $data['config'] .= 'qq|';

                }
                if ($val['type'] == 2 && $val['status'] == 1) {

                    $data['config'] .= 'wx|';

                }
                if ($val['type'] == 3 && $val['status'] == 1) {

                    $data['config'] .= 'wb|';

                }
                if ($val['type'] == 4 && $val['status'] == 1) {

                    $data['config'] .= 'bd|';

                }

            }

        } else {

            $data['config'] = '';

        }
        echo base64_encode(json_encode($data));
        // $str = "qq_login,weixin_login,sina_login,baidu_login,fb_login,gg_login";
        // $this->BaseConfig($str);
    }


    /**
     *显示扩展设置信息
     */
    protected function BaseConfig($name = '')
    {

        $map['name'] = array('in', $name);
        $map['status'] = 1;
        $tool = M('tool', "tab_") -> where($map) -> select();
        $data['config'] = '';
        if (!empty($tool)) {

            foreach ($tool as $key => $val) {

                if ($val['name'] == 'qq_login') {

                    $data['config'] .= 'qq|';

                }
                if ($val['name'] == 'weixin_login') {

                    $data['config'] .= 'wx|';

                }
                if ($val['name'] == 'sina_login') {

                    $data['config'] .= 'wb|';

                }
                if ($val['name'] == 'baidu_login') {

                    $data['config'] .= 'bd|';

                }
                if ($val['name'] == 'fb_login') {

                    $data['config'] .= 'fb|';

                }
                if ($val['name'] == 'gg_login') {

                    $data['config'] .= 'gg|';

                }

            }

        }
        if ($data['config'] != '') {

            $data['config'] = substr($data['config'], 0, strlen($data['config']) - 1);

        }
        echo base64_encode(json_encode($data));

    }


    /**
     * 第三方登录参数请求
     */
    public function oauth_param()
    {

        $request = json_decode(base64_decode(file_get_contents("php://input")), true);
        $type = $request['login_type'];
        switch ($type) {

            case 'qq':
                $param_set = get_game_param($request['game_id'], '', 1);
                $param['qqappid'] = $param_set['openid'];
                break;
            case 'wx':
                $param_set = get_game_param($request['game_id'], '', 2);
                $param['weixinappid'] = $param_set['wx_appid'];
                break;
            case 'wb':
                $param_set = get_game_param($request['game_id'], '', 3);
                $param['weiboappkey'] = $param_set['appkey'];
                break;
            case 'bd':
                $param_set = get_game_param($request['game_id'], '', 4);
                $param['clientid'] = $param_set['clientid'];
                break;
            case 'fb':
                $param_set = get_game_param($request['game_id']);
                $param['appid'] = C('fb_login.appid');
                break;
            case 'gg':
                $param_set = get_game_param($request['game_id']);
                $param['clientid'] = C('gg_login.clientid');
                $param['clientsecert'] = C('gg_login.clientsecert');
                break;

        }
        if (empty($param)) {

            $result['status'] = 1090;
            $result['message'] = '服务器未配置此参数';

        } else {

            $result['status'] = 200;
            $result['message'] = '请求成功';
            $result['param'] = $param;

        }
        echo base64_encode(json_encode($result));

    }


    public function user_register()
    {

        C(api('Config/lists'));
        #获取SDK上POST方式传过来的数据 然后base64解密 然后将json字符串转化成数组
        $user = json_decode(base64_decode(file_get_contents("php://input")), true);
        #判断数据是否为空
        if (empty($user)) {
            $this -> set_message(1001, "fail", "注册数据不能为空");
        }
        Log::write('user_register:' . date('Y-m-d H:i:s') . ' ---- ' . json_encode($user), 'INFO');
        /**是否开启ucenter**/
        if (C('UC_OPEN') == 1) {
            //Ucenter注册
            //1.验证本平台是否存在账号
            $is_user_info = M('user', 'tab_') -> where(['account' => $user['account']]) -> find();
            if (!empty($is_user_info)) {
                $this -> set_message(1017, "fail", "用户名已存在");
            }
            //2.验证其他平台是否存在账号
            $domain = C('UC_OTHER_WEB_URL');
            if (!empty($domain)) {
                $url = "http://{$domain}/Api/user/checkUserName?account={$user['account']}";
                $check_res = json_decode(file_get_contents($url), true);
                if ($check_res['status'] == 0) {
                    $this -> set_message(1017, "fail", "用户名已存在");
                }
            }
            //3.ucenter注册账号
            $ucresult = uc_user_checkname($user['account']);
            if ($ucresult == - 1) {
                $this -> set_message(0, "fail", "用户名不合法");
            } elseif ($ucresult == - 2) {
                $this -> set_message(0, "fail", "包含要允许注册的词语");
            } elseif ($ucresult == - 3) {
                $this -> set_message(1017, "fail", "用户名已存在");
            } else {
                //同步ucenter注册
                cus_uc_register($user['account'], $user['password'], $user['account'] . '@vlcms.com');
            }
        }
        $this -> reg_data($user);


    }


    /**
     * 邮箱注册
     */
    public function user_email_register()
    {

        C(api('Config/lists'));
        #获取SDK上POST方式传过来的数据 然后base64解密 然后将json字符串转化成数组
        $user = json_decode(base64_decode(file_get_contents("php://input")), true);
        if (empty($user)) {
            $this -> set_message(1001, "fail", "注册数据不能为空");

        }
        Log::write('user_email_register:' . date('Y-m-d H:i:s') . ' ---- ' . json_encode($user), 'INFO');
        $v_res = $this -> verify_email_code($user['account'], $user['code']);
        if ($v_res) {

            $this -> reg_data($user, 3);

        }

    }


    /**
     *手机用户注册
     */
    public function user_phone_register()
    {

        C(api('Config/lists'));
        #获取SDK上POST方式传过来的数据 然后base64解密 然后将json字符串转化成数组
        $user = json_decode(base64_decode(file_get_contents("php://input")), true);
        #判断数据是否为空
        if (empty($user)) {
            $this -> set_message(1001, "fail", "注册数据不能为空");
        }
        Log::write('user_phone_register:' . date('Y-m-d H:i:s') . ' ---- ' . json_encode($user), 'INFO');
        #验证短信验证码
        $this -> sms_verify($user['account'], $user['code']);
        /**是否开启ucenter**/
        if (C('UC_OPEN') == 1) {
            //Ucenter注册
            //1.验证本平台是否存在账号
            $is_user_info = M('user', 'tab_') -> where(['account' => $user['account']]) -> find();
            if (!empty($is_user_info)) {
                $this -> set_message(1017, "fail", "用户名已存在");
            }
            //2.验证其他平台是否存在账号
            $domain = C('UC_OTHER_WEB_URL');
            if (!empty($domain)) {
                $url = "http://{$domain}/Api/user/checkUserName?account={$user['account']}";
                $check_res = json_decode(file_get_contents($url), true);
                if ($check_res['status'] == 0) {
                    $this -> set_message(1017, "fail", "用户名已存在");
                }
            }
            //3.ucenter注册账号
            $ucresult = uc_user_checkname($user['account']);
            if ($ucresult == - 1) {
                $this -> set_message(0, "fail", "用户名不合法");
            } elseif ($ucresult == - 2) {
                $this -> set_message(0, "fail", "包含要允许注册的词语");
            } elseif ($ucresult == - 3) {
                $this -> set_message(1017, "fail", "用户名已存在");
            } else {
                //同步ucenter注册
                cus_uc_register($user['account'], $user['password'], $user['account'] . '@vlcms.com');
            }
        }
        $this -> reg_data($user, 2);


    }


    //注册信息
    private function reg_data($user, $type = 1)
    {

        #实例化用户接口
        $userApi = new MemberApi();
        // user表加game_id
        if ($type == 2) {//手机2
            $result = $userApi -> sdk_register_($user['account'], $user['password'], 1, 2, $user['promote_id'], get_promote_name($user['promote_id']), $user['account'], $user["game_id"], get_game_name($user["game_id"]), $user['sdk_version'] ,$user['device_type'],$user['unique_code']);

        } elseif ($type == 3) {//邮箱3
            $result = $userApi -> sdk_register_($user['account'], $user['password'], 1, 7, $user['promote_id'], get_promote_name($user['promote_id']), '', $user["game_id"], get_game_name($user["game_id"]), $user['sdk_version'] ,$user['device_type'],$user['unique_code']);

        } else {//用户1
            $result = $userApi -> sdk_register_($user['account'], $user['password'], 1, 1, $user['promote_id'], get_promote_name($user['promote_id']), $phone = "", $user["game_id"], get_game_name($user["game_id"]), $user['sdk_version'] ,$user['device_type'],$user['unique_code']);


        }
        $res_msg = array();
        if ($result > 0) {

            $this -> set_message(200, "success", "注册成功");

        } else {

            switch ($result) {

                case - 3:
                    $this -> set_message(1017, "fail", "用户名已存在");
                    break;
                default:
                    $this -> set_message(1027, "fail", "注册失败");
                    break;

            }

        }

    }

    /**
     * @函数或方法说明
     * @获取禁用状态
     * @author: 郭家屯
     * @since: 2019/5/7 14:29
     */
    public function get_lock_status(){
        $request = json_decode(base64_decode(file_get_contents("php://input")), true);
        $user = get_user_entity($request['user_id']);
        if($user['lock_status'] == 0 || $user['check_status'] == 0){
            $this->set_message(0,"fail","账号被禁用,无法充值,请联系客服!2");
        }
        $game = M('Game','tab_')->where(['id'=>$request['game_id']])->field('pay_status')->find();
        if($game['pay_status'] == 0){
            $this->set_message(0,"fail","该游戏暂时无法充值,请联系客服!");
        }
        $this->set_message(200,"success","账号状态正常");
    }

    /**
     *修改用户数据
     */
    public function user_update_data()
    {

        $user = json_decode(base64_decode(file_get_contents("php://input")), true);
        C(api('Config/lists'));
        #判断数据是否为空
        if (empty($user)) {

            $this -> new_set_message(1001, "操作数据不能为空");

        }
        #实例化用户接口
        $data['id'] = $user['user_id'];
        $userApi = new MemberApi();
        switch ($user['code']) {

            case 'phone':
                //对于手机号 加上是否重复的验证过程 和 是否预计绑定的验证过程
                $where['id'] = $data['id'];
                $getphone = M('User', 'tab_') -> where($where) -> getField('phone');
                if (!empty($getphone)) {
                    $this -> new_set_message(1125, '该用户已经绑定过手机号,请解绑后再来');
                }
                $tt['phone'] = $user['phone'];
                $getuser = M('User', 'tab_') -> where($tt) -> field('id') -> find();
                if ($getuser) {
                    $this -> new_set_message(1098, '该手机号已被绑定');
                }
                #验证短信验证码
                $this -> sms_verify2($user['phone'], $user['sms_code']);
                $data['phone'] = $user['phone'];
                break;
            case 'nickname':
                $nk = M('User', 'tab_') -> field('id,account,nickname') -> where(['nickname' => $user['nickname']]) -> find();
                if (!empty($nk) && is_array($nk) && $user['user_id'] != $nk['id']) {
                    $this -> new_set_message(1012, "昵称已被使用");
                }
                $data['nickname'] = $user['nickname'];
                break;
            case 'pwd':
                if ($user['old_password'] == $user['password']) {
                    $this -> new_set_message(1126, '新密码与原始密码不能相同');
                }
                $data['old_password'] = $user['old_password'];
                $data['password'] = $user['password'];
                /*判断Ucenter是否打开*/
                if (C('UC_OPEN') == 1) {

                    $username = $user['account'];
                    $opwd = $user['old_password'];
                    $pwd = $user['password'];
                    //修改uc密码
                    $ucresult = uc_user_edit($username, $opwd, $pwd);
                    if ($ucresult == - 1) {
                        $this -> new_set_message(1006, "旧密码输入不正确");
                    }
                    /**
                     * 同步修改其他站点用户密码
                     */
                    $domain = C('UC_OTHER_WEB_URL');
                    if (!empty($domain)) {
                        $url = "http://{$domain}/Api/user/editPassword?account={$username}&oldpsw={$opwd}&newpsw={$pwd}";
                        $aa = json_decode(file_get_contents($url), true);
                    }
                }
                break;
            case 'account':
                if (!preg_match("/^[a-z\d]{6,15}$/i", $user['account'])) {
                    $this -> new_set_message(1025, "用户名为6-15位的数字和字母的组合");
                }
                $data['account'] = $user['account'];
                $data['password'] = $user['password'];
                $data['register_type'] = 1;  //游客改为账号注册
                $map['account'] = $user['account'];
                $res = M('user', 'tab_') -> where($map) -> find();
                if ($res) {

                    $this -> new_set_message(1017, "已存在该用户名");

                }
                $result = $this -> updata_user_youke($data);
                break;
            default:
                $this -> new_set_message(1074, "修改信息不明确");
                break;

        }
        $result = $userApi -> updateUser($data);
        if ($result == - 2) {

            $this -> new_set_message(1006, "旧密码输入不正确");

        } else if ($result !== false) {

            if ($user['code'] == 'pwd') {

                $u_uid['uid'] = $user['user_id'];
                M('user_pwd') -> where($u_uid) -> setField('password', think_encrypt($data['password']));

            }
            $user_res = M('User', 'tab_') -> where(['id' => $user['user_id']]) -> find();
            $data = ['user_account' => $user_res['nickname'], 'update_time' => time(), 'head_img' => $user_res['head_img']];
            M('nearby', 'tab_') -> where(['user_id' => $user['user_id']]) -> save($data);
            $this -> new_set_message(200, "修改成功");

        } else {

            $this -> new_set_message(1012, "修改失败");

        }

    }


    //游客改名,对应修改数据
    private function updata_user_youke($data)
    {

        $map['user_id'] = $data['id'];
        $data1['user_account'] = $data['account'];
        $res = M('user_play_info', 'tab_') -> where($map) -> setField($data1);
        $res1 = M('user_play', 'tab_') -> where($map) -> setField($data1);
        $res2 = M('user_login_record', 'tab_') -> where($map) -> setField($data1);
        $res3 = M('spend', 'tab_') -> where($map) -> setField($data1);
        $res4 = M('provide', 'tab_') -> where($map) -> setField($data1);
        $res5 = M('mend', 'tab_') -> where($map) -> setField($data1);
        $res6 = M('gift_record', 'tab_') -> where($map) -> setField($data1);
        $res7 = M('deposit', 'tab_') -> where($map) -> setField($data1);
        $res8 = M('bind_spend', 'tab_') -> where($map) -> setField($data1);
        $res9 = M('balance_edit', 'tab_') -> where($map) -> setField($data1);
        $res10 = M('agent', 'tab_') -> where($map) -> setField($data1);
        $res11 = M('nearby', 'tab_') -> where($map) -> setField($data1);

    }


    //验证验证码
    public function verify_sms()
    {

        $user = json_decode(base64_decode(file_get_contents("php://input")), true);
        if (empty($user)) {

            $this -> set_message(1001, "fail", "操作数据不能为空");

        }
        $this -> sms_verify($user['phone'], $user['code'], 1);

    }

    //sdk验证邮箱
    public function verify_email()
    {

        $user = json_decode(base64_decode(file_get_contents("php://input")), true);
        if (empty($user)) {

            $this -> set_message(1001, "fail", "操作数据不能为空");

        }
        $code_result = $this -> emailVerify($user['email'], $user['code']);
        if ($code_result == 1) {

            $this -> set_message(200, "success", "验证成功");

        } else {

            if ($code_result == 2) {

                $this -> set_message(1020, "fail", "请先获取验证码");

            } elseif ($code_result == - 98) {

                $this -> set_message(1021, "fail", "验证码超时");

            } elseif ($code_result == - 97) {

                $this -> set_message(1022, "fail", "验证码不正确,请重新输入");

            }

        }

    }


    /**
     *忘记密码接口
     */
    public function forget_password()
    {

        $user = json_decode(base64_decode(file_get_contents("php://input")), true);
        $userApi = new MemberApi();
        #验证短信验证码
        if ($user['code_type'] != 2) {
            $this -> sms_verify($user['phone'], $user['code']);
        }
        $result = $userApi -> updatePassword($user['user_id'], $user['password']);
        if ($result == true) {

            $this -> set_message(200, "success", "修改成功");

        } else {

            $this -> set_message(1012, "fail", "修改失败");

        }

    }


    /**
     *添加玩家信息
     */
    private function add_user_play($user = array())
    {

        $user_play = M("UserPlay", "tab_");
        $map["game_id"] = $user["game_id"];
        $map["user_id"] = $user["user_id"];
        $map['sdk_version'] = $user['sdk_version'];
        $res = $user_play -> where($map) -> find();
        if (empty($res)) {

            $user_entity = get_user_entity($user["user_id"]);
            $data["user_id"] = $user["user_id"];
            $data["user_account"] = $user_entity["account"];
            $data["user_nickname"] = $user_entity["nickname"];
            $data["game_id"] = $user["game_id"];
            $data["game_appid"] = $user["game_appid"];
            $data["game_name"] = get_game_name($user["game_id"]);
            $data["server_id"] = 0;
            $data["server_name"] = "";
            $data["role_id"] = 0;
            $data['parent_id'] = $user_entity["parent_id"];
            $data['parent_name'] = $user_entity["parent_name"];
            $data["role_name"] = "";
            $data["role_level"] = 0;
            $data["bind_balance"] = 0;
            $data["promote_id"] = $user_entity["promote_id"];
            $data["promote_account"] = $user_entity["promote_account"];
            $data['play_time'] = time();
            $data['play_ip'] = get_client_ip();
            $data["sdk_version"] = $user["sdk_version"];
            $data['ppuid'] = $user['puid'] == '' ? 0 : $user['puid'];
            $data['check_time'] = time();
            $user_play -> add($data);

        }

    }


    //修改角色名称
    public function update_user_play()
    {

        $user = json_decode(base64_decode(file_get_contents("php://input")), true);
        if (empty($user)) {

            $this -> set_message(1001, "fail", "操作数据不能为空");

        }
        $map['user_id'] = $user['user_id'];
        $map['game_id'] = $user['game_id'];
        $userplay = M('user_play', 'tab_') -> where($map) -> find();
        if (null == $userplay) {

            $this -> set_message(1004, "fail", "玩家不存在");

        } else {

            $user_play_map['id'] = $userplay['id'];
            if ($user['type'] == 1) {

                $update = M('user_play', 'tab_') -> where($user_play_map) -> setField('role_name', $user['role_name']);

            } else {

                $update = M('user_play', 'tab_') -> where($user_play_map) -> setField('role_level', $user['role_level']);

            }
            if ($update) {

                $this -> set_message(1, "success", "修改成功");

            } else {

                $this -> set_message(0, "fail", "修改失败");


            }

        }

    }


    /**
     * 添加游戏角色数据
     *
     * @param $request
     */
    public function save_user_play_info()
    {

        $request = json_decode(base64_decode(file_get_contents("php://input")), true);
        if (empty($request)) {
            $this -> set_message(1001, "fail", "操作数据不能为空");
        }
        $user_id = $request['user_id'];
        $server_id = empty($request['server_id']) ? 0 : $request['server_id'];
        $map['user_id'] = $user_id;
        $map['game_id'] = $request['game_id'];
        $map['server_id'] = $request['server_id'];
        $map['server_name'] = $request['server_name'];
        $user_play = M('user_play_info', 'tab_');
        $res = $data = $user_play -> where($map) -> find();
        $user = M('user', 'tab_');
        $user_data = $user -> find($user_id);
        
        $gameName = get_game_name($request['game_id']);
        $data['promote_id'] = $request['promote_id'];
        $data['promote_account'] = get_promote_account($request['promote_id']);
        $data['game_id'] = $request['game_id'];
        $data['game_name'] = $gameName;
        $data['server_id'] = $request['server_id'];
        $data['server_name'] = $request['server_name'];
        $data['role_name'] = $request['game_player_name'];
        $data['role_id'] = $request['game_player_id'];
        $data['role_level'] = $request['role_level'];
        $data['user_id'] = $user_id;
        $data['user_account'] = $user_data['account'];
        $data["user_nickname"] = $user_data["nickname"];
        $data['play_time'] = time();
        $data["sdk_version"] = $request["sdk_version"];
        $data['play_ip'] = get_client_ip();
        $data['pipuid'] = $user_data['puid'];

        Log::write('save_user_play_info:' . date('Y-m-d H:i:s') . ' ---- ' . json_encode($data), 'INFO');

        if ($res['id']>0) {
            $user_play->save($data);
            $this->updateLoginRecord($data);
        } else {
            $data['create_time'] = time();
            $data['create_ip'] = get_client_ip();
            // $data['create_device_number'] = time();

            // 修改重复插入问题  增加唯一索引  记录重复插入异常
            try {
                $user_play->add($data);
            } catch (\Exception $e) {
                Log::write('Duplicate Exception:' .json_encode($e->getMessage()), Log::ERR);
            }

            $this->updateLoginRecord($data);
        }

        $server = M('server', 'tab_')->where(['server_id' => $request['server_id'], 'game_id' => $request['game_id']])->find();
        if (empty($server)) {
            $serverData = [
                'game_id' => $request['game_id'],
                'game_name' => $gameName,
                'server_name' => $request['server_name'],
                'server_num' => $request['server_id'],
                'server_id' => $request['server_id'],
                'server_version' => $request["sdk_version"],
                'create_time' => time(),
                'start_time' => time(),
            ];
            M('server', 'tab_')->data($serverData)->add();
        }

        $this -> set_message(200, "success", "成功");

    }

    /**
     * 更新登录记录表区服
     *
     * @param $userPlay
     *
     * @author: 鹿文学[lwx]<fyj301415926@126.com>
     * @since: 2019\4\22 0022 10:38
     *
     */
    private function updateLoginRecord($userPlay) {
        $map = array(
            'game_id' => $userPlay['game_id'],
            'user_id' => $userPlay['user_id'],
            'lpuid' => $userPlay['pipuid'],
            'promote_id' => $userPlay['promote_id'],
            'login_time' => ['gt', 0],
        );

        $userLoginRecordModel = M('user_login_record', 'tab_');

        $userLoginRecordData = $userLoginRecordModel->where($map)->order('id desc')->find();

        $data = array(
            'server_id' => $userPlay['server_id'],
            'server_name' => $userPlay['server_name'],
            'game_player_name'=>$userPlay['role_name'],
            'id'=>$userLoginRecordData['id']
        );

        return $userLoginRecordModel->save($data);
    }


    /**
     * @param $email
     * @param $v_code
     * 验证邮箱验证码
     */
    public function verify_email_code($email, $v_code)
    {
        if (empty($email)) {

            $this -> new_set_message(1016, "邮箱不能为空", []);

        } elseif (empty($v_code)) {

            $this -> new_set_message(1019, "验证码不能为空", []);

        }
        $code_result = $this -> emailVerify($email, $v_code);
        if ($code_result == 1) {

            return true;

        } else {

            if ($code_result == 2) {

                $this -> new_set_message(1020, "请先获取验证码", []);

            } elseif ($code_result == - 98) {

                $this -> new_set_message(1021, "验证码超时", []);

            } elseif ($code_result == - 97) {

                $this -> new_set_message(1022, "验证码不正确,请重新输入", []);

            }

        }

    }


    /**
     * @param $email
     * @param $code
     * @param int $time
     *
     * @return int
     * 验证 邮箱验证码
     */
    public function emailVerify($email, $code, $time = 30)
    {

        $session = session($email);
        if (empty($session)) {

            return 2;

        } elseif ((NOW_TIME - $session['create_time']) > $time * 60) {

            return - 98;

        } elseif ($session['code'] != $code) {

            return - 97;

        }
        session($email, null);
        return 1;

    }


    /**
     * 发送邮件验证码 注册传1 解绑传2 绑定传3
     */
    public function send_email()
    {
        $data = json_decode(base64_decode(file_get_contents("php://input")), true);
        $code_type = $data['code_type'];
        $email = $data['email'];
        $pattern = "/([a-z0-9]*[-_.]?[a-z0-9]+)*@([a-z0-9]*[-_]?[a-z0-9]+)+[.][a-z]{2,3}([.][a-z]{2})?/i";
        if (!preg_match($pattern, $email)) {
            $this -> new_set_message(1017, "请输入正确的邮箱地址");
        }
        if ($code_type == 1) {/* 注册 */
            $user = M('user', 'tab_') -> where(['email|account' => $email]) -> find();
            if ($user) {
                $this -> new_set_message(1017, "该邮箱已被注册或绑定过");
            }
        } elseif ($code_type == 2) {/* 忘记密码 */

        } elseif ($code_type == 3) {/* 解绑 */

        } elseif ($code_type == 4) {/* 绑定 */
            $user = M('user', 'tab_') -> where(['email' => $email]) -> find();
            if ($user) {
                $this -> new_set_message(1017, "该邮箱已被绑定");
            }
        }
        $session = session($data['email']);
        if (!empty($session) && (NOW_TIME - $session['create_time']) < 60) {
            $this -> new_set_message(1024, "验证码发送过于频繁,请稍后再试", []);
            exit;
        }
        $email = $data['email'];
        $code = rand(100000, 999999);
        $bool = sendMail($data['email'], '<strong>' . $code . '<strong>');
        if ($bool) {
            session($email, ['code' => $code, 'create_time' => NOW_TIME]);
            $this -> new_set_message(200, "发送成功", []);
        } else {
            $this -> new_set_message(1018, "发送失败,请检查邮箱地址是否正确", []);
        }
    }


    /**
     * 检查账号是否存在
     *
     * @param $account
     *
     * @return bool
     * author: xmy 280564871@qq.com
     */
    public function checkUserExist($account)
    {

        $map['account'] = $account;
        $data = M('user', 'tab_') -> where($map) -> find();
        if (empty($data)) {

            return true;

        } else {

            return false;

        }

    }


    /**
     *短信发送
     */
    public function send_sms()
    {

        $data = json_decode(base64_decode(file_get_contents("php://input")), true);
        $phone = $data['phone'];
        if ($data['reg'] == 1) { /* 注册检查 */
            $user = M('user', 'tab_') -> where(['phone|account' => $phone]) -> find();
            if ($user) {
                $this -> new_set_message(1098, "该手机号已被注册或绑定过");
                die;
            }
        } elseif ($data['reg'] == 2) { /* 绑定检查 */
            $user = M('user', 'tab_') -> where(['phone' => $phone]) -> find();
            if ($user) {
                $this -> new_set_message(1098, "该手机号已被绑定");
                die;
            }
        } elseif ($data['reg'] == 3) {/* 忘记密码检查 */

        } elseif ($data['reg'] == 4) {/* 解绑检查 */

        }
        $this -> sms_send($phone);


    }


    /**
     *用户基本信息
     */
    public function user_info()
    {

        C(api('Config/lists'));
        $user = json_decode(base64_decode(file_get_contents("php://input")), true);
        $model = M("user", "tab_");
        $data = array();
        switch ($user['type']) {

            case 0:
                $data = $model
                        -> field("tab_user.id,account,ifnull(nickname,account) as nickname,phone,balance,bind_balance,ifnull(tab_user.sex,0) as sex,game_name,register_type,ifnull(age_status,0) as age_status,ifnull(idcard,'') as idcard,ifnull(real_name,'') as real_name,ifnull(head_img,'') as head_img,third_authentication,email,balance,point,gold_coin")
                        -> join("INNER JOIN tab_user_play ON tab_user.id = tab_user_play.user_id and tab_user.id = {$user['user_id']} and tab_user_play.game_id = {$user['game_id']}")
                        -> find();
                break;
            default:
                $map['account'] = $user['user_id'];
                $map['lock_status'] = 1;
                $data = $model -> field("id,account,ifnull(nickname,account) as nickname,phone,balance,ifnull(sex,0) as sex,ifnull(age_status,0) as age_status,ifnull(idcard,'') as idcard,ifnull(real_name,'') as real_name,ifnull(head_img,'') as head_img,third_authentication,email,balance,point,gold_coin") -> where($map) -> find();
                break;

        }
        if (empty($data)) {

            $this -> new_set_message(1004, "帐号不存在或被禁用!", []);

        }
        $unread_count = 0;
        $unread_count += M('share_record', 'tab_') -> where(['invite_id' => $data['id'], 'award_coin' => ['gt', 0], 'read' => 0]) -> count();
        $unread_count += M('point_record', 'tab_') -> where(['type_id' => 6, 'user_id' => $data['id'], 'point' => ['gt', 0], 'read' => 0]) -> count();
        $data['notice_count'] = $unread_count;
        $buddies_request = get_buddies_unagree_count($data['id']);
        $data['request_count'] = $buddies_request;
        $unread_count += $buddies_request;
        $data['unread_count'] = $unread_count;
        $money = 0;
        $money += M('deposit', 'tab_') -> where(['pay_status' => 1, 'user_id' => $data['id']]) -> sum('pay_amount');
        $money += M('spend', 'tab_') -> where(['pay_status' => 1, 'user_id' => $data['id']]) -> sum('pay_amount');
        $data['vip_level'] = get_vip_level($money);
        $data['phone'] = empty($data["phone"]) ? " " : $data["phone"];
        $this -> new_set_message(200, "success", $data);

    }


    /**
     *用户平台币充值记录
     */
    public function user_deposit_record()
    {

        $data = json_decode(base64_decode(file_get_contents("php://input")), true);
        $map["user_id"] = $data["user_id"];
        $map["pay_status"] = 1;
        $row = intval($data['row']);
        $page = intval($data['index']);
        $row = $row ? $row : 20;
        $page = $page ? $page : 1;
        $deposit = M("deposit", "tab_") -> field('pay_way,pay_amount,create_time') -> where($map) -> order('id desc') -> page($page, $row) -> select();
        $count = M("deposit", "tab_") -> field('pay_way,pay_amount,create_time') -> where($map) -> count();
        if (empty($deposit)) {

            echo base64_encode(json_encode(array("status" => 1061, "return_code" => "fail", "return_msg" => "暂无记录")));
            exit();

        }
        foreach ($deposit as $k => $v) {
            $deposit[$k]['pay_way_name'] = get_pay_way($v['pay_way']);
        }
        $return_data['status'] = 200;
        $return_data['total'] = $count;
        $return_data['data'] = $deposit;
        echo base64_encode(json_encode($return_data));

    }


    /**
     *用户领取礼包记录
     */
    public function user_gift_record()
    {

        $data = json_decode(base64_decode(file_get_contents("php://input")), true);
        $map["user_id"] = $data["user_id"];
        $map["game_id"] = $data["game_id"];
        $gift = M("GiftRecord", "tab_")
                -> field("tab_gift_record.game_id,tab_gift_record.game_name,tab_giftbag.giftbag_name ,tab_giftbag.digest,tab_gift_record.novice,tab_gift_record.status,tab_giftbag.start_time,tab_giftbag.end_time")
                -> join("LEFT JOIN tab_giftbag ON tab_gift_record.gift_id = tab_giftbag.id where user_id = {$data['user_id']} and tab_gift_record.game_id = {$data['game_id']}")
                -> select();
        if (empty($gift)) {

            echo base64_encode(json_encode(array("status" => 1061, "return_code" => "fail", "return_msg" => "暂无记录")));
            exit();

        }
        foreach ($gift as $key => $val) {

            $gift[$key]['icon'] = $this -> set_game_icon($val[$key]['game_id']);
            $gift[$key]['now_time'] = NOW_TIME;

        }
        $return_data['status'] = 200;
        $return_data['data'] = $gift;
        echo base64_encode(json_encode($return_data));

    }


    /**
     *用户平台币(绑定和非绑定)
     */
    public function user_platform_coin()
    {

        $data = json_decode(base64_decode(file_get_contents("php://input")), true);
        C(api('Config/lists'));
        $user_play = M("UserPlay", "tab_");
        $platform_coin = array();
        $user_data = array();
        #非绑定平台币信息
        $user_data = get_user_entity($data["user_id"]);
        $platform_coin['status'] = 200;
        $platform_coin["balance"] = $user_data["balance"];
        #绑定平台币信息
        $map["user_id"] = $data["user_id"];
        $map["game_id"] = $data["game_id"];
        $user_data = $user_play -> where($map) -> find();
        $platform_coin["bind_balance"] = $user_data["bind_balance"];
        echo base64_encode(json_encode($platform_coin));

    }


    //判断帐号是否存在
    public function account_exist()
    {

        $data = json_decode(base64_decode(file_get_contents("php://input")), true);
        $map['account'] = $data['account'];
        $user = M('user', 'tab_') -> where($map) -> find();
        if (empty($user)) {

            echo json_encode(array('status' => 1004, 'msg' => '帐号不存在'));

        } else {

            echo json_encode(array('status' => 200));

        }

    }


    //解绑手机
    public function user_phone_unbind()
    {

        $data = json_decode(base64_decode(file_get_contents("php://input")), true);
        $this -> sms_verify($data['phone'], $data['code']);
        $map['id'] = $data['user_id'];
        $user = M('user', 'tab_') -> where($map) -> setField('phone', "");
        if ($user) {

            echo base64_encode(json_encode(array('status' => 200, 'return_msg' => '解绑成功')));


        } else {

            echo base64_encode(json_encode(array('status' => - 1, 'return_msg' => '解绑失败')));


        }

    }
    //解绑邮箱
    //yyh 2018 10 25
    public function unbind_email()
    {
        $request = json_decode(base64_decode(file_get_contents("php://input")), true);
        $user_id = $request['user_id'];
        $email = $request['email'];
        $user_data = M('User', 'tab_') -> field('account,email') -> find($user_id);
        if (empty($user_data)) {
            $this -> new_set_message(1001, "用户数据不存在", []);
        }
        if ($email != $user_data['email']) {
            $this -> new_set_message(1001, "您未绑定该邮箱", []);
        }
        $v_res = $this -> verify_email_code($user_data['email'], $request['code']);
        $map['id'] = $user_id;
        $user = M('user', 'tab_') -> where($map) -> setField('email', "");
        if ($user) {
            $this -> new_set_message(200, "解绑成功", []);
        } else {
            $this -> new_set_message(0, "解绑失败", []);
        }
    }
    //绑定邮箱
    //yyh 2018 10 25
    public function bind_email()
    {
        $request = json_decode(base64_decode(file_get_contents("php://input")), true);
        $user_id = $request['user_id'];
        $email = $request['email'];
        $user_data = M('User', 'tab_') -> field('account,email') -> find($user_id);
        if (empty($user_data)) {
            $this -> new_set_message(1001, "用户数据不存在", []);
        }
        if ($user_data['email'] != '') {
            $this -> new_set_message(1030, "该用户已经绑定过邮箱,请解绑后再来", []);
        }
        $v_res = $this -> verify_email_code($email, $request['code']);
        $map['id'] = $user_id;
        $user = M('user', 'tab_') -> where($map) -> setField('email', $email);
        if ($user) {
            $this -> new_set_message(200, "绑定成功", []);
        } else {
            $this -> new_set_message(0, "绑定失败", []);
        }

    }

    //常见问题
    public function get_problem()
    {

        $data = M('document')
                -> join("left join sys_category c on c.name='FAQ'")
                -> where('c.id = sys_document.category_id AND sys_document.status = 1')
                -> field('sys_document.id,sys_document.title,sys_document.description')
                -> select();
        echo base64_encode(json_encode($data));

    }


    //留言
    public function get_question()
    {

        $request = json_decode(base64_decode(file_get_contents("php://input")), true);
        $type = $request['type'];
        $user_id = $request['user_id'];
        $content = $request['content'];
        $map['user_id'] = $user_id;
        $data = M('question', 'tab_') -> where($map) -> find();
        if ($type == 1) {

            if (empty($data)) {

                $data['create_time'] = time();
                $question[time()] = $content;
                $data['question'] = json_encode($question);
                $data['user_id'] = $user_id;
                $data['account'] = get_user_entity($user_id)['account'];
                M('question', 'tab_') -> where($map) -> add($data);

            } else {

                $question = json_decode($data['question'], true);
                $question[time()] = $content;
                $data['question'] = json_encode($question);
                $data['account'] = get_user_entity($user_id)['account'];
                M('question', 'tab_') -> where($map) -> save($data);

            }

        }
        $question = json_decode($data['question'], true);
        foreach ($question as $k => $v) {

            $res[$k][1] = $v;

        }
        $answer = json_decode($data['answer'], true);
        foreach ($answer as $key => $value) {

            $res[$key][2] = $value;

        }
        ksort($content);
        echo base64_encode(json_encode($res));

    }


    //获取开启的支付
    public function get_pay_server()
    {
        $request = json_decode(base64_decode(file_get_contents("php://input")), true);
        if (pay_set_status('wei_xin') == 1 || pay_set_status('wei_xin_app') 
        || pay_set_status('weixin') == 1 || pay_set_status('weixin_gf') == 1 
        || pay_set_status('jft_wap') == 1 || (pay_set_status('goldpig') == 1 && C('goldpig.wx'))
        || (pay_set_status('heepay') == 1 && C('heepay.wxp'))
        ) {
            $wx_game = 1;
        } else if (pay_set_status('wei_xin_app') == 0 && pay_set_status('weixin') == 0 && pay_set_status('jft_wap') == 0) {
            $wx_game = 0;
        }
        if ($request['price'] >= C('WX_PAY_LIMIT')) $wx_game = 0;
        if (pay_set_status('alipay') == 1 || (pay_set_status('goldpig') == 1 && C('goldpig.zfb'))
        || (pay_set_status('sqpay') == 1 && C('sqpay.zfb'))
        ) {

            /* if (get_game_appstatus($request['game_id'])) { */
            $zfb_game = 1;

            /* } else {

                $zfb_game = 0;

            } */

        } else {

            $zfb_game = 0;

        }
        if (pay_set_status('jubaobar') == 1) {

            $jby_game = 1;

        } else {

            $jby_game = 0;

        }
        if (pay_set_status('jft') == 1) {

            $jft_game = 1;

        } else {

            $jft_game = 0;

        }
        if(pay_set_status('ptb_pay') == 1){
            $ptb_game = 1;
        }else{
            $ptb_game = 0;
        }
        if(pay_set_status('bind_pay') == 1){
            $bind_game = 1;
        }else{
            $bind_game = 0;
        }
        // 双乾 银联支付
        $squnion_pay = 0;
        $sqpay = M('tool','tab_')->field('status, config')->where(array('name'=>'sqpay'))->find();
        if ($sqpay['status'] == 1) {
        	$r = json_decode($sqpay['config'], true);
        	if (isset($r['union']) && $r['union'] == 1) 
        		$squnion_pay = 1;
        }
        // 双乾银联快捷支付
        $shortcut_pay = 0;
        $sqpay = M('tool','tab_')->field('status, config')->where(array('name'=>'sqpay'))->find();
        if ($sqpay['status'] == 1) {
        	$r = json_decode($sqpay['config'], true);
        	if (isset($r['shortcut']) && $r['shortcut'] == 1)
        		$shortcut_pay = 1;
        }
        // 双乾微信小程序支付
        $wx_small = 0;
        $sqpay = M('tool','tab_')->field('status, config')->where(array('name'=>'sqpay'))->find();
        if ($sqpay['status'] == 1) {
        	$r = json_decode($sqpay['config'], true);
        	if (isset($r['wx_small']) && $r['wx_small'] == 1)
        		$wx_small = 1;
        }
        
        $user_id = $request['user_id'];
        $game_id = $request['game_id'];
        $balance = M ('user', 'tab_')->where (array(
        	'id' => $user_id
        ))->getField('balance');
        $bind_balance = M('user_play', 'tab_')->where(array(
        	'user_id' => $user_id,
        	'game_id' => $game_id
        ))->getField('bind_balance');
        
//         pp($squnion_pay);
        //0:APP  1:WAP
        $zfb_type = pay_set_status('alipay') == 1 ? (empty(C('alipay.way')) ? 0 : C('alipay.way')) : 1;
        echo base64_encode(json_encode(array(
        	'status' => 200, 
        	'wx_game' => $wx_game, 
       		'zfb_game' => $zfb_game, 
       		'jby_game' => $jby_game, 
       		'jft_game' => $jft_game, 
       		'zfb_type' => $zfb_type,
       		'ptb_game' => $ptb_game,
       		'bind_game' => $bind_game,
       		'squnion_pay' => $squnion_pay,  // 银联0关  1开
        	'platform_coin' => $balance,
        	'bind_coin' => $bind_balance,
        	'wx_type' => $wx_small,   // 0微信  1 微信小程序 双乾
        	'shortcut_pay' => $shortcut_pay,  // 快捷支付 0关  1开
        )));

    }


    //获取渠道折扣
    public function get_user_discount()
    {

        $request = json_decode(base64_decode(file_get_contents("php://input")), true);
        $game_id = $request['game_id'];
        $user_id = $request['user_id'];
        $user = get_user_entity($user_id);
        $promote_id = $user['promote_id'];
        $discount = $this -> get_discount($game_id, $promote_id, $user_id);
        echo base64_encode(json_encode($discount));

    }


    /**
     * 实名认证信息   获得传递过来的UID,返回该玩家是否已经通过审核
     *
     * @return mixed
     */
    public function return_age()
    {

        $request = json_decode(base64_decode(file_get_contents("php://input")), true);
        if (empty($request)) {

            $this -> set_message(1001, "fail", "操作数据不能为空");

        }
        $mmm['account'] = $request['account'];
        $user = M('User', 'tab_') -> where($mmm) -> find();
        //添加登录记录
        $da = array(
                'user_id' => $user['id'],
                'user_account' => $user['account'],
                'user_nickname' => $user['nickname'],
                'game_id' => $request['game_id'],
                'game_name' => get_game_name($request["game_id"]),
                'server_id' => null,
                'type' => 1,
                'server_name' => null,
                'login_time' => NOW_TIME,
                'login_ip' => get_client_ip(),
                'sdk_version' => $request['sdk_version'],
                'promote_id' => $user['promote_id'],
                'lpuid' => $user['puid'],
        );
        /* $denglu = M('UserLoginRecord', 'tab_')->add($da); */
        $uloginrecord = M('UserGameLoginRecord', 'tab_')
                -> field('id,login_time,down_time') -> where(['user_id' => $user['id'], 'game_id' => $request['game_id'], 'sdk_version' => $request['sdk_version']]) -> order('id desc') -> find();
        if (empty($uloginrecord) || ($uloginrecord['login_time'] < 1 && $uloginrecord['down_time'] > 0)) {
            $denglu = M('UserGameLoginRecord', 'tab_') -> add($da);
        } else {
            $denglu = $uloginrecord['id'];
        }
        $data = C('age_prevent') == '' ? 0 : C('age_prevent'); //为空转换成1;
        $data['on-off'] = $data['bat'] == '' ? 0 : $data['bat'];
        $data['contents_off'] = C('age.contents_off');
        $data['auth'] = C('age') == '' ? 0 : C('age.status');
        $data['is_mandatory'] = C('age') == '' ? 0 : C('age.is_mandatory');
        unset($data['status']);
        $res['date'] = $data;
        $where['id'] = $request['user_id'];
        $re = M('User', 'tab_') -> field('age_status') -> where($where) -> find();
        if ($re) {

            $data['age_status'] = $re['age_status'];

        } else {

            $data['age_status'] = - 1;

        }
        //计算用户的游戏时间 和 休息时间
        $map['user_id'] = $request['user_id'];
        $map['login_time | down_time'] = period(0);
        $map['down_time'] = 0;
        $map['status'] = 0;
        $map2['user_id'] = $request['user_id'];
        $map2['login_time | down_time'] = period(0);
        $map2['login_time'] = 0;
        $map2['status'] = 0;
        $login_ = M('UserGameLoginRecord', 'tab_') -> where($map) -> order('login_time ASC') -> select();
        $down_ = M('UserGameLoginRecord', 'tab_') -> where($map2) -> order('down_time ASC') -> select();
        $login_count = count($login_);
        $down_count = count($down_);
        $play = 0;
        $down = 0;
        if ($login_count >= $down_count && $down_count != 0) {

            for ($i = 0; $i < $down_count; $i ++) {

                $play += $down_[$i]['down_time'] - $login_[$i]['login_time'];
                if ($down_[$i + 1]['down_time'] == 0 && $login_[$i + 1]['login_time'] != 0) {

                    $play += time() - $login_[$i + 1]['login_time'];

                }
                if ($login_[$i + 1]['login_time'] != 0) {

                    $down += $login_[$i + 1]['login_time'] - $down_[$i]['down_time'];

                }

            }

        }
        if ($down_count == 0 && $login_count > 0) {

            $play += time() - $login_[0]['login_time'];

        }
        $data['play_time'] = floor($play / 60);
        $data['down_time'] = floor($down / 60);
        //累计在线时间大于最长在线时间(两个未满18岁防沉迷时间的和) 继续在线就算在休息时间里面了
        if ($data['play_time'] / 60 >= ($data['hours_off_one'] + $data['hours_off_two'])) {

            $data['down_time'] += $data['play_time'] - $data['hours_off_one'] * 60 - $data['hours_off_two'] * 60;
            $data['play_time'] = $data['hours_off_one'] * 60 + $data['hours_off_two'] * 60;

        }
        //一旦游戏时间满足恢复时间  两种时间全部清零
        if ($data['down_time'] - $data['hours_cover'] * 60 >= 0) {

            $where2['user_id'] = $request['user_id'];
            $where2['login_time | down_time'] = period(0);
            $mmp['status'] = 200;
            M('UserGameLoginRecord', 'tab_') -> where($where2) -> save($mmp);
            $deng['id'] = $denglu;
            $de['status'] = 0;
            M('UserGameLoginRecord', 'tab_') -> where($deng) -> save($de);

        }
        echo base64_encode(json_encode(array('status' => 200, 'data' => $data)));

    }


    /**
     * 更改身份证账户   获得传递过来的UID,idcard,name进行更改数据库
     *
     * @return mixed
     */
    public function idcard_change()
    {

        C(api('Config/lists'));
        $user = json_decode(base64_decode(file_get_contents("php://input")), true);
        if (empty($user['user_id']) || empty($user['idcard']) || empty($user['real_name'])) {

            $this -> set_message(1066, "fail", "用户数据异常");

        }
        $map['id'] = $user['user_id'];
        $data['idcard'] = $user['idcard'];
        $data['real_name'] = $user['real_name'];
        if (isset($data['idcard'])) {
            if (substr($data['idcard'], - 1) === 'X') {
                $this -> set_message(1086, "fail", "身份证号码填写不正确,如有字母请小写");
            }
            $checkidcard = new \Think\Checkidcard();
            $invidcard = $checkidcard -> checkIdentity($data['idcard']);
            if (!$invidcard) {

                $this -> set_message(1086, "fail", "身份证号码填写不正确!");

            }
            $cardd = M('User', 'tab_') -> where(array('idcard' => $data['idcard'])) -> find();
            if ($cardd) {

                // $this -> set_message(1087, "fail", "身份证号码已被使用!"); // 去掉身份证唯一验证

            }

        }
        //身份证认证
        if (C('tool_age.status') == 0) {

            if (is_adult($data['idcard'])) {
                $data['age_status'] = 2;  // 成年
            } else {
                $data['age_status'] = 3;  // 未成年
            }
        } else {

            $re = age_verify($data['idcard'], $data['real_name']);
            switch ($re) {

                case - 1:
                    $this -> set_message(1067, "fail", "短信数量已经使用完!");
                    break;
                case - 2:
                    $this -> set_message(1068, "fail", "连接接口失败");
                    break;
                case 0:
                    $this -> set_message(1069, "fail", "用户数据不匹配");
                    break;
                case 1://成年
                    $data['age_status'] = 2;
                    break;
                case 2://未成年
                    $data['age_status'] = 3;
                    break;
                default:

            }

        }
        $return = M('User', 'tab_') -> where($map) -> save($data);
        if ($return === false) {
            $this -> set_message(1070, "fail", "用户数据更新失败");
        }
        $data['status'] = 200;
        echo base64_encode(json_encode($data));

    }


    /**
     * 通过用户的user_id 返回用户的下线时间 必要user_id  可选game_id role_id
     */
    public function down_time()
    {

        C(api('Config/lists'));
        $user = json_decode(base64_decode(file_get_contents("php://input")), true);
        $map['user_id'] = $user['user_id'];
        $map['login_time'] = 0;
        if (!empty($user['game_id'])) {

            $map['game_id'] = $user['game_id'];

        }
        if (!empty($user['role_id'])) {

            $map['role_id'] = $user['role_id'];

        }
        $return = M('UserLoginRecord', 'tab_') -> where($map) -> limit(1) -> order('id DESC') -> select();
        if (empty($return)) {

            $this -> set_message(0, "fail", "该用户没有下线记录");

        }
        echo base64_encode(json_encode($return));

    }


    /**
     * 接口  获得用户的下线数据并且存到数据库大众
     */
    public function get_down_time()
    {

        C(api('Config/lists'));
        $request = json_decode(base64_decode(file_get_contents("php://input")), true);
        if (empty($request)) {

            $this -> set_message(0, "fail", "参数错误");

        }
        $mmm['account'] = $request['account'];
        $user = M('User', 'tab_') -> where($mmm) -> find();
        if (!$user) {

            $this -> set_message(0, "fail", "找不到该用户!");

        }
        $da = array(
                'user_id' => $user['id'],
                'user_account' => $user['account'],
                'user_nickname' => $user['nickname'],
                'game_id' => $request['game_id'],
                'game_name' => get_game_name($request["game_id"]),
                'server_id' => null,
                'type' => 1,
                'server_name' => null,
                'down_time' => NOW_TIME,
                'login_ip' => get_client_ip(),
                'sdk_version' => $request['sdk_version'],
                'promote_id' => $request['promote_id'],
                'lpuid' => $user['puid'],
        );
        $return = M('UserLoginRecord', 'tab_') -> add($da);
        if ($return) {
            if ($request['state'] == 1) {
                M('nearby', 'tab_') -> where(['user_id' => $user['id']]) -> setField(['update_time' => time(), 'game_status' => 0]);
            }
            echo base64_encode(json_encode(array('status' => 200, 'return_msg' => '数据新增成功!')));

        } else {

            $this -> set_message(0, "fail", "数据新增失败!");

        }

    }

    /**
     * 获取小号列表
     *
     * @param  integer $puid 父用户编号
     *
     * @return array         结果集
     * @author    鹿文学
     */
    private function small_list($puid = '', $game_id = '')
    {

        if (!is_numeric($puid) || $puid < 1) {
            return [];
        }
        if (!is_numeric($game_id) || $game_id < 1) {
            return [];
        }
        $usermodel = M('User', 'tab_');
        $user = $usermodel -> field('account,is_platform') -> where(['id' => $puid, 'lock_status' => 1]) -> find();
        if (!is_array($user)) {
            return '';
        }
        $list = [];
        if ($user['is_platform'] == 1) {

            $list = $usermodel -> alias('u') -> field('u.id as user_id,u.account,u.account as user_account,is_platform')
                    -> join('tab_merchandise as m on (m.status = 0 and m.small_id = u.id) ')
                    -> where(['puid' => $puid, 'lock_status' => 1, 'fgame_id' => $game_id]) -> order('register_time desc') -> select();

        } else {

            $list = $usermodel -> field('id as user_id,account,is_platform,if(source_puid>0,CONCAT("(",FROM_UNIXTIME(source_time,"%m-%d"),"购买)",account),account) as user_account')
                    -> where(['puid' => $puid, 'lock_status' => 1, 'fgame_id' => $game_id]) -> order('register_time desc') -> select();

        }
        return $list;
    }

    /**
     * 获取小号列表
     *
     * @return array         结果集
     * @author    鹿文学
     */
    public function get_small_list()
    {

        $request = json_decode(base64_decode(file_get_contents("php://input")), true);
        $list = M('User', 'tab_') -> field('account')
                -> where(['id' => $request['user_id'], 'lock_status' => 1, 'fgame_id' => $request['game_id']]) -> find();
        if (!is_array($list)) {
            $this -> set_message(1004, "fail", "用户不存在或被禁用");
        }
        $small_list = $this -> small_list($request['user_id'], $request['game_id']);
        $small_list[] = array(
                'user_id' => $request['user_id'],
                'account' => $list['account'],
                'user_account' => $list['account'],
                'is_platform' => $this -> get_platform($request['user_id']),
        );
        $return = array(
                'status' => 200,
                'return_code' => 'success',
                'return_msg' => '成功',
                'small_list' => $small_list,
        );
        echo base64_encode(json_encode($return));
        exit();

    }

    /**
     * 添加小号
     *
     * @author    鹿文学
     */
    public function add_small()
    {

        $request = json_decode(base64_decode(file_get_contents("php://input")), true);
        if (empty($request)) {

            $this -> set_message(1001, "fail", "小号数据不能为空");

        }
        $user = M('User', 'tab_');
        $list = $user -> field('account,promote_id')
                -> where(['id' => $request['user_id'], 'lock_status' => 1]) -> find();
        if (!is_array($list)) {
            $this -> set_message(1004, "fail", "用户不存在或被禁用");
        }
        $result2 = $user -> where(array('fgame_id' => $request['game_id'], ['puid' => $request['user_id'], '_complex' => array('source_puid' => $request['user_id'], 'source_time' => 0), '_logic' => 'or'])) -> count();
        if ($result2 >= 10) {
            $this -> set_message(1099, "fail", "此平台账号小号数量已超出");
        }
        $result = $user -> where(['account' => $request['account']]) -> find();
        if ($result) {

            $this -> set_message(1017, "fail", "此账号已存在");

        }
        $userApi = new MemberApi();
        $res = $userApi -> register_small($request['user_id'], $request['account'], 1, 1, $list['promote_id'], get_promote_name($list['promote_id']), $request["game_id"], get_game_name($request["game_id"]), $request['sdk_version']);
        if ($res) {

            $this -> add_user_play(['puid' => $request['user_id'], 'game_id' => $request['game_id'], 'user_id' => $res, 'sdk_version' => $request['sdk_version']]);
            $small_list = $this -> small_list($request['user_id'], $request['game_id']);
            $small_list[] = array(
                    'user_id' => $request['user_id'],
                    'account' => $list['account'],
                    'user_account' => $list['account'],
                    'is_platform' => $this -> get_platform($request['user_id']),
            );
            $return = array(
                    'status' => 200,
                    'return_code' => 'success',
                    'return_msg' => '添加成功',
                    'small_list' => $small_list,
            );
            echo base64_encode(json_encode($return));
            exit();

        } else {

            $this -> set_message(1027, "fail", "添加失败");

        }

    }

    /**
     * 获取登录游戏信息并记录登录信息
     *
     * @author 鹿文学
     */
    public function get_enter_game_info()
    {

        $request = json_decode(base64_decode(file_get_contents("php://input")), true);
        $userApi = new MemberApi();
        if ($request['user_id'] == $request['small_id']) {
            $res = $userApi -> get_enter_game_info([], $request['small_id'], $request['game_id'], get_game_name($user['game_id']), $request['sdk_version']);
        } else {
            $res = $userApi -> get_enter_game_info(['puid' => $request['user_id']], $request['small_id'], $request['game_id'], get_game_name($user['game_id']), $request['sdk_version']);
        }
        if (is_array($res)) {

            $return = array(
                    'status' => 200,
                    'return_code' => 'success',
                    'return_msg' => '操作成功',
                    'user_id' => $res['user_id'],
                    'account' => $res['account'],
                    'token' => $res['token'],
                    'OTP_token' => think_encrypt(json_encode(array('uid' => $res['user_id'], 'time' => time())), 1),
                    'is_uc' => 0,
            );
            echo base64_encode(json_encode($return));
            exit();

        } else {
            $this -> set_message(1004, "fail", "用户不存在或被禁用");
        }

    }

    /**
     * 获取公用账号标识
     *
     * @author 鹿文学
     */
    public function get_platform($uid = 0)
    {
        if (is_numeric($uid) && $uid > 0) {

            $data = M('User', 'tab_') -> field('is_platform') -> where(['id' => $uid]) -> find();
            return $data['is_platform'];

        } else {
            return 0;
        }
    }


    /**
     * 退出按钮
     * 1:开启  0:关闭
     */
    public function loginout_status()
    {
        $status = C('LOGINOUT_STATUS');
        echo base64_encode(json_encode(array('status' => 200, 'data' => $status)));
    }

    /**
     * 强更接口
     *
     * @return [type] [description]
     */
    public function force_update()
    {
        $request = json_decode(base64_decode(file_get_contents("php://input")), true);
        $game_info = M('Game', 'tab_') -> where(array('id' => $request['game_id'])) -> find();
        $game_source = M('GameSource', 'tab_') -> where(array('game_id' => $request['game_id'])) -> find();
        if (empty($game_source)) {
            $game_source['source_version'] = 0;
        }
        $data['is_force_update'] = $game_info['is_force_update'];
        $data['source_version'] = $game_source['source_version'];
        $data['update_tips'] = '游戏已经更新,请下载最新游戏包~';
        $remark = json_decode($game_source['remark']);
        if ($game_info['sdk_version'] == 1) {
            $data['and_remark'] = !empty($remark) ? $remark : [];
            $data['and_file_size'] = !empty($game_source['file_size']) ? $game_source['file_size'] : 0;
            $data['and_version_code'] = !empty($game_source['version']) ? $game_source['version'] : 0;
            $data['and_version_name'] = !empty($game_source['version']) ? $game_source['version'] : '';
            $host = 'http://' . $_SERVER['HTTP_HOST'];
        } else {
            $data['ios_remark'] = !empty($remark) ? $remark : [];
            $data['ios_file_size'] = !empty($game_source['file_size']) ? $game_source['file_size'] : 0;
            $data['ios_version_code'] = !empty($game_source['version']) ? $game_source['version'] : 0;
            $data['ios_version_name'] = !empty($game_source['version']) ? $game_source['version'] : '';
            $host = 'https://' . $_SERVER['HTTP_HOST'];
        }
        if ($request['promote_id'] > 0) {
            //渠道包
            $apply_info = M('Apply', 'tab_') -> where(array('game_id' => $request['game_id'], 'promote_id' => $request['promote_id'])) -> find();
            if ($apply_info['enable_status'] == 1) {

                if ($request['launch_id'] > 0) {
                    $applylauntch = M('apply_launch', 'tab_') -> where(['apply_id' => $apply_info['id'], 'platform_id' => $request['launch_id'], 'position' => ($request['position'] ? $request['position'] : 1)]) -> find();
                    $data['game_url'] = 'http://' . $_SERVER['HTTP_HOST'] . '/index.php?s=/Home/Home/promotionofregistration/pid/' . $request['promote_id'] . '/gid/' . $game_info['relation_game_id'] . '/lid/' . $request['launch_id'] . '/p/' . $request['position'];
                    if ($applylauntch) {
                        $file_url = $applylauntch['launch_down_url'];
                        $pfile_url = $applylauntch['launch_plist_url'];
                        if (stripos($file_url, 'http://') === false) {
                            $file_url = strpos($file_url,'http') ===false ? $host . str_replace('./', '/', $file_url) : $file_url;
                        }
                        if (stripos($pfile_url, 'https://') === false) {
                            $pfile_url = strpos($pfile_url,'http') ===false ? $host . str_replace('./', '/', $pfile_url) : $pfile_url;
                        }

                    } else {
                        $file_url = '';
                        $pfile_url = '';
                    }

                } else {

                    $data['game_url'] = 'http://' . $_SERVER['HTTP_HOST'] . '/index.php?s=/Home/Home/promitionofregestion/pid/' . $request['promote_id'] . '/gid/' . $game_info['relation_game_id'];
                    $file_url = strpos($apply_info['pack_url'],'http') ===false ?$host . ltrim($apply_info['pack_url'], '.') : $apply_info['pack_url'];
                    $pfile_url = strpos($apply_info['plist_url'],'http') ===false ?$host . ltrim($apply_info['plist_url'], '.') : $apply_info['plist_url'];
                }

            } else {
                $data['update_tips'] = '游戏正在更新,请稍后再试~';
                $file_url = '';
                $pfile_url = '';
            }
        } else {
            //原包
            $data['game_url'] = 'http://' . $_SERVER['HTTP_HOST'] . '/mobile.php?s=/Game/detail/id/' . $request['game_id'];
            $file_url = strpos($game_source['file_url'],'http') ===false ? $host . ltrim($game_source['file_url'], '.') : $game_source['file_url'];
            $pfile_url = strpos($game_source['plist_url'],'http')===false ?  $host . ltrim($game_source['plist_url'], '.') : $game_source['plist_url'];

        }
        if ($game_info['sdk_version'] == 1) {
            $data['and_file_url'] = $file_url;
        } else {
            $data['ios_file_url'] = $pfile_url;
        }
        echo base64_encode(json_encode(array('code' => 200, 'msg' => '请求成功', 'data' => $data)));
    }


    /**
     * 设备统计
     *
     * @param        integer        sdk_version        系统版本(1:安卓,2:苹果)
     * @param    string        model                        设备型号
     * @param        string        unique_code            设备唯一码
     * @param        integer        game_id                    游戏编号
     * @param        integer        mark                        在线标志(0:退出游戏,1:登录游戏)
     *
     * @return  json
     * @author  鹿文学
     */
    public function device_record()
    {

        $request = json_decode(base64_decode(file_get_contents("php://input")), true);

        $device_record = M('device_record', 'tab_');
        $map = array(
                'unique_code' => $request['unique_code'],
        );

        $result = $device_record -> where($map) -> order('create_time desc') -> find();
        $duration = 0;
        $now = time();
        if (is_array($result) && $result['mark'] == 1) {

            if ($request['mark'] == 1) {

                $map['id'] = $result['id'];
                $device_record -> where($map) -> setField(['duration' => intval(2.5 * 3600)]);


            } elseif ($request['mark'] == 0) {

                $duration = $now - $result['create_time'];

            }

        }
        $data = array(
                'create_time' => $now,
                'version' => $request['sdk_version'],
                'model' => $request['model'],
                'unique_code' => $request['unique_code'],
                'game_id' => $request['game_id'],
                'game_name' => get_game_name($request['game_id']),
                'mark' => $request['mark'],
                'duration' => $duration,
        );
        $res = $device_record -> add($data);
        if ($res > 0) {
            $this -> new_set_message(200, "添加设备信息成功", []);
        } else {
            $this -> new_set_message(0, "添加设备信息失败", []);
        }

    }
    //sdk记录投放数据
    //author yyh 2018.10.22
    public function launch_record()
    {
        $request = json_decode(base64_decode(file_get_contents("php://input")), true);
        $game_id = $request['game_id'];
        $user_id = $request['user_id'];
        $launch_id = $request['launch_id'];
        $promote_id = $request['promote_id'];
        $position = $request['position'];

        $game_data = M('Game', 'tab_') -> field('id as game_id,game_name') -> find($game_id);
        if (empty($game_data)) {
            $this -> new_set_message(0, '游戏不存在', []);
        }
        $user_data = M('User', 'tab_')
                -> field('id as user_id,account as user_account')
                -> where(['promote_id' => $promote_id, 'id' => $user_id])
                -> find();
        if (empty($user_data)) {
            $this -> new_set_message(0, '账号不存在', []);
        }
        $launch_data = M('LaunchPlatform', 'tab_') -> field('id as launch_id,name') -> find($launch_id);
        if (empty($launch_data)) {
            $this -> new_set_message(0, '投放平台不存在', []);
        }
        $promote_data = M('Promote', 'tab_') -> field('id,account') -> find($promote_id);
        if (empty($promote_data)) {
            $this -> new_set_message(0, '推广员数据不存在', []);
        }
        $record_data = M('LaunchRecord', 'tab_') -> where(['platform_id' => $launch_id, 'game_id' => $game_id, 'user_id' => $user_id, 'promote_id' => $promote_id]) -> find();
        if (empty($record_data)) {
            $data['platform_id'] = $launch_id;
            $data['platform_name'] = $launch_data['name'];
            $data['game_id'] = $game_id;
            $data['game_name'] = $game_data['game_name'];
            $data['user_id'] = $user_id;
            $data['user_account'] = $user_data['user_account'];
            $data['promote_id'] = $promote_id;
            $data['promote_account'] = $promote_data['account'];
            $data['unique_code'] = $request['unique_code'] ?: '';
            $data['create_time'] = time();
            $data['position'] = $position;
            $res = M('LaunchRecord', 'tab_') -> add($data);
            if (!$res) {
                $this -> new_set_message(0, '记录投放数据失败', []);
            }
        }
        $this -> new_set_message(200, '记录投放数据成功', []);

    }
    //支付宝芝麻信用
    //yyh  2018 10 24
    public function alipay_zmxy()
    {
        $request = json_decode(base64_decode(file_get_contents("php://input")), true);
        $user_id = $request['user_id'];
        $game_id = $request['game_id'];
        if ($user_id < 1) {
            $this -> new_set_message(0, 'user_id参数错误', []);
        }
        $alipayauth = M('alipay_auth', 'tab_') -> field('appid,status') -> where(['game_id' => $game_id]) -> find();
        if (empty($alipayauth)) {
            $this -> new_set_message(0, '此游戏不支持支付宝快捷认证', []);
        }
        if (empty($alipayauth) || $alipayauth['status'] != 1) {
            $this -> new_set_message(0, '此游戏未开启支付宝快捷认证', []);
        }
        $appid = $alipayauth['appid'];
        Vendor('Alipay.AopSdk');
        $c = new \AopClient();
        $c -> gatewayUrl = "https://openapi.alipay.com/gateway.do";
        $c -> appId = $appid;
        $c -> rsaPrivateKey = file_get_contents("./Application/Sdk/SecretKey/alipay/rsa2_private_key.txt");
        $c -> format = "json";
        $c -> charset = "utf-8";
        $c -> signType = "RSA2";
        $c -> alipayrsaPublicKey = file_get_contents("./Application/Sdk/SecretKey/alipay/alipay2_public_key.txt");
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称:alipay.user.userinfo.share
        $request = new \ZhimaCustomerCertificationInitializeRequest();
        $transaction_id = 'ZGYD' . date('Ymdhis', time()) . sp_random_string(6);
        $request -> setBizContent("{"
                                  . "\"transaction_id\":\"{$transaction_id}\","
                                  . "\"product_code\":\"w1010100000000002978\","
                                  . "\"biz_code\":\"SMART_FACE\","
                                  . "\"identity_param\":\"{}\","
                                  . "\"ext_biz_param\":\"{}\"" . "  }");
        $response = $c -> execute($request);
        if ($response -> zhima_customer_certification_initialize_response -> code != 10000) {
            $this -> new_set_message(0, '授权失败' . $response -> zhima_customer_certification_initialize_response -> code, []);
        }
        $biz_no = $response -> zhima_customer_certification_initialize_response -> biz_no;
        $request_get_url = new \ZhimaCustomerCertificationCertifyRequest();
        $request_get_url -> setBizContent("{\"biz_no\":\"{$biz_no}\"}");
        // $notify_url = $_SERVER['HTTP_HOST'].'/sdk.php/User/get_alipay_zmxy_notify';
        $return_url = $_SERVER['HTTP_HOST'] . '/sdk.php/User/get_alipay_zmxy_return/user_id/' . $user_id . '/game_id/' . $game_id;
        // $request_get_url->setNotifyUrl("alipay://{$notify_url}");
        $request_get_url -> setReturnUrl("alipay://{$return_url}");
        $responseurl = $c -> pageExecute($request_get_url, 'GET');
        $this -> new_set_message(200, 'success', ['url' => $responseurl, 'appid' => $appid]);


        /* $result  = $c->pageExecute($request_get_url);

						$responseNode = str_replace(".", "_", $request_get_url->getApiMethodName()) . "_response";

						$resultCode = $result->$responseNode->code;

						if(!empty($resultCode)&&$resultCode == 10000){


							$save['id'] = $user_id;
							$save['age_status'] = 2;
							$save['third_authentication'] = 1;
							$save['real_name'] = $biz_no;
							$save['idcard'] = $zfbuser;
							$save['anti_addiction'] = 1;
							M('user','tab_')->save($save);

							$this->new_set_message(200, 'success', []);
						} else {
							$this->new_set_message(0, 'fail', []);
						} */

    }
    //芝麻信用回调
    //yyh  2018 10 24
    public function get_alipay_zmxy_return()
    {

        $biz_content = json_decode($_GET['biz_content'], true);
        $biz_no = $biz_content['biz_no'];
        $user_id = $_GET['user_id'];
        $game_id = $_GET['game_id'];
        if ($user_id < 1) {
            $this -> assign('result', 'fail');
            $this -> display();
            exit;
        }
        $user_data = M('User', 'tab_') -> field('id') -> find($user_id);
        if (empty($user_data)) {
            $this -> assign('result', 'fail');
            $this -> display();
            exit;
        }
        $alipayauth = M('alipay_auth', 'tab_') -> field('appid,status') -> where(['game_id' => $game_id]) -> find();
        if (empty($alipayauth)) {
            $this -> assign('result', 'fail');
            $this -> display();
            exit;
        }
        if (empty($alipayauth) || $alipayauth['status'] != 1) {
            $this -> assign('result', 'fail');
            $this -> display();
            exit;
        }
        $appid = $alipayauth['appid'];
        Vendor('Alipay.AopSdk');
        $aop = new \AopClient ();
        $aop -> gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop -> appId = $appid;
        $aop -> rsaPrivateKey = file_get_contents("./Application/Sdk/SecretKey/alipay/rsa2_private_key.txt");
        $aop -> alipayrsaPublicKey = file_get_contents("./Application/Sdk/SecretKey/alipay/alipay2_public_key.txt");
        $aop -> apiVersion = '1.0';
        $aop -> signType = 'RSA2';
        $aop -> postCharset = 'utf-8';
        $aop -> format = 'json';
        $request = new \ZhimaCustomerCertificationQueryRequest ();
        $request -> setBizContent("{" .
                                  "\"biz_no\":\"{$biz_no}\"" .
                                  "  }");
        $result = $aop -> execute($request);
        $responseNode = str_replace(".", "_", $request -> getApiMethodName()) . "_response";
        $resultCode = $result -> $responseNode -> code;
        $zfbuserjson = $result -> $responseNode -> identity_info;
        $zfbuserarr = json_decode($zfbuserjson, true);
        $zfbuser = $zfbuserarr['user_id'];
        if (!empty($resultCode) && $resultCode == 10000) {
            $this -> assign('result', 'success');
            $save['id'] = $user_id;
            $save['age_status'] = 2;
            $save['third_authentication'] = 1;
            $save['real_name'] = $biz_no;
            $save['idcard'] = $zfbuser;
            $save['anti_addiction'] = 1;
            M('user', 'tab_') -> save($save);
        } else {
            $this -> assign('result', 'fail');
        }
        $this -> display();
    }


    /**
     * 获取支付宝实名认证结果
     *
     * @return   third_authentication  0失败 1成功
     * author: 鹿文学
     */
    public function get_auth_result()
    {

        $request = json_decode(base64_decode(file_get_contents("php://input")), true);
        $user_id = $request['user_id'];
        if ($user_id < 1) {
            $this -> new_set_message(0, 'user_id参数错误', []);
        }
        $user = M('User', 'tab_') -> field('third_authentication') -> where(['id' => $user_id]) -> find();
        $this -> new_set_message(200, '', ['third_authentication' => $user['third_authentication']]);

    }


    /**
     * 绑币记录
     *
     * @param $token
     * @param int $p
     * author: yyh 2018 10 26
     */
    public function get_user_bind_coin()
    {
        $request = json_decode(base64_decode(file_get_contents("php://input")), true);
        $user_id = $request['user_id'];
        $page = intval($request['p']);
        $page = $page ? $page : 1; //默认显示第一页数据
        $row = intval($request['row']) ?: 10;
        $model = new UserModel();
        $data = $model -> getUserBindCoin($user_id, $page, $row);
        foreach ($data as $key => $value) {
            $data[$key]['icon'] = new_icon_url($value['icon']);
        }
        if (empty($data)) {
            $this -> new_set_message(1033, "暂无数据", []);
        } else {
            $this -> new_set_message(200, "成功", $data);
        }
    }
    //提现金币wap链接
    //yyh 2018 10 26
    public function withdraw_gold_url()
    {
        $data['url'] = 'http://' . $_SERVER['HTTP_HOST'] . '/mobile.php?s=/Trade/withdraw_gold/issdk/1.html';
        $data['IS_OPEN_SMALL_ACCOUNT'] = C('IS_OPEN_SMALL_ACCOUNT') == 1 ? 1 : 0;//是否打开小号配置
        $this -> new_set_message(200, "成功", $data);
    }


    /**
     * 签到
     *
     * @author 鹿文学
     */
    public function sign_in()
    {

        $request = json_decode(base64_decode(file_get_contents("php://input")), true);
        $result = A('Point', 'Event') -> sign_in($request['user_id']);
        switch ($result['mark']) {
            case - 1:
                {

                    $this -> new_set_message(1131, "此奖励不存在或被禁用", []);

                };
                break;
            case - 2:
                {
                    unset($result['mark']);
                    $this -> new_set_message(1132, "今日已签过", $result);

                };
                break;
            case - 3:
                {
                    unset($result['mark']);
                    $this -> new_set_message(1133, "签到失败", $result);

                };
                break;
            case 1:
                {
                    unset($result['mark']);
                    $this -> new_set_message(200, "签到成功", $result);

                };
                break;
            default:
                $this -> new_set_message(1131, "此奖励不存在或被禁用", []);
        }

    }

    /**
     * vip等级
     *
     * @author 鹿文学
     */
    public function vip_level_list()
    {

        $tool = M('Tool', 'tab_') -> field('config') -> where(['name' => 'viplevel', 'status' => 1]) -> find();
        if (empty($tool)) {
            $this -> new_set_message(1134, "vip等级不存在或被禁用", []);
        }
        $viplevel = json_decode($tool['config'], true);
        if (!is_array($viplevel)) {
            $this -> new_set_message(1134, "vip等级不存在或被禁用", []);
        }
        $data = [];
        $vl = 0;
        $len = count($viplevel);
        foreach ($viplevel as $k => $v) {
            $vl = intval(str_replace('vip', '', $k));
            if ($vl - 1 == 0) {
                /* $data['VIP 0'] = '0-'.(intval($v)-1); */
            }
            if ($len == $vl) {
                $data['VIP ' . $vl] = $v . '以上';
            } else {
                $data['VIP ' . $vl] = $v . '-' . ($viplevel['vip' . ($vl + 1)] - 1);
            }
        }
        $this -> new_set_message(200, "请求成功", $data);

    }


    /**
     * 获取附近的人列表
     *
     * @author 鹿文学
     */
    public function get_nearby_list()
    {

        $request = json_decode(base64_decode(file_get_contents("php://input")), true);
        $nearbymodel = M('nearby', 'tab_');
        $userid = $request['user_id'];
        $gameid = $request['game_id'];
        $longitude = $request['longitude'];
        $latitude = $request['latitude'];
        $id = $nearbymodel -> field('id') -> where(['user_id' => $userid]) -> find();
        $user = M('user', 'tab_') -> field('account,nickname,head_img') -> where(['id' => $userid]) -> find();
        if (!empty($id)) {
            $data = array(
                    'update_time' => time(),
                    'user_nickname' => $user['nickname'],
                    'head_img' => $user['head_img'] ? $user['head_img'] : '',
                    'longitude' => $longitude,
                    'latitude' => $latitude,
            );
            $nearbymodel -> where(['id' => $id['id']]) -> save($data);
        } else {
            $data = array(
                    'user_id' => $userid,
                    'user_account' => $user['account'],
                    'user_nickname' => $user['nickname'],
                    'head_img' => $user['head_img'] ? $user['head_img'] : '',
                    'longitude' => $longitude,
                    'latitude' => $latitude,
                    'create_time' => time(),
                    'update_time' => time(),
            );
            $nearbymodel -> add($data);
        }
        $distance = 3; /* 三公里距离内 */
        /* 求经纬度 */
        $point = get_square_point($longitude, $latitude, $distance);
        $left_top_lng = $point['left_top']['longitude']; /* 左上经度 */
        $right_bottom_lng = $point['right_bottom']['longitude']; /* 右下经度 */
        $left_top_lat = $point['left_top']['latitude'];/* 左上纬度 */
        $right_bottom_lat = $point['right_bottom']['latitude'];/* 右下纬度 */
        $list = $nearbymodel -> alias('n') -> field('n.user_id,n.user_account,if(n.user_nickname="",n.user_account,n.user_nickname) as user_nickname,n.longitude,n.latitude,if(n.head_img="","",n.head_img) as head_img,n.game_status,ifnull(max(up.role_level),0) as role_level,ifnull(b.invitee_id,0) as invitee_id,ifnull(b.invitee_status,5) as invitee_status,ifnull(b.inviter_id,0) as inviter_id,ifnull(b.inviter_status,5) as inviter_status')
                -> join("left join tab_buddies as b on ((b.invitee_id=n.user_id and b.inviter_id = {$userid}) or (b.inviter_id=n.user_id and b.invitee_id={$userid}) ) ")
                -> join('left join tab_user_play as up on((up.ppuid=n.user_id or up.user_id=n.user_id) and up.game_id = ' . $gameid . ') ')
                -> where(['n.nearby_status' => 1, 'n.user_id' => array('neq', $userid), 'n.longitude' => ['between', array($left_top_lng, $right_bottom_lng)], 'n.latitude' => ['between', array($right_bottom_lat, $left_top_lat)]]) -> group('n.user_id') -> select();
        $data = [];
        if (is_array($list)) {
            /*
			 * 互为好友不显示 ,我未删,对方删 不显示
			 * buddies_status  0:我删除,1:我未删,2:待我验证, 3:待我重新验证,  5:对方删,6:对方未删,7:待对方验证,8:对方重新验证,10:没关系
			 */
            foreach ($list as $k => $v) {
                if ($v['invitee_status'] == 1 && $v['inviter_status'] == 1) {/* 互为好友不显示 */
                    continue;
                }
                if ($v['invitee_id'] >= 0 && $v['inviter_id'] >= 0) {
                    if ($v['invitee_id'] == $userid) {
                        if ($v['invitee_status'] == 1 && $v['inviter_status'] == 0) {
                            continue;
                        }/* 我未删,对方删 不显示 */
                        $buddies_status = $v['invitee_status'];
                    } else {
                        if ($v['invitee_status'] == 0 && $v['inviter_status'] == 1) {
                            continue;
                        }/* 我未删,对方删 不显示 */
                        $buddies_status = $v['invitee_status'] + 5;
                    }
                } else {
                    $buddies_status = 10;
                }
                $data[] = [
                        'user_id' => $v['user_id'],
                        'user_account' => $v['user_account'],
                        'user_nickname' => $v['user_nickname'],
                        'longitude' => $v['longitude'],
                        'latitude' => $v['latitude'],
                        'head_img' => $v['head_img'],
                        'game_status' => $v['game_status'],
                        'role_level' => $v['role_level'],
                        'distance' => get_distance_by_twopoint($longitude, $latitude, $v['longitude'], $v['latitude'], 2),
                        'buddies_status' => $buddies_status,
                ];

            }
            $data = my_sort($data, 'distance');
        }
        $this -> new_set_message(200, "", $data);
    }


    /**
     * 添加好友
     *
     * @author 鹿文学
     */
    public function set_buddies()
    {

        $request = json_decode(base64_decode(file_get_contents("php://input")), true);
        $buddiesmodel = M('buddies', 'tab_');
        $guest_id = $request['guest_id'];
        $user_id = $request['user_id'];
        $message = $request['message'];
        $map['_string'] = "(inviter_id = {$user_id} and invitee_id = {$guest_id})";
        $map['_complex'] = array('inviter_id' => $guest_id, 'invitee_id' => $user_id);
        $map['_logic'] = 'or';
        $result = $buddiesmodel -> where($map) -> find();
        if (!empty($result)) {
            if ($result['inviter_status'] == 1 && $result['invitee_status'] == 1) {
                $this -> new_set_message(1136, "您已与" . ($result['inviter_id'] == $user_id ? $result['invitee_account'] : $result['inviter_account']) . "成为好友", []);
                exit;
            } else {
                $data['message'] = $message;
                if ($result['inviter_id'] == $user_id) {
                    $data['inviter_status'] = 1;
                    $guest_status = $result['invitee_status'];
                    if ($result['invitee_status'] == 0) {
                        $guest_status = $data['invitee_status'] = 3;
                    }
                } else {
                    $data['invitee_status'] = 1;
                    $guest_status = $result['inviter_status'];
                    if ($result['inviter_status'] == 0) {
                        $guest_status = $data['inviter_status'] = 3;
                    }
                }
                $res = $buddiesmodel -> where(['id' => $result['id']]) -> save($data);
                if ($res > 0) {
                    if ($guest_status == 1) {
                        $this -> new_set_message(200, "成功向对方发送好友请求", []);
                    } else {
                        $this -> new_set_message(200, "成功向对方发送好友请求", []);
                    }
                } else {
                    $this -> new_set_message(1137, "您已经发送过请求了 请耐心等待", []);
                }

            }

        } else {
            $usermodel = M('user', 'tab_');
            $user = $usermodel -> field('account') -> where(['id' => $user_id]) -> find();
            $guest = $usermodel -> field('account') -> where(['id' => $guest_id]) -> find();
            $data = array(
                    'inviter_id' => $user_id,
                    'inviter_account' => $user['account'],
                    'invitee_id' => $guest_id,
                    'invitee_account' => $guest['account'],
                    'inviter_status' => 1,
                    'invitee_status' => 2,
                    'message' => $message,
                    'create_time' => time(),
            );
            $res = $buddiesmodel -> add($data);
            if ($res > 0) {
                $this -> new_set_message(200, "成功向对方发送好友请求", []);
            } else {
                $this -> new_set_message(1018, "发送失败", []);
            }

        }


    }

    /**
     * 同意添加好友
     *
     * @author 鹿文学
     */
    public function agree_buddies()
    {

        $request = json_decode(base64_decode(file_get_contents("php://input")), true);
        $buddiesmodel = M('buddies', 'tab_');
        $guest_id = $request['guest_id'];
        $user_id = $request['user_id'];
        $agree = $request['agree'] == 1 ? $request['agree'] : 0;
        $map['_string'] = "(inviter_id = {$user_id} and invitee_id = {$guest_id})";
        $map['_complex'] = array('inviter_id' => $guest_id, 'invitee_id' => $user_id);
        $map['_logic'] = 'or';
        $result = $buddiesmodel -> where($map) -> find();
        if (!empty($result)) {
            if ($result['inviter_status'] == 1 && $result['invitee_status'] == 1) {
                $this -> new_set_message(1136, "您已与" . ($result['inviter_id'] == $user_id ? $result['invitee_account'] : $result['inviter_account']) . "成为好友", ['unread_count' => get_buddies_unagree_count($user_id)]);
                exit;
            } else {

                if ($result['inviter_id'] == $user_id) {
                    $data['inviter_status'] = $agree;
                    $data['invitee_status'] = 1;
                    $guest_account = $result['invitee_account'];
                } else {
                    $data['invitee_status'] = $agree;
                    $data['inviter_status'] = 1;
                    $guest_account = $result['inviter_account'];
                }
                $res = $buddiesmodel -> where(['id' => $result['id']]) -> save($data);
                if ($res > 0) {
                    $this -> new_set_message(200, $agree == 1 ? "您已与" . $guest_account . "成为好友" : '', ['unread_count' => get_buddies_unagree_count($user_id)]);
                } else {
                    $this -> new_set_message(0, $agree == 1 ? "添加好友失败" : '', ['unread_count' => get_buddies_unagree_count($user_id)]);
                }


            }
        } else {

            $this -> new_set_message(1135, "没有此好友信息", ['unread_count' => get_buddies_unagree_count($user_id)]);

        }

    }

    /**
     * 获取好友请求列表
     *
     * @author 鹿文学
     */
    public function get_buddies_request_list()
    {

        $request = json_decode(base64_decode(file_get_contents("php://input")), true);
        $userid = $request['user_id'];
        $gameid = $request['game_id'];
        $buddiesmodel = M('buddies', 'tab_');
        $map['_string'] = "(inviter_id = {$userid} and inviter_status in(2,3) and invitee_status=1 )";
        $map['_complex'] = array('invitee_id' => $userid, 'invitee_status' => array('in', '2,3'), 'inviter_status' => 1);
        $map['_logic'] = 'or';
        $list = $buddiesmodel -> alias('b') -> field('n.user_id,n.user_account,if(n.user_nickname="",n.user_account,n.user_nickname) as user_nickname,if(n.head_img="","",n.head_img) as head_img,n.game_status,ifnull(max(up.role_level),0) as role_level')
                -> join("inner join tab_nearby as n on((b.invitee_id=n.user_id and b.inviter_id = {$userid}) or (b.inviter_id=n.user_id and b.invitee_id={$userid}) ) ")
                -> join("left join tab_user_play as up on(((up.ppuid=b.invitee_id or up.user_id=b.invitee_id and b.inviter_id = {$userid}) or (up.ppuid=b.inviter_id or up.user_id=b.inviter_id and b.invitee_id = {$userid})) and up.game_id = {$gameid}) ")
                -> where($map) -> group('n.user_id') -> order('role_level desc,b.create_time desc') -> select();
        $this -> new_set_message(200, "", is_array($list) ? $list : []);

    }

    /**
     * 获取好友列表(游戏好友)
     *
     * @author 鹿文学
     */
    public function get_buddies_list()
    {

        $request = json_decode(base64_decode(file_get_contents("php://input")), true);
        $userid = $request['user_id'];
        $gameid = $request['game_id'];
        $buddiesmodel = M('buddies', 'tab_');
        $map['_string'] = "(inviter_id = {$userid} and inviter_status=1 and invitee_status in(0,1,3) )";
        $map['_complex'] = array('invitee_id' => $userid, 'invitee_status' => 1, 'inviter_status' => ['in', '0,1,3']);
        $map['_logic'] = 'or';
        $list = $buddiesmodel -> alias('b') -> field("n.user_id,n.user_account,if(n.user_nickname='',n.user_account,n.user_nickname) as user_nickname,if(n.head_img='','',n.head_img) as head_img,n.game_status,ifnull(max(up.role_level),0) as role_level,if(b.inviter_id = {$userid},invitee_status,inviter_status)+5 as buddies_status")
                -> join("left join tab_nearby as n on((b.invitee_id=n.user_id and b.inviter_id = {$userid}) or (b.inviter_id=n.user_id and b.invitee_id={$userid}) ) ")
                -> join("left join tab_user_play as up on(((up.ppuid=b.invitee_id or up.user_id=b.invitee_id and b.inviter_id = {$userid}) or (up.ppuid=b.inviter_id or up.user_id=b.inviter_id and b.invitee_id = {$userid})) and up.game_id = {$gameid}) ")
                -> where($map) -> group('n.user_id') -> order('role_level desc') -> select();
        $this -> new_set_message(200, "", is_array($list) ? $list : []);


    }

    /**
     * 好友聊天列表(站内信)
     *
     * @author 鹿文学
     */
    public function get_buddies_chat_list()
    {

        $request = json_decode(base64_decode(file_get_contents("php://input")), true);
        $userid = $request['user_id'];
        $gameid = $request['game_id'];
        $guestids = is_array($request['guest_ids']) ? implode(',', $request['guest_ids']) : $request['guest_ids'];
        $buddiesmodel = M('buddies', 'tab_');
        $map['_string'] = "(inviter_id = {$userid} and invitee_id in ({$guestids}) and inviter_status=1 and invitee_status in(0,1,3) )";
        $map['_complex'] = array('invitee_id' => $userid, 'inviter_id' => ['in', $guestids], 'invitee_status' => 1, 'inviter_status' => ['in', '0,1,3']);
        $map['_logic'] = 'or';
        $list = $buddiesmodel -> alias('b') -> field('n.user_id,n.user_account,if(n.user_nickname="",n.user_account,n.user_nickname) as user_nickname,if(n.head_img="","",n.head_img) as head_img,n.game_status,ifnull(max(up.role_level),0) as role_level')
                -> join("left join tab_nearby as n on((b.invitee_id=n.user_id and b.inviter_id = {$userid}) or (b.inviter_id=n.user_id and b.invitee_id={$userid}) ) ")
                -> join("left join tab_user_play as up on(((up.ppuid=b.invitee_id or up.user_id=b.invitee_id and b.inviter_id = {$userid}) or (up.ppuid=b.inviter_id or up.user_id=b.inviter_id and b.invitee_id = {$userid})) and up.game_id = {$gameid}) ")
                -> where($map) -> group('n.user_id') -> order('role_level desc') -> select();
        $this -> new_set_message(200, "", is_array($list) ? $list : []);


    }


    /**
     * 删除好友
     *
     * @author 鹿文学
     */
    public function del_buddies()
    {

        $request = json_decode(base64_decode(file_get_contents("php://input")), true);
        $buddiesmodel = M('buddies', 'tab_');
        $guest_id = $request['guest_id'];/* 要删除的好友编号 */
        $user_id = $request['user_id'];
        $map['_string'] = "(inviter_id = {$user_id} and invitee_id = {$guest_id})";
        $map['_complex'] = array('inviter_id' => $guest_id, 'invitee_id' => $user_id);
        $map['_logic'] = 'or';
        $result = $buddiesmodel -> where($map) -> find();
        if (!empty($result)) {

            if ($result['inviter_id'] == $user_id) {
                $data['inviter_status'] = 0;
            } else {
                $data['invitee_status'] = 0;
            }
            $res = $buddiesmodel -> where(['id' => $result['id']]) -> save($data);
            if ($res > 0) {
                $this -> new_set_message(200, "删除成功", []);
            } else {
                $this -> new_set_message(1054, "删除失败", []);
            }

        } else {

            $this -> new_set_message(1135, "没有此好友信息", []);

        }

    }

    /**
     * @函数或方法说明
     * @获取后端版本
     * @author: 郭家屯
     * @since: 2019/5/24 10:16
     */
    public function get_php_version()
    {
        $res_msg = array(
                "status" => 200,
                "return_code" => "success",
                "return_msg" => "获取成功",
                "php_version" => 631,
        );
        echo base64_encode(json_encode($res_msg));
        exit;
    }

}