<?php

namespace Mobile\Controller;

use Org\XiguSDK\Xigu;
use User\Api\SuserApi;
use Org\UcenterSDK\Ucservice;
use User\Api\MemberApi;
use Admin\Model\PointTypeModel;
use Think\Log;
use Base\Tool\TaskClient;
use Base\Service\UserService;

class UserController extends BaseController
{
    private $suser;

    public function __construct()
    {
        parent::__construct();
        $this->suser = new SuserApi;
    }

    public function asd()
    {
        var_dump(sendMail("894827077@qq.com", "测试啊", "成都市"));
        die;

    }

    /**
     * 登录
     * @return [type] [description]
     * @author wyr <840186209@qq.com>
     */
    public function login()
    {
        if (IS_POST) {
            $post = I('post.');
            $account = $post['phone'];
            $password = $post['password'];

            $promoteId = I('post.promote_id');
            $promoteId = intval($promoteId);

            $member = new MemberApi();

            /*是否开启Ucenter*/
            if (C('UC_OPEN') == 1) {
                $username = $account;

                //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)) {//本地存在账号,验证密码直接登录

                        $res = $this->suser->login($account, $password);
                        if ($res > 0) {
                            $data = $this->bindingPromote($promoteId, $account);
                        } else {
                            switch ($res) {
                                case -1000:
                                    $error = '账号不存在';
                                    break;
                                case -10021:
                                    $error = '密码错误!';
                                    break;
                                case -1001:
                                    $error = '账号被禁用,请联系客服!';
                                    break;
                                default:
                                    $error = '未知错误!';
                                    break;
                            }
                            $data = array(
                                'status' => 0,
                                'msg' => $error,
                            );
                        }
                        echo json_encode($data);
                        die();

                    } else {//本地不存在账号,新增账号并登录


                        $resdata = array();
                        $resdata['account'] = trim($username);
                        $resdata['nickname'] = trim($username);
                        $resdata['password'] = $password;
                        $resdata['register_way'] = 3;
                        $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'] = '';

                        $res = $this->suser->register_array($resdata);

                        if ($res > 0) {

                            $res = $this->suser->login($account, $password);
                            if ($res > 0) {
                                $data = array(
                                    'status' => 1,
                                    'msg' => '登录成功',
                                );
                            } else {
                                switch ($res) {
                                    case -1000:
                                        $error = '账号不存在';
                                        break;
                                    case -10021:
                                        $error = '密码错误!';
                                        break;
                                    case -1001:
                                        $error = '账号被禁用,请联系客服!';
                                        break;
                                    default:
                                        $error = '未知错误!';
                                        break;
                                }
                                $data = array(
                                    'status' => 0,
                                    'msg' => $error,
                                );
                            }
                            echo json_encode($data);
                            die();

                        } else {
                            $msg = $res == -3 ? "账号已存在" : "身份证被占用";
                            return $this->ajaxReturn(array('status' => 0, 'msg' => $msg));
                        }
                    }

                } elseif ($uc_uid == -1) {
                    //用户不存在,验证本地用户账号密码
                    $res = $this->suser->login($account, $password);
                    if ($res > 0) {
                        $data = $this->bindingPromote($promoteId, $account);

                        //同步ucenter注册
                        cus_uc_register($username, $password, $username . '@vlcms.com');
                    } else {
                        switch ($res) {
                            case -1000:
                                $error = '账号不存在';
                                break;
                            case -10021:
                                $error = '密码错误!';
                                break;
                            case -1001:
                                $error = '账号被禁用,请联系客服!';
                                break;
                            default:
                                $error = '未知错误!';
                                break;
                        }
                        $data = array(
                            'status' => 0,
                            'msg' => $error,
                        );
                    }
                    echo json_encode($data);
                    die();
                } elseif ($uc_uid == -2) {
                    //密码错误
                    $this->ajaxReturn(array('status' => -1002, 'code' => -10021, 'msg' => '密码错误'));
                } else {
                    //登录失败
                }
            }

            $res = $this->suser->login($account, $password);
            if ($res > 0) {
                $data = $this->bindingPromote($promoteId, $account);
            } else {
                switch ($res) {
                    case -1000:
                        $error = '账号不存在';
                        break;
                    case -10021:
                        $error = '密码错误!';
                        break;
                    case -1001:
                        $error = '账号被禁用,请联系客服!';
                        break;
                    default:
                        $error = '未知错误!';
                        break;
                }
                $data = array(
                    'status' => 0,
                    'msg' => $error,
                );
            }
            echo json_encode($data);
            die();
        } else {
            $pid = I('get.pid', 0);
            $gid = I('get.gid', 0);
            $from = I('get.from', "");
            if ($pid > 0 || $gid > 0) {
                cookie('pgInfo', json_encode(['pid' => $pid, 'gid' => $gid]), 3600 * 24);
            }
            if ($_REQUEST['url']) {
                $this->assign('url', base64_decode(base64_decode($_REQUEST['url'])));
            } else {
                $this->assign('url', U('User/index'));
            }
            $this->display();
        }
    }

    public function bindingPromote($promoteId, $account)
    {
        if ($promoteId > 0) {
            $wherePromote['id'] = $promoteId;
            $promoteData = M('Promote', 'tab_')->field('id,account')->where($wherePromote)->find();

            if (!empty($promoteData)) {
                $whereUser['account'] = $account;
                $whereUser['_logic'] = 'or';
                $whereUser['mobile_phone'] = $account;
                $userData = M('User', 'tab_')->where($whereUser)->find();

                if (!empty($userData)) {
                    if (empty($userData['promote_id'])) {
                        $saveData['promote_id'] = $promoteId;
                        $saveData['promote_account'] = $promoteData['account'];

                        $saveRes = M('User', 'tab_')->where(array('id' => $userData['id']))->save($saveData);
                        if ($saveRes) {
                            $data = array('status' => 2, 'msg' => '登录成功');
                        } else {
                            $data = array('status' => 0, 'msg' => '绑定失败');
                        }
                    } else {
                        if ($userData['promote_id'] == $promoteId) {
                            $data = array('status' => 2, 'msg' => '登录成功');
                        } else {
                            $data = array('status' => 2, 'msg' => '登录成功');
                        }
                    }
                } else {
                    $data = array('status' => 0, 'msg' => '数据异常');
                }
            } else {
                $data = array('status' => 0, 'msg' => '数据异常');
            }
        } else {
            $data = array('status' => 1, 'msg' => '登录成功');
        }

        return $data;
    }

    /**
     * 注册步骤一 填写用户名和密码
     * @return [type] [description]
     * @author wyr <840186209@qq.com>
     */
    public function step()
    {
        if (IS_POST) {
            $post = I('post.');
            $account = $post['nickname'];
            $password = $post['password'];
            $sex = isset($post['sex']) ? $post['sex'] : 0;
            if (empty($account)) {
                echo json_encode(array('status' => 0, 'msg' => '请填写昵称'));
                exit;
            }
            if (empty($password)) {
                echo json_encode(array('status' => 0, 'msg' => '请输入密码'));
                exit;
            }

            $promoteId = I('post.promote_id');
            $promoteId = intval($promoteId);
            if ($promoteId > 0) {
                $gameId = intval(I('post.game_id'));
                $safeinfo = array('nickname' => $account, 'password' => $password, 'sex' => $sex, 'status' => 1, 'promote_id' => $promoteId, 'game_id' => $gameId);
            } else {
                $safeinfo = array('nickname' => $account, 'password' => $password, 'sex' => $sex, 'status' => 1);
            }
            session('safeinfo', $safeinfo);
            $url = U('register');

            echo json_encode(array('status' => 1, 'msg' => $url));
        } else {
            $this->display();
        }
    }


    /**
     * 注册
     * @return [type] [description]
     * @author wyr <840186209@qq.com>
     */
    public function register()
    {
//        $safeinfo = session('safeinfo');
//        if ($safeinfo['status'] == 1) {
            if (IS_POST) {

                $post = I('post.');
                $account = $post['phone'];
                $password = $post['password'];
                $sex = isset($post['sex']) ? $post['sex'] : 0;
                if (empty($account)) {
                    echo json_encode(array('status' => 0, 'msg' => '请输入手机号'));
                    exit;
                }
                if (empty($password)) {
                    echo json_encode(array('status' => 0, 'msg' => '请输入密码'));
                    exit;
                }

                $promoteId = I('post.promote_id');
                $promoteId = intval($promoteId);
                if ($promoteId > 0) {
                    $gameId = intval(I('post.game_id'));
                    $safeinfo = array('nickname' => $account, 'password' => $password, 'sex' => $sex, 'status' => 1, 'promote_id' => $promoteId, 'game_id' => $gameId);
                } else {
                    $safeinfo = array('nickname' => $account, 'password' => $password, 'sex' => $sex, 'status' => 1);
                }

                $phone = $post['phone'];
                $safecode = $post['code'];
                $nickname = 'U_' . substr($safeinfo['nickname'],-4);
                $password = $safeinfo['password'];
                $sex = $safeinfo['sex'];

                if (!$this->checksafecode($phone, $safecode)) {
                    return $this->ajaxReturn(array('status' => 0, 'msg' => '验证失败'));
                }


                /**是否开启ucenter**/
                if (C('UC_OPEN') == 1) {
                    $userService = new UserService();
                    if ($userService->isAccountExist($phone)) {
                        return $this->ajaxReturn(array('status' => 0, 'msg' => '用户名已存在'));
                    }

                    //3.ucenter注册账号
                    $ucresult = uc_user_checkname($phone);
                    if ($ucresult == -1) {
                        $this->ajaxReturn(array('status' => 0, 'msg' => '用户名不合法'));
                        exit;
                    } elseif ($ucresult == -2) {
                        $this->ajaxReturn(array('status' => 0, 'msg' => '包含要允许注册的词语'));
                        exit;
                    } elseif ($ucresult == -3) {
                        $this->ajaxReturn(array('status' => 0, 'msg' => '用户名已经存在'));
                        exit;
                    } else {
                        //同步ucenter注册
                        cus_uc_register($phone, $password, $phone . '@vlcms.com');
                    }

                }

                $register_way = 4;
                $register_type = 2;
                switch ($sex) {
                    case '0':
                        $head_img = "http://" . $_SERVER['HTTP_HOST'] . '/Public/Mobile/images/logoo.png';
                        break;
                    default:
                        $head_img = "http://" . $_SERVER['HTTP_HOST'] . '/Public/Mobile/images/head_women@3x.png';
                        break;
                }

                if (!preg_match("/^1[345789]\d{9}$/", $phone)) {
                    echo json_encode(['status' => 0, 'msg' => '手机号格式不正确']);
                    die;
                }

                if (!preg_match("/^[a-zA-Z0-9]{6,15}+$/", $password)) {
                    echo json_encode(['status' => 0, 'msg' => '密码格式不正确']);
                    die;
                }
                $pgInfo = strval(cookie('pgInfo'));
                Log::write('register:' . date('Y-m-d H:i:s') . ' ---- ' . json_encode($_POST) . ' --- ' . $pgInfo, 'INFO');
                if (isset($_POST['promote_id']) && !empty($_POST['promote_id'])) {
                    Log::write('cxj_register:' . date('Y-m-d H:i:s') . ' ---- post' . json_encode($_POST) .' --- INFO');
                    $thisPromoteAccount = M('promote', 'tab_')->where(array('id' => $_POST['promote_id']))->getField('account');
                    $thisPromoteAccount = !empty($thisPromoteAccount) ? $thisPromoteAccount : '自然注册';
                    $promoteAccount = isset($_POST['promote_account']) ? $_POST['promote_account'] : $thisPromoteAccount;
                    $pid = $this->suser->register($phone, $password, $phone, $register_way, $register_type, $_POST['promote_id'], $promoteAccount, $sex, $nickname, $head_img);
                } else {
                    $pid = $this->suser->register($phone, $password, $phone, $register_way, $register_type, '', '', $sex, $nickname, $head_img);
                }
                if ($pid > 0) {
                    $taskClient = new TaskClient();
                    $taskClient->registerEvent($pid, 'WAP');
                    if (empty($safeinfo['promote_id'])) {
                        $data = array(
                            'status' => 1,
                            'msg' => '注册成功',
                            'url' => U('Index/index'),
                        );
                    } else {
                        $data = array(
                            'status' => 1,
                            'msg' => '注册成功',
                            'url' => U('User/login', array('pid' => $safeinfo['promote_id'], 'gid' => $safeinfo['game_id'])),
                        );
                    }
                    session('safeinfo', null);
                } else {
                    $data = array(
                        'status' => $pid,
                        'msg' => '注册失败',
                    );
                }
                echo json_encode($data);
            } else {
                $pid = I('get.pid', 0);
                $gid = I('get.gid', 0);
                if ($pid > 0 || $gid > 0) {
                    cookie('pgInfo', json_encode(['pid' => $pid, 'gid' => $gid]), 3600 * 24);
                }

                if ($_REQUEST['url']) {
                    $url = base64_decode($_REQUEST['url']);
                } else {
                    $url = $_SERVER['HTTP_REFERER'];
                }
                $this->assign('url', $url);
                $this->display();
            }
//        } else {
//            $this->redirect(U('step'));
//        }
    }

    /**
     * 账号注册
     * @return [type] [description]
     * @author 郭家屯
     */
    public function step1()
    {
        if (IS_POST) {
            $post = I('post.');
            $account = $post['account'];
//            $nickname = $post['nickname'];
            $nickname = 'U_' . substr($account,-4);;
            $password = $post['password'];
            $sex = $post['sex'];

            $pgInfo = strval(cookie('pgInfo'));
            Log::write('step1:' . date('Y-m-d H:i:s') . ' ---- ' . json_encode($post) . ' --- ' . $pgInfo, 'INFO');


            /**是否开启ucenter**/
            if (C('UC_OPEN') == 1) {
                $userService = new UserService();
                if ($userService->isAccountExist($account)) {
                    return $this->ajaxReturn(array('status' => 0, 'msg' => '用户名已存在'));
                }

                //3.ucenter注册账号
                $ucresult = uc_user_checkname($_POST['account']);
                if ($ucresult == -1) {
                    $this->ajaxReturn(array('status' => 0, 'msg' => '用户名不合法'));
                    exit;
                } elseif ($ucresult == -2) {
                    $this->ajaxReturn(array('status' => 0, 'msg' => '包含要允许注册的词语'));
                    exit;
                } elseif ($ucresult == -3) {
                    $this->ajaxReturn(array('status' => 0, 'msg' => '用户名已经存在'));
                    exit;
                } else {
                    //同步ucenter注册
                    cus_uc_register($_POST['account'], $_POST['password'], $_POST['account'] . '@vlcms.com');
                }
            }


            $register_way = 4;
            $register_type = 1;
            switch ($sex) {
                case '0':
                    $head_img = "http://" . $_SERVER['HTTP_HOST'] . '/Public/Mobile/images/logoo.png';
                    break;
                default:
                    $head_img = "http://" . $_SERVER['HTTP_HOST'] . '/Public/Mobile/images/head_women@3x.png';
                    break;
            }
            $map['account'] = $account;
            $map['phone'] = $account;
            $map['_logic'] = "or";
            $is_setting = M("user", "tab_")->where($map)->field("id")->find();
            if ($is_setting) {
                echo json_encode(array('status' => 0, 'msg' => '账号已存在'));
                exit;
            }

            if (!preg_match("/^[a-z\d]{6,15}$/i", $account)) {
                echo json_encode(['status' => 0, 'msg' => '账号格式不正确']);
                die;
            }

            if (!preg_match("/^[a-zA-Z0-9]{6,15}+$/", $password)) {
                echo json_encode(['status' => 0, 'msg' => '密码格式不正确']);
                die;
            }

            $pid = $this->suser->register($account, $password, '', $register_way, $register_type, '', '', $sex, $nickname, $head_img);

            if ($pid > 0) {

                $taskClient = new TaskClient();
                $taskClient->registerEvent($pid, 'WAP');

                $promoteId = I('post.promote_id');
                $promoteId = intval($promoteId);

                if ($promoteId > 0) {
                    $gameId = intval(I('post.game_id'));

                    $data = array(
                        'status' => 1,
                        'msg' => '注册成功',
                        'url' => U('User/login', array('pid' => $promoteId, 'gid' => $gameId)),
                    );
                } else {
                    $data = array(
                        'status' => 1,
                        'msg' => '注册成功',
                        'url' => U('Index/index'),
                    );
                }
            } else {
                $data = array(
                    'status' => $pid,
                    'msg' => '注册失败',
                );
            }
            echo json_encode($data);
            exit;
        }
        $this->display();
    }

    /**
     * 发动手机验证码
     */
    public function telsafecode($phone = '', $delay = 10, $flag = true)
    {
        $taskClient = new TaskClient();
        $result = $taskClient->sendSmsCode($phone, get_client_ip());
        $data = [];
        if ($result['code'] == TaskClient::SUCCESS) {
            $data['status'] = 1;
        } else {
            $data['status'] = 0;
        }
        $data['msg'] = $result['message'];
        echo json_encode($data);
        exit;
    }

    /**
     * 发送安全码
     */
    public function sendsafecode($phone, $delay = 10)
    {
        if (IS_POST) {

            $res = $this->suser->checkAccount($phone);
            if (!$res) {
                echo json_encode(array('status' => 0, 'msg' => '手机号码被占用'));
                exit;
            }
            $this->telsafecode($phone);
            exit;
        } else {
            echo json_encode(array('status' => 0, 'msg' => '请按正确的流程'));
            exit;
        }
    }

    /**
     * 手机安全码验证
     */
    public function checksafecode($phone, $code)
    {
        $taskClient = new TaskClient();
        $result = $taskClient->checkSms($phone, $code);
        $data = [];
        if ($result && $result['code'] == TaskClient::SUCCESS) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 忘记密码
     * @return [type] [description]
     * @author wyr <840186209@qq.com>
     */
    public function forget()
    {
        if (IS_POST) {

            $phone = $_POST['phone'];
            $code = $_REQUEST['code'];

            if (!$this->checksafecode($phone, $code)) {
                return $this->ajaxReturn(array('status' => 0, 'msg' => '验证失败'));
            }

            $this->success('验证成功', U('User/forget1', array('phone' => $phone)));


        } else {
            $this->display();
        }

    }

    public function forget1()
    {
        if (IS_POST) {
            $new_pwd = $_REQUEST['new_pwd'];
            $u_uid['phone'] = $_REQUEST['phone'];
            $code = $_REQUEST['code'];
            //验证短信验证码
            if (!$this->checksafecode($u_uid['phone'], $code)) {
                $this->error("验证失败");
            }
            $user = M('user', 'tab_')->where($u_uid)->find();
            if (!$user) {
                $this->error("账号不存在");
            }

            $result = M('user', 'tab_')->where($u_uid)->setField('password', think_ucenter_md5($new_pwd, UC_AUTH_KEY));
            if ($result != false) {
                $this->success("修改成功", U('User/login'));
            } elseif ($result === 0) {
                $this->error("新密码和旧密码一致,请重新输入");
            } else {
                $this->error("修改失败");
            }
        } else {
            $this->display();
        }
    }

    /**
     * 忘记密码发送短信
     * @param $account
     * author: xmy 280564871@qq.com
     */
    public function forget_send_msg($account)
    {
        $data = D("User")->getUserInfo($account);
        if (C('UC_SET') == 1) {
            $uc = new Ucservice();
            $data_uc = $uc->get_uc($account);
            if (empty($data) && !empty($data_uc)) {
                $this->error("UC用户不支持");
            }
        }
        if (empty($account)) {
            echo json_encode(array('status' => 0, 'msg' => '账号不存在'));
            exit;
        } elseif (empty($data['phone'])) {
            echo json_encode(array('status' => 0, 'msg' => '该用户未绑定手机号'));
            exit;
        }
        $result = $this->telsafecode($account);
    }

    /**
     * 判断是否登录
     * @return [type] [description]
     */
    public function islogin()
    {

        $user = $this->suser->login_info();

        if ($user) {

            if ($user['nickname']) {
                $account = $user['nickname'];
            } else {
                $account = $user['account'];
            }
            return $user['user_id'];

        } else {
            return 0;
        }
    }

    /**
     * 个人中心首页
     * @return [type] [description]
     * @author wyr <840186209@qq.com>
     */
    /* public function index() {

        if(!$this->islogin()){$this->redirect('Mobile/User/login');}
        $session = session('user_auth');
        $user = D('User')->where(array('id'=>$session['user_id']))->find();
        $headimg = $user['head_img'];
        $user['head_img'] = is_numeric($headimg)?get_cover($headimg,'path'):$headimg;
        $this->assign('user',$user);
        $this->show_sing_in($session['user_id']);
        $this->display();
    } */

    /**
     * 个人中心
     * @author 鹿文学
     */
    public function index()
    {
        if (!$this->islogin()) {
            $this->redirect('Mobile/User/login');
        }
        $user = D('User')->getInfo();
        $this->assign('user', $user);
        $this->show_sing_in($user['id']);
        $this->display();
    }

    public function show_sing_in($user_id)
    {
        $type = D('PointRecord')->getPointType("sign_in");
        if (!$type) {
            return false;
        }
        $base_point = $type['point'];
        $increase_point = $type['time_of_day'];
        $record = D('PointRecord')->getSignInInfo($user_id, $type['id']);
        //计算间隔时间
        $today = strtotime(date("Y-m-d"));
        $time = strtotime(date("Y-m-d", $record['create_time']));
        $day = ($today - $time) / 86400;
        if ($day == 1) {//昨日积分 + 递增积分
            $add_point = $record['point'] + $increase_point;
            //超过7天 重新计算
            if ($record['day'] >= 7) {
                $add_point = $base_point;
                $sign_day = 1;
            } else {
                $sign_day = $record['day'];
            }
            $data['point'] = $add_point;
        } elseif ($day == 0) {
            $add_point = $record['point'] + $increase_point;
            $data['point'] = $add_point;
            $sign_day = 1;
        } else {//基础积分
            $data['point'] = $base_point;
            $sign_day = 0;
        }
        $this->assign('point', $data['point']);
        $this->assign('sign_day', $sign_day);
        $this->assign('day', $day);
    }

    public function sign_in()
    {


        $user_id = $this->islogin();

        $model = D('PointRecord');
        $result = $model->addPointBySignIn($user_id);
        if ($result !== false) {
            $data['day'] = $result;
            $this->success("签到成功", $data);
        } else {
            $this->error($model->getError());
        }
    }


    /**
     * 个人中心->编辑资料
     * @return [type] [description]
     * @author wyr <840186209@qq.com>
     */
    public function userset()
    {
        if (!$this->islogin()) {
            $this->redirect('Mobile/User/login');
        }


        $logininfo = $this->suser->login_info();

        $user = D('User')->where(array('id' => $logininfo['user_id']))->find();
        if (is_numeric($user['head_img'])) {
            $user['head_img'] = get_cover($user['head_img'], "path");
        }
        $this->assign('user', $user);
        $this->display();
    }

    /**
     * 个人中心->编辑资料->修改昵称
     * @return [type] [description]
     * @author 小纯洁
     */
    public function usernick()
    {
        if (!$this->islogin()) {
            $this->redirect('Mobile/User/login');
        }


        $logininfo = $this->suser->login_info();

        if (IS_POST) {
            $map['id'] = $logininfo['user_id'];
            $model = D('User')->where($map)->save(array('nickname' => $_REQUEST['nickname']));

            $this->suser->set_login_info('nickname', $_REQUEST['nickname']);

            if ($model !== false) {
                $this->success("修改成功", U('User/userset'));
            } else {
                $this->error("修改失败");
            }
        } else {
            $this->assign('user', $logininfo);
            $this->display();
        }
    }

    /**
     * 个人中心->编辑资料->绑定/解除手机
     * @return [type] [description]
     * @author 郭家屯
     */
    public function userphone()
    {
        if (!$this->islogin()) {
            $this->redirect('Mobile/User/login');
        }
        $logininfo = $this->suser->login_info();
        $map['id'] = $logininfo['user_id'];
        $user = M("user", "tab_")->where($map)->field("id,phone")->find();
        if (IS_POST) {
            $code = I("post.scode");
            $phone = I("post.phone");
            if (!$this->checksafecode($phone, $code)) {
                echo json_encode(array('status' => 0, 'msg' => '验证失败'));
                exit();
            }
            if (!$user['phone']) {
                $where['account'] = $phone;
                $where['phone'] = $phone;
                $condition['_complex'] = $where;
                $condition['id'] = array("neq", $user['id']);
                $is_user = M("user", "tab_")->where($condition)->field("id")->find();
                if ($is_user) {
                    echo json_encode(array('status' => 0, 'msg' => '手机号已存在,请更换手机号'));
                    exit();
                }
                $model = M('User', 'tab_')->where($map)->save(array('phone' => $phone));
            } else {
                $model = M('User', 'tab_')->where($map)->save(array('phone' => ''));
            }
            $this->suser->set_login_info('phone', $_REQUEST['phone']);

            if ($model !== false) {
                echo json_encode(array('status' => 1, 'msg' => '修改成功', 'url' => U('User/userset')));
                exit();
            } else {
                echo json_encode(array('status' => 0, 'msg' => '修改失败'));
                exit();
            }
        } else {
            $this->assign('user', $user);
            $this->display();
        }
    }

    /**
     *发送验证码请求
     * @author 郭家屯
     */
    public function sendvcode()
    {
        if (!IS_POST) {
            echo json_encode(array('status' => 0, 'msg' => '请按正确的流程'));
            exit;
        }

        $logininfo = $this->suser->login_info();
        if ($logininfo['nickname'] == "Uc用户") {
            echo json_encode(array('status' => 0, 'msg' => 'Uc用户暂不支持'));
            exit();
        }
        if (!$this->islogin()) {
            $this->redirect('Mobile/User/login');
        }
        $phone = I('phone');
        $map['id'] = $logininfo['user_id'];
        $user = M("user", "tab_")->where($map)->field("id,phone")->find();
        if (!$user['phone']) {
//            $where['account'] = $phone;
            $where['phone'] = $phone;
//            $where['_logic'] = 'OR';
            $is_user = M("user", "tab_")->where($where)->field("id")->find();
            if ($is_user) {
                echo json_encode(array('status' => 0, 'msg' => '手机号已存在,请更换手机号'));
                exit();
            }
        }
        $this->telsafecode($phone);
    }

    /**
     * 个人中心->编辑资料->修改性别
     * @return [type] [description]
     * @author 小纯洁
     */
    public function usersex()
    {
        if (!$this->islogin()) {
            $this->redirect('Mobile/User/login');
        }

        $logininfo = $this->suser->login_info();
        if (IS_POST) {
            $map['id'] = $logininfo['user_id'];
            $sex = $_REQUEST['sex'];
            $user = D('User')->where($map)->find();
            $img_url = strstr($user['head_img'], "http://");
            if ($img_url) {
                switch ($sex) {
                    case '0':
                        $head_img = "http://" . $_SERVER['HTTP_HOST'] . '/Public/Mobile/images/logoo.png';
                        break;
                    default:
                        $head_img = "http://" . $_SERVER['HTTP_HOST'] . '/Public/Mobile/images/head_women@3x.png';
                        break;
                }
            } else {
                $head_img = $user['head_img'];
            }
            $model = D('User')->where($map)->save(array('sex' => $sex, 'head_img' => $head_img));
            if ($model !== false) {
                $this->success("修改成功", U('User/userset'));
            } else {
                $this->error("修改失败");
            }
        } else {
            $user = D('user')->field("sex")->find($logininfo['user_id']);
            $this->assign('user', $logininfo);
            $this->assign('sex', $user['sex']);
            $this->display();
        }
    }

    /**
     * 个人中心->编辑资料->实名认证
     * @return [type] [description]
     * @author 小纯洁
     */
    public function userauth()
    {
        if (!$this->islogin()) {
            $this->redirect('Mobile/User/login');
        }

        $logininfo = $this->suser->login_info();
        

        if (IS_POST) {
            $resdata['age_status'] = 0;
            $map['id'] = $logininfo['user_id'];

            if (isset($_POST['idcard'])) {
                $checkidcard = new \Think\Checkidcard();
                $invidcard = $checkidcard->checkIdentity($_POST['idcard']);
                if (!$invidcard) {
                    $this->ajaxReturn(array('status' => -1, 'info' => '身份证号码填写不正确', 'url' => U('User/userauth')));
                }
                // $cardd = M('User', 'tab_')->where(array('idcard' => $_POST['idcard']))->find();
                // if ($cardd) {
                //     $this->ajaxReturn(array('status' => -1, 'info' => '身份证号码已被使用', 'url' => U('User/userauth')));
                // }
            }
            $status = M("Tool","tab_")->field("status")->where("name = 'tool_age'")->find()['status'];
            if ($status == 0) {
                $this->ajaxReturn(array('status' => 0, 'info' => '实名认证暂未开启!', 'url' => U('User/userauth')));
            } else {
                //PC_REAL_NAME_REGISTER
                $ages =  M("Config")->where("name = 'PC_REAL_NAME_REGISTER'")->field("value")->find()['value'];
                
                if($ages == "1"){
                    $re =age_verify($_REQUEST['idcard'],$_REQUEST['real_name']);
                    if ($re == 0) {
                        $this->ajaxReturn(array('status' => 0, 'info' => '审核失败!', 'url' => U('User/userauth')));
                    }
                    if ($re == -1) {
                        $this->ajaxReturn(array('status' => 0, 'info' => '短信数量已使用完!', 'url' => U('User/userauth')));
                    }
                    if ($re == "202") {
                        $this->ajaxReturn(array('status' => 0, 'info' => '无法验证!【中心中无此身份证记录,军人转业,户口迁移等】', 'url' => U('User/userauth')));
                    }
                    if ($re == "203") {
                        $this->ajaxReturn(array('status' => 0, 'info' => '异常情况!', 'url' => U('User/userauth')));
                    }
                    if ($re == "204") {
                        $this->ajaxReturn(array('status' => 0, 'info' => '姓名格式不正确!', 'url' => U('User/userauth')));
                    }
                    if ($re == "205") {
                        $this->ajaxReturn(array('status' => 0, 'info' => '身份证格式不正确!', 'url' => U('User/userauth')));
                    }
                    if ($re == 1) {
                        $resdata = 2;//成年
                    }
                    if ($re == 2) {
                        $resdata = 3;//未成年
                    }
                }else{
                    $re  = 2;
                    $resdata = 2;
                }
                
            }
            if ($re > 0) {
                $model = D('User')->where($map)->save(array('real_name' => $_REQUEST['real_name'], 'idcard' => $_REQUEST['idcard'], 'age_status' => $resdata));
            }

            if ($model !== false) {

                $this->success("修改成功", U('User/userset'));
            } else {
                $this->error("修改失败");
            }
        } else {
            $user = D('User')->where(array('id' => $logininfo['user_id']))->find();
            if($user["age_status"] > 0){
                $user["idcard"] = substr($user["idcard"],0,1)."***********".substr($user["idcard"],-1,1);
            }
            $this->assign('user', $user);
            $this->display();
        }
    }

    /**
     * 个人中心->编辑资料->修改密码
     * @return [type] [description]
     * @author 小纯洁
     */
    public function userpassword()
    {
        if (!$this->islogin()) {
            $this->redirect('Mobile/User/login');
        }

        $logininfo = $this->suser->login_info();

        if (IS_POST) {
            $old_pwd = $_REQUEST['old_pwd'];
            $new_pwd = $_REQUEST['new_pwd'];


            /*判断Ucenter是否打开*/
            if (C('UC_OPEN') == 1) {

                $username = $logininfo['account'];
                //修改uc密码
                $ucresult = uc_user_edit($username, $_POST['old_pwd'], $_POST['new_pwd']);
                if ($ucresult == -1) {
                    $this->error("原始密码不正确");
                }
            }


            $result = D('User')->changePwd($logininfo['account'], $old_pwd, $new_pwd);
            if ($result == -1) {
                $this->error("原始密码不正确");
            } elseif ($result != false) {
                $u_uid['account'] = $logininfo['account'];
                M('user_pwd')->where($u_uid)->setField('password', think_encrypt($new_pwd));


                $this->suser->logout();

                $this->success("修改成功", U('User/login'));
            } elseif ($result === 0) {
                $this->error("新旧密码一致,请重新输入");
            } else {
                $this->error("修改失败");
            }
        } else {
            $this->display();
        }
    }

    /**
     * 个人中心->编辑资料->收货管理
     * @return [type] [description]
     * @author 小纯洁
     */
    public function useraddresslist()
    {
        if (!$this->islogin()) {
            $this->redirect('Mobile/User/login');
        }

        $logininfo = $this->suser->login_info();

        $userData = M('UserAddress', 'tab_')->where(array('user_id' => $logininfo['user_id']))->select();
        $this->assign('list_data', $userData);
        $this->display();
    }

    /**
     * 个人中心->编辑资料->收货管理->新增收货地址
     * @return [type] [description]
     * @author 小纯洁
     */
    public function useraddressadd()
    {
        if (!$this->islogin()) {
            $this->redirect('Mobile/User/login');
        }

        $logininfo = $this->suser->login_info();

        if (IS_POST) {
            $model = M('UserAddress', 'tab_');
            $data = $_REQUEST;
            $data['user_id'] = $logininfo['user_id'];
            $data['create_time'] = time();
            $userData = M('UserAddress', 'tab_')->where(array('user_id' => $logininfo['user_id']))->select();
            if (isset($data['is_default'])) {
                $data['is_default'] = 1;
                $model->where(array('user_id' => $logininfo['user_id']))->save(array('is_default' => 0));
            } else {
                $data['is_default'] = 0;
            }
            if ($model->create($data) && $model->add()) {
                $this->success('添加成功', U('User/useraddresslist'));
            } else {
                $this->error('添加失败');
            }
        } else {
            $this->display();
        }

    }

    /**
     * 个人中心->编辑资料->收货管理->编辑收货地址
     * @return [type] [description]
     * @author 小纯洁
     */
    public function useraddressedit($id = 0)
    {
        if (!$this->islogin()) {
            $this->redirect('Mobile/User/login');
        }

        $logininfo = $this->suser->login_info();

        $model = M('UserAddress', 'tab_');
        if (IS_POST) {
            $data = $_REQUEST;
            $data['user_id'] = $logininfo['user_id'];
            $data['id'] = $id;
            if (!empty($data['is_default'])) {
                $model->where('user_id=' . $logininfo['user_id'])->save(array('is_default' => 0));
            }
            if ($model->save($data) !== false) {
                $this->success('编辑成功', U('User/useraddresslist'));
            } else {
                $this->error('编辑失败');
            }
        } else {
            $data = $model->find($id);
            $this->assign("data", $data);
            $this->display();
        }

    }

    /**
     * 个人中心->编辑资料->收货管理->删除收货地址
     * @return [type] [description]
     * @author 小纯洁
     */
    public function useraddressdel($id = 0)
    {
        if (!$this->islogin()) {
            $this->redirect('Mobile/User/login');
        }


        $model = M('UserAddress', 'tab_');
        $result = $model->where("id=" . $id)->delete();
        if ($result !== false) {
            $this->success('地址删除成功', U('User/useraddresslist'));
        } else {
            $this->error("地址删除失败");
        }
    }

    /**
     * 个人中心->编辑资料->收货管理->设置默认收货地址
     * @return [type] [description]
     * @author 小纯洁
     */
    public function setDefaultAddress($id = 0, $type = 'setting')
    {
        if (!$this->islogin()) {
            $this->redirect('Mobile/User/login');
        }
        $model = M('UserAddress', 'tab_');

        $logininfo = $this->suser->login_info();

        switch ($type) {
            case 'setting':
                $map['id'] = array('neq', $id);
                $map['user_id'] = $logininfo['user_id'];
                $model->where($map)->save(array('is_default' => 0));
                $result = $model->where(array('id' => $id))->save(array('is_default' => 1));
                break;
            case 'cancel':
                $result = $model->where(array('id' => $id))->save(array('is_default' => 0));
                break;
        }
        if ($result !== false) {
            $this->success('地址删除成功');
        } else {
            $this->error("地址删除失败");
        }
    }

    /**
     * 个人中心->绑币管理
     * @return [type] [description]
     * @author wyr <840186209@qq.com>
     */
    public function userbindcoin()
    {

        $islogin = $this->islogin();
        if ($islogin) {
            $map['user_id'] = $islogin;
            $page = $page ? $page : 1; //默认显示第一页数据
            $row = C('LIST_ROWS');
            $data = M("user_play", "tab_")
                ->field("game_name,game_id,bind_balance")
                ->where($map)
                ->group("game_id")
                ->page($page, $row)
                ->select();

            $display = '';
            $this->assign('page', $page);
            $this->assign('data', $data);
        } else {
            $display = 'login';
        }
        $this->display($display);
    }

    /**
     * AJAX 绑币管理加载更多
     * @return [type] [description]
     */
    public function ajaxcoin()
    {
        $p = I('post.p');
        $status = 0;
        $row = C('LIST_ROWS');
        $map['user_id'] = $this->suser->login_info('user_id');
        $lists = M("user_play", "tab_")
            ->field("game_name,game_id,bind_balance")
            ->where($map)
            ->group("game_id")
            ->page($p, $row)
            ->select();
        if (!empty($lists) && is_array($lists)) {
            $status = 1;
        }
        echo json_encode(array('status' => $status, 'page' => $p, 'lists' => $lists));
    }

    public function recharge($pay_type = 1)
    {
        if (!$this->islogin()) {
            $this->redirect('Mobile/User/login');
        }
        $logininfo_id = $this->suser->login_info('user_id');
        if (IS_POST) {

            $user_id = get_user_id($_REQUEST['account']);


            $pay_amount = $_POST['pay_amount'];

            if ($user_id != $logininfo_id) {
                $this->error('只能给自己充值');
            }
            if ($user_id == 0) {
                $this->error('账号不存在');
            }

            if ($pay_amount < 0) {
                $this->error('金额不正确');
            }
            $pay_amount = abs($pay_amount);
            //$pay_amount = 0.01;
            if ($_REQUEST['spendType'] == 2) {
                $userMap['user_id'] = $user_id;
                $userMap['game_id'] = $_REQUEST['game_id'];
                $empty = M('UserPlay', 'tab_')->where($userMap)->find();
                if (empty($empty)) {
                    $this->error('该用户未玩过此游戏哦~');
                }
            }
            $json = array(
                'type' => $_REQUEST['spendType'],
                'user_id' => $user_id,
                'game_id' => $_REQUEST['game_id']
            );
            $userEntiy = get_user_entity($logininfo_id);
            $pay = A('Pay');
            $result = $pay->recharge($pay_amount, json_encode($json), $_POST['way'], $userEntiy['promote_id']);
            $this->ajaxReturn($result);
        } else {
            $game = M("game", "tab_");
            $map['apply_status'] = 1;
            $map['online_status'] = 1;
            $map['user_id'] = $logininfo_id;
            $lists = $game->field('tab_game.id,tab_game.game_name,bind_recharge_discount')
                ->join('tab_user_play as up on up.game_id = tab_game.id')
                ->where($map)
                ->group('tab_game.id')
                ->select();
            $this->assign('gameList', $lists);
            $this->display();
        }


    }

    /**
     * 个人中心->我的游戏
     * @return [type] [description]
     * @author wyr <840186209@qq.com>
     */
    // public function usergame($p = 1)
    // {
    //     if (!$this->islogin()) {
    //         $this->redirect('Mobile/User/login');
    //     }
    //     $page = intval($p);
    //     $page = $page ? $page : 1; //默认显示第一页数据
    //     $row = C('LIST_ROWS');
    //     $map['user_id'] = $this->suser->login_info('user_id');
    //     $data = D('DownRecord')->table('tab_down_record AS tdr')
    //         ->field('tab_game.id,tab_game.dow_status,tab_game.game_name,tab_game.game_size,tab_game.dow_num,tab_game.icon,tab_game.features,tdr.user_id,tab_game.and_dow_address,tab_game.add_game_address,tab_game.ios_dow_address,tab_game.ios_game_address,tab_game.game_score,tab_game.sdk_version')
    //         ->join("tab_game ON tdr.game_id = tab_game.id")
    //         ->where($map)
    //         ->page($page, $row)
    //         ->select();

    //     $this->assign("data", $data);
    //     $this->assign("page", $page);
    //     $this->display();
    // }
    public function usergame()
    {
        if (!$this->islogin()) {
            $this->redirect('Mobile/User/login');
        }
        $map['user_id'] = $this->suser->login_info('user_id');
        $data = D('DownRecord')->table('tab_user_game_login_record AS tdr')
            ->field('tab_game.id,tab_game.dow_status,tab_game.game_name,tab_game.game_size,tab_game.dow_num,
            tab_game.icon,tab_game.features,tdr.user_id,tab_game.and_dow_address,tab_game.add_game_address,
            tab_game.ios_dow_address,tab_game.ios_game_address,tab_game.game_score,tab_game.sdk_version')
            ->join("tab_game ON tdr.game_id = tab_game.id")
            ->where($map)
            ->group("tdr.user_id, tdr.game_id")
            ->select();

        $this->assign("data", $data);
        $this->display();
    }

    /**
     * 个人中心->我的游戏 AJAX加载更多
     * @return [type] [description]
     * @author 小纯洁
     */
    public function ajaxUserGame()
    {
        $page = I('post.p');
        $status = 0;
        $row = C('LIST_ROWS');
        $map['user_id'] = $this->suser->login_info('user_id');
        $data = D('DownRecord')->table('tab_down_record AS tdr')
            ->field('tab_game.id,tab_game.game_name,tab_game.game_size,tab_game.dow_num,tab_game.icon,tab_game.features,tdr.user_id,tab_game.and_dow_address,tab_game.add_game_address,tab_game.ios_dow_address,tab_game.ios_game_address,tab_game.game_score')
            ->join("tab_game ON tdr.game_id = tab_game.id")
            ->where($map)
            ->page($page, $row)
            ->select();
        foreach ($data as $key => $value) {
            $data[$key]['icon'] = get_img_url($value['icon']);
            $data[$key]['dow_url'] = U('Down/down_file', array('game_id' => $value['id'], 'sdk_version' => 1));
        }
        if (!empty($data) && is_array($data)) {
            $status = 1;
        }
        echo json_encode(array('status' => $status, 'page' => $page, 'lists' => $data));
    }

    /**
     * 个人中心->我的评论
     * @return [type] [description]
     * @author wyr <840186209@qq.com>
     */
    public function usercomment($game_name = '')
    {
        if (!$this->islogin()) {
            $this->redirect('Mobile/User/login');
        }
        $page = intval($p);
        $page = $page ? $page : 1; //默认显示第一页数据
        $row = C('LIST_ROWS');
        $map['status'] = 1;
        $map['account'] = $this->suser->login_info('account');
        if (!empty($game_name)) {
            $game = D("Game")->where(['game_name' => ['like', "%" . $game_name . "%"]])->select();
            if (empty($game)) {
                $map['game_id'] = ['in', '0'];
            } else {
                $map['game_id'] = ['in', array_column($game, "id")];
            }
        }
        $data = D('Comment')->field("account,create_time,comment,game_id")->where($map)->order("create_time desc")->page($page, $row)->select();
        foreach ($data as $key => $val) {
            $user = D("User")->getUserInfo($val['account']);
            $data[$key]['nickname'] = $user['nickname'];
            $data[$key]['head_img'] = $user['head_img'];
            $gameIcon = D('Game')->where('id = ' . $val['game_id'])->getField('icon');
            $data[$key]['game_icon'] = get_cover($gameIcon, 'path');
            $data[$key]['create_time'] = date("Y-m-d H:i:s", $data[$key]['create_time']);
        }
        $result['data'] = $data;
        $result['count'] = D('Comment')->where($map)->count();
        $this->assign('data', $result['data']);
        $this->assign('count', $result['count']);
        $this->assign('page', $page);
        $this->display();
    }

    /**
     * AJAX 我的评论加载更多
     * @return [type] [description]
     */
    public function ajaxComment()
    {
        if (!$this->islogin()) {
            $this->redirect('Mobile/User/login');
        }
        $page = I('post.p');
        $row = C('LIST_ROWS');
        $map['status'] = 1;
        $map['account'] = $this->suser->login_info('account');
        $data = D('Comment')->field("account,create_time,comment,game_id")->where($map)->order("create_time desc")->page($page, $row)->select();
        foreach ($data as $key => $val) {
            $user = D("User")->getUserInfo($val['account']);
            $data[$key]['nickname'] = $user['nickname'];
            $data[$key]['head_img'] = $user['head_img'];
            $data[$key]['create_time'] = date("Y-m-d H:i:s", $data[$key]['create_time']);
        }

        if (!empty($data) && is_array($data)) {
            $status = 1;
        }
        echo json_encode(array('status' => $status, 'page' => $page, 'lists' => $data));
    }

    /**
     * 个人中心->我的收藏
     * @return [type] [description]
     * @author wyr <840186209@qq.com>
     */
    public function usercollection($p = 1)
    {
        if (!$this->islogin()) {
            $this->redirect('Mobile/User/login');
        }
        $page = intval($p);
        $page = $page ? $page : 1; //默认显示第一页数据
        $data = D("Game")->getMyCollectGame($this->suser->login_info('account'), $p);
        $this->assign("data", $data);
        $this->assign("page", $page);
        $this->display();
    }

    /**
     * 个人中心->我的收藏 AJAX加载更多
     * @return [type] [description]
     * @author 小纯洁
     */
    public function ajaxUserCollection()
    {
        $page = I('post.p');
        $row = C('LIST_ROWS');
        $data = D("Game")->getMyCollectGame($this->suser->login_info('account'), $page);
        if (!empty($data) && is_array($data)) {
            $status = 1;
        }
        echo json_encode(array('status' => $status, 'page' => $page, 'lists' => $data, 'p' => $page));
    }

    /**
     * 个人中心->我的收藏->设置收藏
     * @return [type] [description]
     * @author wyr <840186209@qq.com>
     */
    public function set_collection()
    {
        if (!$this->islogin()) {
            $this->redirect('Mobile/User/login');
        }
        $game_id = $_REQUEST['game_id'];
        $account = $this->suser->login_info('account');
        $status = $_REQUEST['status'];
        $result = D('Game')->collectGame($game_id, $account, $status);
        if ($result != false) {
            $this->success("取消成功", U('User/usercollection'));
        } else {
            $this->error("取消失败");
        }
    }


    /**
     * 个人中心->我的邀请
     * @return [type] [description]
     * @author wyr <840186209@qq.com>
     */
    public function userinvitation()
    {
        if (!$this->islogin()) {
            $this->redirect('Mobile/User/login');
        }
        $page = intval($p);
        $page = $page ? $page : 1; //默认显示第一页数据
        $row = C('LIST_ROWS');
        $map['invite_id'] = $this->suser->login_info('user_id');
        $data = D('ShareRecord')->field("user_account,create_time,award_coin")
            ->where($map)
            ->order("create_time desc")
            ->group('user_id')
            ->page($page, $row)
            ->select();
        foreach ($data as $key => $value) {
            $data[$key]['user_account'] = substr_replace($value['user_account'], '****', 3, 4);
            $data[$key]['create_time'] = date('Y-m-d', $value['create_time']);
        }
        $total_data = D('ShareRecord')->field("count(distinct user_id) as invite_num,sum(award_coin) as award_coin")
            ->where($map)
            ->group("invite_id")
            ->find();
        $total_data['invite_num'] = empty($total_data['invite_num']) ? 0 : $total_data['invite_num'];
        $total_data['award_coin'] = empty($total_data['award_coin']) ? 0 : $total_data['award_coin'];
        $this->assign('data', $data);
        $this->assign('total_data', $total_data);
        $this->assign('page', $page);
        $this->display();
    }

    /**
     * AJAX 我的评论加载更多
     * @return [type] [description]
     */
    public function ajaxInvitation()
    {
        $page = I('post.p');
        $row = C('LIST_ROWS');
        $map['invite_id'] = $this->suser->login_info('user_id');
        $data = D('ShareRecord')->field("user_account,create_time,award_coin")
            ->where($map)
            ->order("create_time desc")
            ->page($page, $row)
            ->select();
        foreach ($data as $key => $value) {
            $data[$key]['user_account'] = substr_replace($value['user_account'], '****', 3, 4);
            $data[$key]['create_time'] = date('Y-m-d', $value['create_time']);
        }
        if (!empty($data) && is_array($data)) {
            $status = 1;
        }
        echo json_encode(array('status' => $status, 'page' => $page, 'lists' => $data));
    }


    /**
     * 个人中心->我的积分
     * @return [type] [description]
     * @author wyr <840186209@qq.com>
     */
    public function userintegral($type = 1, $p = 1)
    {
        if (!$this->islogin()) {
            $this->redirect('Mobile/User/login');
        }
        $user_id = $this->suser->login_info('user_id');
        $page = intval($p);
        $page = $page ? $page : 1; //默认显示第一页数据
        if ($type == 1) {
            $map['pr.user_id'] = $user_id;
            $map['pr.type'] = $type;
            $data = D("PointRecord")->getUserAchieveRecord($map, "create_time desc", $page);
        } else {
            $map['user_id'] = $user_id;
            $data = D("PointShopRecord")->getLists($map, "create_time desc", $page);
        }
        //$total = D('PointShopRecord')->getUserSpendPoint($user_id);
        $total = D('User')->getUserByAccount($this->suser->login_info('account'), 'point');
        $this->assign('data', $data);
        $this->assign('total', empty($total) ? 0 : $total['point']);
        $this->display();
    }

    /**
     * 个人中心->我的积分 AJAX 加载更多
     * @return [type] [description]
     * @author wyr <840186209@qq.com>
     */
    public function ajaxUserIntegral($type = 1)
    {
        $user_id = $this->suser->login_info('user_id');
        $page = I('post.p');
        $row = C('LIST_ROWS');
        if ($type == 1) {
            $map['pr.user_id'] = $user_id;
            $map['pr.type'] = $type;
            $data = D("PointRecord")->getUserAchieveRecord($map, "create_time desc", $page);
            foreach ($data as $key => $value) {
                $data[$key]['create_time'] = data('Y-m-d', $value['create_time']);
            }
        } else {
            $map['user_id'] = $user_id;
            $data = D("PointShopRecord")->getLists($map, "create_time desc", $page);
            $data = $data['data'];
            foreach ($data as $key => $value) {
                $data[$key]['url'] = U('User/exchangerecorddetail', array('id' => $value['id']));
                $data[$key]['create_time'] = data('Y-m-d', $value['create_time']);
            }
        }

        if (!empty($data) && is_array($data)) {
            $status = 1;
        }
        echo json_encode(array('status' => $status, 'page' => $page, 'lists' => $data));
    }

    /**
     * 个人中心->我的积分->商品详情
     * @return [type] [description]
     * @author wyr <840186209@qq.com>
     */
    public function exchangerecorddetail($id = 0)
    {
        if (!$this->islogin()) {
            $this->redirect('Mobile/User/login');
        }
        $map['sr.id'] = $id;
        $map['sr.user_id'] = $this->suser->login_info('user_id');
        $data = D("PointShopRecord")->table("tab_point_shop_record as sr")
            ->field("ps.good_name,ps.good_type,ps.good_info,ps.good_usage,ps.cover,sr.number,sr.good_key,sr.user_name,sr.address,sr.phone")
            ->join("left join tab_point_shop ps on ps.id = sr.good_id")
            ->where($map)
            ->find();
        $data['cover'] = get_img_url($data['cover']);
        $data['good_key'] = json_decode($data['good_key']);
        // var_dump($data['good_key']);die;
        $this->assign('data', $data);
        $this->display();
    }


    /**
     * 个人中心->我的礼包
     * @return [type] [description]
     * @author wyr <840186209@qq.com>
     */
    public function usergift($p = 1)
    {
        if (!$this->islogin()) {
            $this->redirect('Mobile/User/login');
        }
        $page = intval($p);
        $page = $page ? $page : 1; //默认显示第一页数据
        $data = D("Giftbag")->getMyGiftRecord($this->suser->login_info('account'), $page);
//        echo D("Giftbag")->_sql();
//        dump($data);die();
        foreach ($data as $key => $value) {
            $data[$key]['end_time'] = empty($value['end_time']) ? "永久" : date('Y-m-d H:i:s', $value['end_time']);
        }
        $this->assign("data", $data);
        $this->assign("page", $page);
        $this->display();
    }

    /**
     * 个人中心->我的礼包 AJAX加载更多
     * @return [type] [description]
     * @author 小纯洁
     */
    public function ajaxUserGift()
    {
        $page = I('post.p');
        $row = C('LIST_ROWS');
        $data = D("Giftbag")->getMyGiftRecord($this->suser->login_info('account'), $page);
        foreach ($data as $key => $value) {
            $data[$key]['start_time'] = date('Y-m-d', $value['start_time']);
            $data[$key]['end_time'] = date('Y-m-d', $value['end_time']);
            $data[$key]['url'] = U('Gift/detail', array('id' => $value['gift_id']));
        }
        if (!empty($data) && is_array($data)) {
            $status = 1;
        }
        echo json_encode(array('status' => $status, 'page' => $page, 'lists' => $data));
    }

    /**
     * 个人中心->兑换记录
     * @return [type] [description]
     * @author wyr <840186209@qq.com>
     */
    public function exchangerecord($p = 0)
    {
        if (!$this->islogin()) {
            $this->redirect('Mobile/User/login');
        }
        $page = intval($p);
        $page = $page ? $page : 1; //默认显示第一页数据
        $row = C('LIST_ROWS');
        $map['user_id'] = $this->suser->login_info('user_id');//$user_id;
        $type = $_REQUEST['type'];
        if ($type == 2) {
            $map['good_type'] = ['in', [1, 2]];//商品
            $totalMap['good_type'] = ['in', [1, 2]];//商品
        } elseif ($type == 3) {
            $map['good_type'] = 3;//平台币
            $totalMap['good_type'] = 3;//平台币
        }

        $data = D("PointShopRecord")
            ->field("id,good_name,good_type,number,pay_amount,create_time")
            ->where($map)
            ->order('create_time desc')
            ->page($page, $row)
            ->select();
        $totalMap['user_id'] = $this->suser->login_info('user_id');
        $total = D("PointShopRecord")->where($totalMap)->sum("pay_amount");
        $this->assign('total', empty($total) ? 0 : $total);
        $this->assign('data', $data);
        $this->assign('page', $page);
        $this->display();
    }

    /**
     * AJAX 兌換記錄加载更多
     * @return [type] [description]
     */
    public function ajaxExchangeRecord()
    {
        $page = I('post.p');
        $row = C('LIST_ROWS');
        $type = I('post.type');
        $map['user_id'] = $this->suser->login_info('user_id');//$user_id;
        if ($type == 2) {
            $map['good_type'] = ['in', [1, 2]];//商品
        } elseif ($type == 3) {
            $map['good_type'] = 3;//平台币
        }
        $data = D("PointShopRecord")
            ->field("id,good_name,good_type,number,pay_amount,create_time")
            ->where($map)
            ->order('create_time desc')
            ->page($page, $row)
            ->select();
        foreach ($data as $key => $value) {
            $data[$key]['create_time'] = date('Y-m-d H:i:s', $value['create_time']);
            $data[$key]['durl'] = U('User/exchangerecorddetail', array('id' => $value['id']));
        }
        if (!empty($data) && is_array($data)) {
            $status = 1;
        }
        echo json_encode(array('status' => $status, 'page' => $page, 'lists' => $data));
    }

    /**
     * 个人中心->我的积分->获取方式
     * @return [type] [description]
     * @author wyr <840186209@qq.com>
     */
    public function userintegralguide()
    {

        $model = new PointTypeModel();

        $data = $model->getLists(['status' => 1]);

        foreach ($data['data'] as $key => $val) {

            $result[$val['key']]['point'] = $val['point'];

            $result[$val['key']]['time_of_day'] = $val['time_of_day'];

            $result[$val['key']]['name'] = $val['name'];

            $result[$val['key']]['remake'] = $val['remake'];

        }

        $this->assign("data", $result);

        $this->display();
    }

    public function share_register($id = 0)
    {
        if (!empty($id)) {
            $data = D('Game')->find($id);
            $data['icon'] = get_cover($data['icon'], 'path');
        }
        $this->assign('data', $data);
        $this->display();
    }

    /**
     * 绑定支付宝
     */
    public function alipay()
    {
        if (IS_POST) {

            $member = new MemberApi();
            $user = D('User')->getLoginInfo();
            if (is_array($user)) {
                $res = $member->save_alipay($user['user_id'], $_POST);
                $res['url'] = U('User/userset');
                $this->ajaxReturn($res, 'json');
            } else {
                $this->ajaxReturn(['status' => 0, 'msg' => '请登录'], 'json');
            }


        } else {

            $this->assign('user', D('User')->getAlipay());

            $this->display();

        }
    }

    /**
     * 提现记录
     * @param integer $p 当前页
     * @author  鹿文学
     */
    public function withdraw_record($p = 1)
    {

        $order = 'audit_time desc';

        $lists = D('WithdrawGoldCoin')->lists($p, $map, 'id,money,coin,status,order_number,if(audit_time>0,FROM_UNIXTIME(audit_time,"%Y-%m-%d %H:%i:%s"),"") as audit_time', $order);

        $this->assign('lists', $lists['lists']);
        $this->assign('page', $lists['current']);
        $this->assign('totalpage', $lists['total']);

        $this->display();

    }

    /**
     * 提现记录
     * @param integer $p 当前页
     * @author  鹿文学
     */
    public function ajax_withdraw_record($p = 1)
    {

        $order = 'audit_time desc';

        $lists = D('WithdrawGoldCoin')->lists($p, $map, 'id,money,coin,status,order_number,if(audit_time>0,FROM_UNIXTIME(audit_time,"%Y-%m-%d %H:%i:%s"),"") as audit_time', $order);

        $this->ajaxReturn($lists, 'json');

    }

    /**
     * 消费记录
     * @param integer $p 当前页
     * @author  鹿文学
     */
    public function useing_record($p = 1)
    {

        $lists = D('User')->useing_record($p);
        foreach ($lists['lists'] as $key => $value) {
            $sort_data[$key] = $value['pay_time'];
        }
        array_multisort($sort_data, SORT_REGULAR, SORT_DESC, $lists['lists']);
        $this->assign('lists', $lists['lists']);
        $this->assign('page', $lists['current']);
        $this->assign('totalpage', $lists['total']);

        $this->display();

    }

    /**
     * 消费记录
     * @param integer $p 当前页
     * @author  鹿文学
     */
    public function ajax_useing_record($p = 1)
    {

        $lists = D('User')->useing_record($p);

        $this->ajaxReturn($lists, 'json');

    }


}