<?php

namespace Common\Model;
use Think\Model;

/**
 * 用户模型
 */
class MemberModel extends Model{

    protected $_validate = array(
    );

    protected $_auto = array(
        array('regtime', NOW_TIME, self::MODEL_INSERT),
    	array('status', '1', self::MODEL_INSERT),
    );

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

    public function getInfoByMobile($mobile){
    	return $this->where(array('mobile'=>$mobile,'is_fault'=>0))->find();
    }


    public function getInfoByOpenid($openid){
    	return $this->where(array('openid'=>$openid))->find();
    }


    public function getInfoByAlipayid($alipayid){
    	return $this->where(array('alipayid'=>$alipayid))->find();
    }
    
    
    public function getInfoByClientid($client_id){
        return $this->where(array('client_id'=>$client_id))->find();
    }
    

    //根据外部unionid获取用户信息
    public function getInfoByUnionid($unionid,$source='line'){
    	if($source=='alipay')
    		return $this->where(array('alipayid'=>$unionid))->find();
    	else if($source=='line')
    	    return $this->where(array('client_id'=>$unionid))->find();
    	else
    		return $this->where(array('openid'=>$unionid))->find();
    }

    public function regByMobile($mobile){
    	if(empty($mobile)){
    		return false;
    	}
    	$data['mobile'] = $mobile;
    	$data['regtime'] = time();
    	$data['username'] = 'u'.time().rand(10000, 99999);

	    if($res = $this->add($data))
	    	return $res;
	    else
	    	return false;

    }

    public function regByUnionid($unionid,$mobile='',$source='line'){
    	if(empty($mobile)){
    		return false;
    	}
    	if($source == 'alipay')
    		$data['alipayid'] = $unionid;
    	else if($source == 'line')
    	    $data['client_id'] = $unionid;
    	else
    		$data['openid'] = $unionid;
    	$data['regtime'] = time();
    	$data['username'] = 'u'.time().rand(10000, 99999);
    	$data['mobile'] = $mobile;

    	if($res = $this->add($data))
    		return $res;
    	else
    		return false;

    }

    public function updateCredits($id, $credits){
    	$this->where("id=$id")->setInc('credits',$credits);
    }

    public function updateAmount($id, $amount){
        $this->where("id=$id")->setInc('amount',$amount);
    }

    public function updateLevel($id, $level){
        $this->where("id=$id")->save(array('levelid'=>$level));
    }

}
