<?php

namespace web\admin;

class login {
    public static function json_login() {
        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('zc_admin');
        $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', $authtime / 1000));

        if ($post->get('pass') != sha256($rsuser['password'] . $authtime)) {
            $updata = array();
            $updata['trytime'] = array('trytime+1');
            $updata['logintimes'] = tostamp();
            $csql = new \ciy\sql('zc_admin');
            $csql->where('id', $rsuser['id']);
            $db->update($csql, $updata);
            savelog($db, $rsuser['id'], 'LOGINERR', '用户[' . $user . ']登录密码错误 密码123654:[' . sha256('123654' . $_token['salt']) . ']');
            return errjson('用户名或密码错误.');
        }
        $id = $rsuser['id'];
        $db->execute('delete from zc_online where exptimes<? and user=?', array(time(), $id));
        $exp = tostamp() + $_token['swapsec']; //默认三天过期，每天换秘钥
        $sid = randstr(10);
        $updata = array();
        $updata['user'] = $id;
        $updata['targettype'] = 10;
        $updata['sid'] = $sid;
        $updata['addtimes'] = tostamp();
        $updata['exptimes'] = $exp;
        $updata['ip'] = getip();
        $csql = new \ciy\sql('zc_online');
        if ($db->insert($csql, $updata) === false)
            return errjson('online数据库更新失败:' . $db->error);
        $oid = $db->insert_id();
        $updata = array();
        $updata['logintimes'] = tostamp();
        $updata['trytime'] = 0;
        $csql = new \ciy\sql('zc_admin');
        $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, $oid, $sid);
    }
    public static function json_restorage() {
        global $db;
        $rsuser = verifyfast();
        $csql = new \ciy\sql('zc_admin');
        $csql->where('id', $rsuser['id']);
        $userrow = $db->getone($csql);
        $db->execute('update zc_online set usrchg=0 where id=?', array($rsuser['_o']));
        return self::getsync($userrow);
    }
    static function getsync($userrow, $oid = 0, $sid = '') {
        global $db;
        global $_token;
        if ($oid > 0) {
            $auth = array();
            $auth['id'] = $userrow['id'];
            $auth['_o'] = $oid;
            $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=/; httponly; SameSite=None; Secure';
                header($headercookie);
            } else {
                $ret['_ciyauth'] = $enauth;
                //header('_ciyauth: ' . $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,id');
        $ret['storage']['cata'] = $db->get($csql);
        $departname = '';
        if ($userrow['departid'] > 0) {
            $csql = new \ciy\sql('zc_depart');
            $csql->where('id', $userrow['departid']);
            $csql->column('name');
            $departname = $db->get1($csql);
        }
        $ret['me'] = array();
        $ret['me']['depart'] = $departname;
        $ret['me']['addtimes'] = $userrow['addtimes'];
        $ret['me']['icon'] = $userrow['icon'];
        $ret['me']['mobile'] = $userrow['mobile'];
        $ret['me']['sex'] = $userrow['sex'];
        $ret['me']['name'] = $userrow['name'];
        $power = $userrow['power'];
        $ret['me']['power'] = $power;
        $ret['me']['needpass'] = empty($userrow['password']);
        return succjson($ret);
    }
    public static function json_logout() {
        global $db;
        $rsuser = verifyuser();
        if (is_array($rsuser)) {
            $csql = new \ciy\sql('zc_online');
            $csql->where('id', $rsuser['_o']);
            $db->delete($csql);
            self::saveluser($db, 2, $rsuser['id']);
        }
        return succjson();
    }
    private static function saveluser($db, $isinout, $userid, $model = '') {
        $updata = array();
        $updata['isinout'] = $isinout;
        $updata['loguser'] = $userid;
        $updata['addtimes'] = tostamp();
        $updata['ip'] = getip();
        $updata['model'] = $model;
        $csql = new \ciy\sql('zc_luser');
        $db->insert($csql, $updata);
        return false;
    }
}
