<?php

namespace web\ambap;

class login {
    public static function json_uperr() {
        global $db;
        $post = new \ciy\post();
        $errs = $post->get('err');
        $meid = $post->getint('meid');
        if (is_array($errs)) {
            foreach ($errs as $err) {
                savelog($db, $meid, $err['type'], $err['msg'], false, $err['t']);
            }
        }
        return succjson();
    }
    public static function json_login_mobile() {
        global $db;
        global $_token;
        $post = new \ciy\post();
        $model = $post->get('model');
        $user = $post->get('user');
        if (empty($user))
            return errjson('请填写用户名');
        $csql = new \ciy\sql('ap_user');
        $csql->where('mobile', $user);
        $rsuser = $db->getone($csql);
        if ($rsuser === false)
            return errjson($db->error);
        if (!is_array($rsuser)) {
            savelog($db, 0, 'LOGINERR', '用户[' . $user . ']不存在，在尝试登录');
            return errjson('用户名不存在');
        }
        if ($rsuser['trytime'] > 10) {
            if (tostamp() - $rsuser['logintimes'] < 600) {
                savelog($db, $rsuser['id'], 'LOGINERR', '用户[' . $user . ']登录连续失败');
                return errjson('连续输入密码错误，10分钟后再来登录.');
            }
        }
        if ($rsuser['stpstatus'] != 10) {
            savelog($db, $rsuser['id'], 'LOGINERR', '用户[' . $user . ']被禁用，在尝试登录');
            return errjson('您的账户已经被禁用.');
        }
        $authtime = $post->getint('auth');
        if (abs($authtime / 1000 - tostamp()) > 300)
            return errjson('您的本地时间与服务器时间相差超过5分钟，请调整本机时间。<br/>服务器时间: ' . date('Y-m-d H:i:s') . '<br/>您本机时间: ' . date('Y-m-d H:i:s', (int)($authtime / 1000)));
        // if($user == '1')
        //     clog(md5('1' . $_token['salt'])); //开发生成默认密码
        if ($post->get('pass') != md5($rsuser['password'] . $authtime)) {
            $updata = array();
            $updata['trytime'] = array('trytime+1');
            $updata['logintimes'] = tostamp();
            $csql = new \ciy\sql('ap_user');
            $csql->where('id', $rsuser['id']);
            $db->update($csql, $updata);
            savelog($db, $rsuser['id'], 'LOGINERR', '用户[' . $user . ']登录密码错误' . md5('1' . $_token['salt']));
            return errjson('用户名或密码错误.');
        }
        $sid = randstr(10);
        $exp = tostamp() + $_token['swapsec'];
        $id = $rsuser['id'];
        $updata = array();
        $updata['logintimes'] = tostamp();
        $updata['trytime'] = 0;
        $updata['sid'] = $sid;
        $updata['exptimes'] = $exp;
        $updata['ip'] = getip();
        $csql = new \ciy\sql('ap_user');
        $csql->where('id', $id);
        if ($db->update($csql, $updata) === false)
            return errjson('user数据库更新失败:' . $db->error);
        self::saveluser($db, 1, $rsuser['id'], $model);
        return self::getsync($rsuser, $sid);
    }
    public static function json_reg_mobile() {
        global $db;
        global $_token;
        $post = new \ciy\post();
        $model = $post->get('model');
        $upid = $post->getint('upid');
        $user = $post->get('user');
        $pass = $post->get('pass');
        if (empty($user))
            return errjson('请填写手机号');
        if (empty($pass))
            return errjson('请填写密码');
        $csql = new \ciy\sql('ap_user');
        $csql->where('mobile', $user);
        $rsuser = $db->getone($csql);
        if ($rsuser === false)
            return errjson($db->error);
        if (is_array($rsuser))
            return errjson('该手机号已被注册');

        $sid = randstr(10);
        $exp = tostamp() + $_token['swapsec']; //默认三天过期，每天换秘钥
        $rsuser = array();
        $rsuser['upid'] = $upid;
        $rsuser['stpstatus'] = 10;
        $rsuser['userlevel'] = 10;
        $rsuser['name'] = ':' . substr($user, -4);
        $rsuser['mobile'] = $user;
        $rsuser['password'] = $pass;
        $rsuser['myinvmoney'] = 0;
        $rsuser['mycashmoney'] = 0;
        $rsuser['mybondmoney'] = 0;
        $rsuser['mypnt'] = 0;
        $rsuser['trytime'] = 0;
        $rsuser['logintimes'] = tostamp();
        $rsuser['addtimes'] = tostamp();
        $rsuser['icon'] = '';
        $rsuser['memo'] = '';
        $rsuser['power'] = '';
        $rsuser['sid'] = $sid;
        $rsuser['exptimes'] = $exp;
        $rsuser['accounttimes'] = tostamp() + 86400 * 3;
        $rsuser['ip'] = getip();
        $csql = new \ciy\sql('ap_user');
        if ($db->insert($csql, $rsuser) === false)
            return errjson('注册用户失败:' . $db->error);
        $id = $db->insert_id();
        $rsuser['id'] = $id;
        if ($upid > 0) {
            //上级用户统计
        }
        self::saveluser($db, 1, $rsuser['id'], '手机注册:' . $model);
        return self::getsync($rsuser, $sid);
    }
    public static function json_wx_autouser() {
        global $db;
        global $_token;
        $post = new \ciy\post();
        $code = $post->get('code');
        $upid = $post->getint('upid');
        $weixinapi = new \web\api\weixin(1);
        $wxret = $weixinapi->call('https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code&appid={appid}&secret={appsecret}&js_code=' . $code);
        if (is_string($wxret))
            return errjson($wxret);

        $openid = $wxret['openid'];
        $sskey = $wxret['session_key'];
        $csql = new \ciy\sql('ap_user');
        $csql->where('wxminaid', $openid);
        $rsuser = $db->getone($csql);
        $userid = 0;
        $sid = randstr(10);
        $exp = tostamp() + $_token['swapsec']; //默认三天过期，每天换秘钥
        if (is_array($rsuser)) {
            $userid = $rsuser['id'];
            if ($rsuser['upid'] == 0 && $upid > 0 && $upid != $userid)
                $rsuser['upid'] = $upid;
            if (isset($wxret['unionid']))
                $rsuser['wxunionid'] = $wxret['unionid'];
            $rsuser['wxminakey'] = $sskey;
            $rsuser['wxminaid'] = $openid;
            $rsuser['trytime'] = 0;
            $rsuser['logintimes'] = time();
            $rsuser['sid'] = $sid;
            $rsuser['exptimes'] = $exp;
            $rsuser['ip'] = getip();
            $csql = new \ciy\sql('ap_user');
            $csql->where('id', $userid);
            if ($db->update($csql, $rsuser) === false)
                return errjson('wx更新失败:' . $db->error);
        } else {
            $newpnt = 1000; //注册赠送积分
            $rsuser = array();
            $rsuser['upid'] = $upid;
            if (isset($wxret['unionid']))
                $rsuser['wxunionid'] = $wxret['unionid'];
            $rsuser['icon'] = '';
            $rsuser['certs'] = '';
            $rsuser['name'] = '';
            $rsuser['mobile'] = '';
            $rsuser['stpstatus'] = 10;
            $rsuser['userlevel'] = 10;
            $rsuser['myinvmoney'] = 0;
            $rsuser['mycashmoney'] = 0;
            $rsuser['mybondmoney'] = 0;
            $rsuser['mypnt'] = $newpnt;
            $rsuser['logintimes'] = time();
            $rsuser['wxminakey'] = $sskey;
            $rsuser['wxminaid'] = $openid;
            $rsuser['addtimes'] = time();
            $rsuser['sid'] = $sid;
            $rsuser['exptimes'] = $exp;
            $rsuser['accounttimes'] = tostamp() + 86400 * 3;
            $rsuser['ip'] = getip();
            $csql = new \ciy\sql('ap_user');
            if ($db->insert($csql, $rsuser) === false)
                return errjson('wx新增失败:' . $db->error);
            $rsuser['id'] = $db->insert_id();
            if ($newpnt > 0) {
                $updata = array();
                $updata['pnt'] = 1000;
                $updata['vuser'] = $rsuser['id'];
                $updata['name'] = '注册奖励';
                $updata['addtimes'] = time();
                $csql = new \ciy\sql('ap_pnt_record');
                if ($db->insert($csql, $updata) === false)
                    return errjson('reward新增失败:' . $db->error);
            }
            if ($upid > 0) {
                // $updata = array();
                // $updata['upall'] = array('upall+1');
                // $csql = new \ciy\sql('ap_user');
                // $csql->where('id', $upid);
                // if ($db->update($csql, $updata) === false)
                //     return errjson('上线统计失败:' . $db->error);
            }
        }
        return self::getsync($rsuser, $sid);
    }
    public static function json_forgetpass() {
        global $db;
        global $_token;
        $post = new \ciy\post();
        $model = $post->get('model');
        $mobile = $post->get('user');
        $pass = $post->get('pass');
        $code = $post->get('capsms');
        $codeid = $post->getint('capsms_id');
        if (empty($code))
            return errjson('请填写验证码');
        if (empty($mobile))
            return errjson('请填写手机号');
        if (empty($pass))
            return errjson('请填写密码');

        $csql = new \ciy\sql('ap_user');
        $csql->where('mobile', $mobile);
        $rsuser = $db->getone($csql);
        if (!is_array($rsuser))
            return errjson('该手机号未注册');
        $csql = new \ciy\sql('ap_usr_capcode');
        $csql->where('id', $codeid);
        $caprow = $db->getone($csql);
        if (!is_array($caprow))
            return errjson('未发送验证码');
        if ($caprow['exptimes'] < time())
            return errjson('验证码已过期');
        $errmsg = '';
        if ($caprow['account'] != $mobile)
            $errmsg = '验证码与手机号不匹配';
        if ($caprow['code'] != $code)
            $errmsg = '验证码错误';
        if (!empty($errmsg)) {
            $updata = array();
            $updata['exptimes'] = array('exptimes-180');
            $csql = new \ciy\sql('ap_usr_capcode');
            $csql->where('id', $codeid);
            if ($db->update($csql, $updata) === false)
                return errjson('减扣失败:' . $db->error);
            return errjson($errmsg);
        }
        $sid = randstr(10);
        $exp = tostamp() + $_token['swapsec']; //默认三天过期，每天换秘钥
        $updata = array();
        $updata['trytime'] = 0;
        $updata['password'] = $pass;
        $updata['logintimes'] = tostamp();
        $updata['trytime'] = 0;
        $updata['sid'] = $sid;
        $updata['exptimes'] = $exp;
        $updata['ip'] = getip();
        $csql = new \ciy\sql('ap_user');
        $csql->where('id', $caprow['vuser']);
        if ($db->update($csql, $updata) === false)
            return errjson('密码更新失败:' . $db->error);
        self::saveluser($db, 1, $rsuser['id'], '密码找回成功:' . $model);
        return self::getsync($rsuser, $sid);
        return succjson();
    }
    public static function json_sendsms() {
        global $db;
        $post = new \ciy\post();
        $mobile = $post->get('account');
        $length = $post->getint('length');
        if ($length < 3 || $length > 8)
            return errjson('验证码长度必须在3-8位之间');
        $csql = new \ciy\sql('ap_user');
        $csql->where('mobile', $mobile);
        $rsuser = $db->getone($csql);
        if (!is_array($rsuser))
            return errjson('该手机号未注册');

        $csql = new \ciy\sql('ap_usr_capcode');
        $csql->where('account', $mobile);
        $csql->where('addtimes>', tostamp() - 1);
        $cnt = $db->get1($csql);
        if ($cnt > 0)
            return errjson('验证码发送频繁，请1分钟后再尝试');

        $code = rand(pow(10, $length - 1), pow(10, $length) - 1);
        $updata = array();
        $updata['vuser'] = $rsuser['id'];
        $updata['account'] = $mobile;
        $updata['code'] = $code;
        $updata['addtimes'] = tostamp();
        $updata['exptimes'] = tostamp() + 600;
        $csql = new \ciy\sql('ap_usr_capcode');
        if ($db->insert($csql, $updata) === false)
            return errjson('更新失败:' . $db->error);
        $id = $db->insert_id();
        $data = array();
        $data['txt'] = $code;
        $param = array(
            "mobile" => $mobile,
            "style" => "1",
            "data" => $data,
            "sendnow" => true,
        );
        $retapi = ciy_api('sms', $param);
        if ($retapi !== true)
            return errjson($retapi);
        $ret['id'] = $id;
        return succjson($ret);
    }
    public static function json_restorage() {
        global $db;
        $rsuser = verifyfast();
        return self::getsync($rsuser);
    }
    static function getsync($userrow, $sid = '') {
        global $db;
        global $_token;
        $ret = array();
        if (!empty($sid)) {
            $auth = array();
            $auth['id'] = $userrow['id'];
            $auth["_s"] = $sid;
            $authstr = json_encode($auth, JSON_PARTIAL_OUTPUT_ON_ERROR);
            $enauth = encrypt($authstr, 'E', $_token['salt']);
            if ($_token['type'] == 'cookie') {
                $headercookie = 'Set-Cookie: ' . $_token['field'] . '=' . $enauth . '; expires=' . gmdate('D, d-M-Y H:i:s T', time() + $_token['swapsec'] + $_token['expsec']) . '; path=/; SameSite=None; Secure; httponly';
                header($headercookie);  //Cookie方式，安全性好
            } else {
                $ret['_ciyauth'] = $enauth; //Localstorage方式，兼容性更好
                //header($_token['field'] . ': ' . $enauth);  //有坑
            }
        }
        $ret['storage'] = array();
        $csql = new \ciy\sql('zc_admin');
        $csql->column('id,name');
        $ret['storage']['adminuser'] = $db->get($csql);
        $csql = new \ciy\sql('zc_cata');
        $csql->order('csort');
        $ret['storage']['cata'] = $db->get($csql);
        $csql = new \ciy\sql('ap_pnt_track');
        $ret['pnttrack'] = $db->get($csql);
        $ret['me'] = array();
        $ret['me']['addtimes'] = $userrow['addtimes'];
        $ret['me']['accounttimes'] = $userrow['accounttimes'];
        //$ret['me']['saasid_a'] = $userrow['saasid_a'];
        $ret['me']['id'] = $userrow['id'];
        $ret['me']['eid'] = enid($userrow['id']);
        $ret['me']['upid'] = $userrow['upid'];
        $ret['me']['icon'] = $userrow['icon'];
        $ret['me']['mobile'] = $userrow['mobile'];
        $ret['me']['name'] = $userrow['name'];
        $ret['me']['userlevel'] = $userrow['userlevel'];
        $ret['me']['mymoney'] = $userrow['mymoney'];
        $ret['me']['mycashmoney'] = $userrow['mycashmoney'];
        $ret['me']['myinvmoney'] = $userrow['myinvmoney'];
        $ret['me']['mybondmoney'] = $userrow['mybondmoney'];
        $ret['me']['mypnt'] = $userrow['mypnt'];
        $ret['me']['certs'] = $userrow['certs'];
        $ret['me']['needpass'] = empty($userrow['password']);
        if (!empty($userrow['mobile'])) {
            $csql = new \ciy\sql('zc_debug_user');
            $csql->where('targettype', 21);
            $csql->where('isuse', 1);
            $csql->where('user', $userrow['mobile']);
            $ret['me']['dbg'] = is_array($db->getone($csql));
        }
        $csql = new \ciy\sql('ap_usr_ext');
        $csql->where('id', $userrow['id']);
        $extrow = $db->getone($csql);
        if (is_array($extrow)) {
            $ret['me']['truename'] = $extrow['truename'];
            $ret['me']['email'] = $extrow['email'];
            $ret['me']['wxno'] = $extrow['wxno'];
            $ret['me']['idid'] = $extrow['idid'];
            $ret['me']['cciy'] = $extrow['cciy'] . '';
            $ret['me']['cashtype'] = $extrow['cashtype'];
            $ret['me']['bankno'] = $extrow['bankno'];
            $ret['me']['bankname'] = $extrow['bankname'];
            $ret['me']['bankaccount'] = $extrow['bankaccount'];
            $ret['me']['bankcode'] = $extrow['bankcode'];
        } else {
            $ret['me']['truename'] = '';
        }
        return succjson($ret);
    }
    public static function json_logout() {
        global $db;
        $rsuser = verifyuser();
        if (is_array($rsuser)) {
            self::saveluser($db, 2, $rsuser['id']);
        }
        return succjson();
    }
    public static function json_debug_list() {
        global $db;
        $csql = new \ciy\sql('zc_debug_user');
        $csql->where('targettype', 21);
        $csql->where('isuse', 1);
        $ret['list'] = $db->get($csql);
        return succjson($ret);
    }
    public static function json_debug_chguser() {
        global $db;
        global $_token;
        $post = new \ciy\post();
        $usercode = $post->getint('code');
        $csql = new \ciy\sql('zc_debug_user');
        $csql->where('id', $usercode);
        $dbguser = $db->getone($csql);
        if ($dbguser === false)
            return errjson($db->error);
        if (!is_array($dbguser))
            return errjson('用户code不存在');
        $csql = new \ciy\sql('ap_user');
        $csql->where('mobile', $dbguser['user']);
        $rsuser = $db->getone($csql);
        if (!is_array($rsuser))
            return errjson('用户不存在');
        $sid = randstr(10);
        $exp = tostamp() + $_token['swapsec'];
        $id = $rsuser['id'];
        $updata = array();
        $updata['logintimes'] = tostamp();
        $updata['trytime'] = 0;
        $updata['sid'] = $sid;
        $updata['exptimes'] = $exp;
        $updata['ip'] = getip();
        $csql = new \ciy\sql('ap_user');
        $csql->where('id', $id);
        if ($db->update($csql, $updata) === false)
            return errjson('user数据库更新失败:' . $db->error);
        return self::getsync($rsuser, $sid);
    }
    private static function saveluser($db, $isinout, $userid, $model = '') {
        $updata = array();
        $updata['isinout'] = $isinout;
        $updata['loguser'] = $userid;
        $updata['addtimes'] = tostamp();
        $updata['ip'] = getip();
        $updata['model'] = dbstr($model, 250);
        $csql = new \ciy\sql('ap_luser');
        $db->insert($csql, $updata);
        return false;
    }
}
