<?php

namespace admin\model;
use source\Model;

/**
 * 用户模型

 */

class MemberAdmin extends Model {
	
	/* 自动验证规则 */
    protected $_validate = array(
    	array('username','require','用户名不能为空',self::EXISTS_VALIDATE,'require', self::MODEL_BOTH),
    	array('username', '', '用户名已经存在', self::VALUE_VALIDATE, 'unique', self::MODEL_INSERT),
   		array('email','email','邮箱格式错误',self::VALUE_VALIDATE,'regex', self::MODEL_BOTH),
    	array('email','','邮箱已占用',self::VALUE_VALIDATE,'unique', self::MODEL_BOTH),
    	array('mobile','/^1\d{10}$/','手机号格式不正确',self::VALUE_VALIDATE,'regex',self::MODEL_BOTH),
    	array('mobile','','手机号已占用',self::VALUE_VALIDATE,'unique', self::MODEL_BOTH),
    	array('repassword','password','确认密码不正确',self::VALUE_VALIDATE,'confirm', self::MODEL_BOTH),
    );

    /* 自动完成规则 */
    protected $_auto = array(
        array('password','_password',3,'callback'),
    	array('password','',2,'ignore'),
    );
	
	protected function _password($data){
		if(empty($data)){
		    return '';
		}
		return md5(sha1($data));
	}

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

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

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

        session('user_auth', $auth);
        session('user_auth_sign', data_auth_sign($auth));
		return $user['id'];

    }

	/*更新数据前*/
	public function _before_update(&$data){
		if(session('user_auth.id')!=C('USER_ADMINISTRATOR') && $data['id']!=session('user_auth.id')){
		    $this->error='对不起，你没有权限';
		}
	}
	
	public function _after_update($data){
		if($data['id']){
			M('auth_group_access')->where(array('uid'=>I('id')))->delete();
			$group=I('group');
			foreach ($group as $k => $v) {
				M('auth_group_access')->add(array(
					'uid'=>I('id'),
					'group_id'=>$v
				));
			}
		}
	}
}
