<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace Agent\Model;
use Think\Model;

/**
 * 商户模型
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */

class AgentModel extends Model {

    protected $_validate = array(
    );

    /* 自动完成规则 */
    protected $_auto = array(

            array('password','',3,'ignore'),
    		array('password', 'md5', self::MODEL_BOTH, 'function'),
            array('update_time', NOW_TIME, self::MODEL_BOTH),
    );



    /**
     * 登录指定用户
     * @param  integer $uid 用户ID
     * @return boolean      ture-登录成功，false-登录失败
     */
    public function login($username='',$password=''){
    	$return = array('uid'=>0, 'msg'=>'', 'status'=>0);
    	$info = $this->where(array('username'=>$username))->find();
        if ($info) {
            $pass = $info['password'];
            if (md5($password) != $pass) {
                $return['msg'] = 'password is incorrect';
            }else{
                $return['uid'] = $info['id'];
                $return['status'] = $info['status'];;
                if($info['status']!=1){
                	$return['msg'] = 'The account has been disabled';
                }
            }
        }else{
            $return['msg'] = 'username is incorrect';
        }

        /* 登录用户 */
        $this->autoLogin($info);
        return $return;
    }

    /**
     * 注销当前用户
     * @return void
     */
    public function logout(){
        session('agent_auth', null);
        session('agent_auth_sign', null);
    }

    /**
     * 自动登录用户
     * @param  integer $user 用户信息数组
     */
    private function autoLogin($user){
        /* 更新登录信息 */
        $data = array(
            'uid'             => $user['id'],
            'login'           => array('exp', '`login`+1'),
            'last_login_time' => NOW_TIME,
            'last_login_ip'   => get_client_ip(1),
        );
        $this->save($data);

        /* 记录登录SESSION和COOKIES */
        $auth = array(
            'uid'             => $user['id'],
            'username'        => $user['username'],
            'last_login_time' => $user['last_login_time'],
        );

        session('agent_auth', $auth);
        session('agent_auth_sign', data_auth_sign($auth));

    }

    public function getNickName($uid){
        return $this->where(array('id'=>(int)$uid))->getField('nickname');
    }

    public function getUserInfo($uid){
        return $this->where(array('id'=>(int)$uid))->find();
    }

}
