<?php
/**
 *      [XCECP] (C) COLNET Inc.
 *      This is NOT a freeware, use is subject to license terms
 */
if(!defined("IN_QKWEB")){exit("Access Denied");}
class UserModel extends BaseModel{
	public $ticket = '';
	public $msg = '';
	public $mobileRegCodeId = "";
	function getInfo($id){
		$sql = "select * from qk_user where id='$id'";
		$userInfo = $this->db->getRow($sql);
		$userInfo['score'] = $this->db->getOne("select sum(score) from qk_user_score where userId='".$userInfo['id']."' and iStatus=1");
		$userInfo['amount'] = $this->db->getOne("select sum(amount) from qk_finance where userId='".$userInfo['id']."' and iStatus=1");
		if(!$userInfo['amount']){$userInfo['amount']='0.00';}
		if($GLOBALS['_G']['config']['user']['loginName']==false && $userInfo['email']){
			$userInfo['loginName'] = $userInfo['email'];
		}
		$userInfo['level'] = $this->db->getOne("select name from `qk_user_level` where id='".$userInfo['levelId']."'");
		$userInfo['auth']=array();
		$userInfo['auth']['weibo'] = $this->db->getOne("select id from qk_weibo_auth where userId='".$userInfo['id']."'");
		$userInfo['auth']['qq'] = $this->db->getOne("select id from qk_qq_auth where userId='".$userInfo['id']."'");
		$userInfo['auth']['baidu'] = $this->db->getOne("select id from qk_baidu_auth where userId='".$userInfo['id']."'");
		$userInfo['auth']['alipay'] = $this->db->getOne("select id from qk_alipay_auth where userId='".$userInfo['id']."'");
		$userInfo['auth']['taobao'] = $this->db->getOne("select id from qk_taobao_auth where userId='".$userInfo['id']."'");
			$userInfo['distributionGrade'] = $GLOBALS['db']->getOne("select name from `qk_distribution_grade` where id='".$v['distributionGradeId']."'");
			$province = $GLOBALS['db']->getOne("select name from `qk_district` where id='".$v['distributionProvinceId']."'");
			$city = $GLOBALS['db']->getOne("select name from `qk_district` where id='".$v['distributionCityId']."'");
			$county = $GLOBALS['db']->getOne("select name from `qk_district` where id='".$v['distributionCountyId']."'");
			$userInfo['distributionDistrict'] = $province.' '.$city.' '.$county;
			//print_r($userInfo);
		return $userInfo;
	}
	function edit($params){$params['act']='edit';return $this->query($params);}
	function add($params,$quick=false){$params['act']="add"; return $this->query($params,$quick); }
	function register($params){
		$params['act']='add';
		$params['loginPwd'] = $params['pwd'];
		$params['loginPwdRepeat'] = $params['pwdRepeat'];
		$email = $params['email'];
		$mobile = $params['mobile'];
		$loginPwd = $params['loginPwd'];
		$loginPwdRepeat = $params['loginPwdRepeat'];
		if(!$mobile || !is_numeric($mobile) || strlen($mobile)!=11){$this->msg='手机号码填写不正确';return false;}
		$config=getConfig('user');
		if($config['regEmail']=='1'){
			if(strlen($email)<5 || !strpos($email,"@") || !preg_match("/^([a-zA-Z0-9@\.\-]+)$/",$email)){ $this->msg = '请填写正确的注册邮箱'; return false; }
		}
		if($config['verifyMobile']=='1'){
			$mobile = $params['mobile'];	if(!$mobile || !preg_match("/^1([0-9]{10})$/",$mobile)){$this->msg='手机号码格式不正确';return false;}
			$mobileCode = $params['mobileCode'];if(!$mobileCode || !preg_match("/^([0-9]{6})$/",$mobileCode)){$this->msg='手机验证码格式不正确';return false;}
			if($this->verifyMobileReg($mobile,$mobileCode)){
				$params['mobileActivationTime']=date('Y-m-d H:i:s');
			}else{
				$this->msg='手机验证码不正确';return false;
			}
		}
		if(!$loginPwd || strlen($loginPwd)<6 || strlen($loginPwd)>20){$this->msg='密码长度只能在6-20位字符之间';return false;}
		if($loginPwdRepeat!=$loginPwd){$this->msg='两次输入密码不一致';}
		$ret = $this->query($params);
		return $ret;
	}
	function query($params,$quick=false){
			global $_G;
			$id = $params["id"];
			$act = $params["act"];
			$loginName = trim($params["loginName"]);
			$loginName = strtolower($loginName);
			$nickname = $params["nickname"];
			$loginPwd = $params["loginPwd"];
			$loginPwdRepeat = $params["loginPwdRepeat"];
			$email = $params["email"];
			$space = $params["space"];
			$name = $params["name"];
			$certNo = $params["certNo"];
			$inviter = $params["inviter"];
			$mobile = $params["mobile"];
			$qq = $params["qq"];
			$captcha = $params["captcha"];
			$agreement = $params["agreement"];
			$firstName = $params["firstName"];
			$lastName = $params["lastName"];
			$comName = $params["comName"];
			$address = $params["address"];
			$suburb = $params["suburb"];
			$zipCode = $params["zipCode"];
			$city = $params["city"];
			$province = $params["province"];
			$country = $params["country"];
 			$bill_address = $params["bill_address"];
			$bill_suburb = $params["bill_suburb"];
			$bill_zipCode = $params["bill_zipCode"];
			$bill_city = $params["bill_city"];
			$bill_province = $params["bill_province"];
			$bill_country = $params["bill_country"];
			$tel = $params["tel"];
			$fax = $params["fax"];
			$distributionGradeId = $params["distributionGradeId"];
			$distributionProvinceId = $params["distributionProvinceId"];
			$distributionCityId = $params["distributionCityId"];
			$distributionCountyId = $params["distributionCountyId"];
			$groupId = $params["groupId"];
			$levelId = $params["levelId"];
			$creditLine = $params["creditLine"];
			if($inviter){
				$inviterId = $this->db->getOne("select id from qk_user where loginName='".$inviter."'");
				if(!$inviterId){$inviterId=0; $this->msg = $_G['lang']['register']['error']['inviter']; return false; }
			}
			$config=getConfig('user');
			if(!$quick){
				if($config['regEmail']=='1'){
					if(strlen($email)<5 || !strpos($email,"@") || !preg_match("/^([a-zA-Z0-9@\.\-]+)$/",$email)){ $this->msg = $_G['lang']['register']['error']['email']; return false; }
				}
				if($qq && !preg_match("/^(\d+)$/",$qq)){ $this->msg = 'QQ号码为数字'; return false; }
				if(!$mobile || !is_numeric($mobile) || strlen($mobile)!=11){ $this->msg = '手机号码格式不正确'; return false; }
				if($email){
					if(strlen($email)<5 || !strpos($email,"@") || !preg_match("/^([a-zA-Z0-9@\.\-]+)$/",$email)){ $this->msg = $_G['lang']['register']['error']['email']; return false; }
				}
			}
			if($act=="register"){$act="add";}
			if($act=="add"){
				if(!$quick){
					//if($this->db->getOne("select id from qk_user where email='$email'")){$this->msg='注册邮箱重复';return false;}
					if(!$loginPwd || strlen($loginPwd)<6 || strlen($loginPwd)>20){ $this->msg = $_G['lang']['register']['error']['password']; return false; }
					if(!$loginPwdRepeat || strlen($loginPwdRepeat)<6 || strlen($loginPwdRepeat)>20){ $this->msg = $_G['lang']['register']['error']['passwordConfirmation']; return false; }
					if($loginPwd != $loginPwdRepeat){ $this->msg = $_G['lang']['register']['error']['passwordConfirmation']; return false; }
					$loginPwd = md5($loginPwd);
					if($email){
						$sql = "select count(id) from qk_user where email='$email'";
						if($this->db->getOne($sql)){ $this->msg = $_G['lang']['register']['error']['emailRepeat']; return false; }
					}
					if($this->db->getOne("select id from qk_user where mobile='$mobile'")){$this->msg='手机号码重复';return false;}
				}
				if($loginName!=""){
					if(preg_match("/^\d+$/",$loginName)){ $this->msg = '登录名不允许全为数字'; return false;}
					if(!$quick && (strlen($loginName)<4 || strlen($loginName)>20)){ $this->msg = '用户名长度必需为5-20位';return false; }
					if($wheres){ $wheres .= " or loginName='$loginName'";}else{ $wheres = " loginName='$loginName'"; } 			
					$res = $this->db->getOne("select count(id) from qk_user where $wheres");
					if($res){ $this->msg = $_G['lang']['register']['error']['loginNameRepeat']; return false; }
				}
				$sql = "insert into qk_user set loginName='$loginName',loginPwd='$loginPwd',";
				$sqlEnd = ",posttime=UNIX_TIMESTAMP()";
			}else if($act=="edit" && $id && is_numeric($id)){
				if($this->db->getOne("select id from qk_user where email='$email' and id<>$id")){$this->msg='注册邮箱重复';return false;}
				if($this->db->getOne("select id from qk_user where mobile='$mobile' and id<>$id")){$this->msg='手机号码重复';return false;}

				$sql = "update qk_user set ";
				$sqlEnd = " where id='$id'";
				if($loginPwd){ $loginPwd = md5($loginPwd); $sql .= "loginPwd='$loginPwd',"; }
			}else{
				$this->msg = '数据不完整';
				return false;
			}
			$sql .= "email='$email',country='$country',tel='$tel',fax='$fax',nickname='$nickname'";
			if(isset($params['groupId'])){$sql .= ",groupId='$groupId'";}
			if(isset($params['levelId'])){$sql .= ",levelId='$levelId'";}
			$sql .= ",firstName='$firstName',lastName='$lastName',comName='$comName',address='$address',suburb='$suburb',zipCode='$zipCode',city='$city',province='$province'";
			$sql .= ",space='$space',name='$name',certNo='$certNo',inviter='$inviter',mobile='$mobile',inviterId='$inviterId',distributionGradeId='$distributionGradeId'";
			$sql .= ",distributionProvinceId='$distributionProvinceId',distributionCityId='$distributionCityId',distributionCountyId='$distributionCountyId'";
			$sql .= ",qq='$qq',creditLine='$creditLine'";
			$sql .= $sqlEnd;
			if($this->db->query($sql)){
				if($act=="edit"){
					$_SESSION['email']=$email;
					$account=$nickname?$nickname:($email?$email:($mobile?$mobile:'请完善用户资料'));
					setcookie("account",$account,time()+36000,"/");
					$this->msg = $_G['lang']['userEdit']['success']; return true;
				}else if($act=="add"){
					$userId = $this->db->insert_id();
					//注册赠送优惠券功能
					$couponConfig = getConfig('coupon');//$couponConfig['enable']==1 && 
					if($couponConfig['register']==1){
						$res = $this->db->getAll("select id,money from qk_coupon where typeId=1");
						if(is_array($res) && count($res)>0){
							$key = array_rand($res); $couponId = $res[$key]['id']; $money = $res[$key]['money'];
							$couponNumber = randCoupon();
							$sql = "insert into qk_user_coupon set userId='$userId',couponId='$couponId',money='$money',number='$couponNumber',iStatus=1,endtime=0,posttime=UNIX_TIMESTAMP()";
							$this->db->query($sql);
						}
					}
					//注册赠送优惠券功能 End

					if($address){
						$sql = "insert into qk_user_addr set userId='$userId'";
						$sql .= ",firstName='$firstName',lastName='$lastName',name='$name',comName='$comName'";
						$sql .= ",suburb='$suburb',city='$city',province='$province',country='$country',`primary`='$primary',workplace='$workplace'";
						$sql .= ",district='$district',address='$address',zipCode='$zipCode',mobile='$mobile',phone='$phone'";
						$sql .= ",posttime=UNIX_TIMESTAMP()";
						$this->db->query($sql);
					}
					if($bill_address){
						$sql = "insert into qk_user_addr set userId='$userId'";
						$sql .= ",firstName='$firstName',lastName='$lastName',name='$name',comName='$comName'";
						$sql .= ",suburb='$bill_suburb',city='$bill_city',province='$bill_province',country='$bill_country',`primary`='0',workplace='$workplace'";
						$sql .= ",district='$district',address='$bill_address',zipCode='$zipCode',mobile='$mobile',phone='$phone'";
						$sql .= ",posttime=UNIX_TIMESTAMP()";
						$this->db->query($sql);
					}
					return $userId;
				}
			}else{
				if($act=="edit"){
					$this->msg = $_G['lang']['userEdit']['error']['error'];
				}
			}
		return false;
	}

	function password($params,$id=0){
		$oldPwd = $params['password_current'];
		$loginPwd = $params['password_new'];
		$loginPwd2 = $params['password_confirmation'];
		$oldPwd = md5($oldPwd);
		$sql = "select loginPwd from qk_user where id='$id'";
		$oldPwdDb = $this->db->getOne($sql);
		if($oldPwdDb != $oldPwd){
			$this->msg = '原密码不正确';return false;
		}
		if(strlen($loginPwd)<5 || strlen($loginPwd)>16){ $this->msg='密码必须为6-16位字符';return false;}
		if($loginPwd == $loginPwd2){$loginPwd = md5($loginPwd);}else{
			$this->msg = '两次输入的新密码不一致';return false;
		}
		$sql = "update qk_user set loginPwd='$loginPwd' where id='$id'";
		if(@$this->db->query($sql)){
			$this->msg = '修改密码成功';return true;
		}
	}

	function getAddrInfo($id,$userId=0){
		$wheres = "";
		if(isset($_SESSION['adminId']) && $_SESSION['adminId']){
		}else{
			 $wheres .="and userId='$userId'";
		}
		$sql = "select * from qk_user_addr where id='$id' $wheres";
		$info = $this->db->getRow($sql);
		$info['userInfo'] = $this->db->getRow("select * from qk_user where id='".$info['userId']."'");
		return $info;
	}

	function editAddr($params,$userId=0){
		if($userId){
			$wheres = " and userId='$userId'";
		}
		$id = $params['id'];
		if(!$id || !settype($id,"integer")){return false;}
		
		$firstName = $params['firstName'];
		$lastName = $params['lastName'];
		$comName = $params['comName'];
		$suburb = $params['suburb'];
		$city = $params['city'];
		$province = $params['province'];
		$country = $params['country'];
		$workplace = $params['workplace'];
		$name = $params['name'];
		$district = $params['district'];
		$address = $params['address'];
		$zipCode = $params['zipCode'];
		$mobile = $params['mobile'];
		$phone = $params['phone'];
		$primary = $params['primary'];
		if(!$primary || !settype($primary,"integer")){$primary=0;}

		$sql = "update qk_user_addr set ";
		$sql .= " firstName='$firstName',lastName='$lastName',comName='$comName',suburb='$suburb',zipCode='$zipCode'";
		$sql .= ",workplace='$workplace',name='$name',address='$address',mobile='$mobile',phone='$phone'";
		if($district){
			$sql .= ",district='$district'";
		}
		$sql .= ",city='$city',province='$province',country='$country' where id='$id' $wheres";
		if($this->db->query($sql)){
			if($primary==1){
				$this->setAddrPrimary($id,$userId);
			}
			return true;
		}
		return false;
	}

	function addAddr($params,$userId=0){
		if(!$userId){
			return false;
		}	
		$firstName = $params['firstName'];
		$lastName = $params['lastName'];
		$comName = $params['comName'];
		$suburb = $params['suburb'];
		$zipCode = $params['zipCode'];
		$city = $params['city'];
		$province = $params['province'];
		$country = $params['country'];

		$workplace = $params['workplace'];
		$name = $params['name'];
		$district = $params['district'];
		$address = $params['address'];
		$mobile = $params['mobile'];
		$phone = $params['phone'];

		$sql = "insert into qk_user_addr set ";
		$sql .= " firstName='$firstName',lastName='$lastName',comName='$comName',suburb='$suburb',zipCode='$zipCode'";
		$sql .= ",workplace='$workplace',name='$name',district='$district',address='$address',mobile='$mobile',phone='$phone'";
		$sql .= ",city='$city',province='$province',country='$country',userId='$userId',posttime=UNIX_TIMESTAMP()";
		if($this->db->query($sql)){
			$id = $this->db->insert_id();
			//$this->setAddrPrimary($id,$userId);
			exit('{"success":true,"errno":0,"data":{"workplace":"'.$workplace.'","name":"'.$name.'","mobile":"'.$mobile.'","phone":"'.$phone.'","district":"'.$district.'","address":"'.$address.'","zipcode":"'.$zipCode.'","aid":'.$id.'}}');
			return true;
		}
		return false;
	}

	function setAddrPrimary($id,$userId){
		if($id && settype($id,"integer") && $userId && settype($userId,"integer")){
			$sql = "update qk_user_addr set `primary`=0 where userId='$userId'";
			$this->db->query($sql);
			$sql = "update qk_user_addr set `primary`=1 where userId='$userId' and id='$id'";
			$this->db->query($sql);
			return true;
		}
		return false;
	}

	function delAddr($id,$userId=0){
		if($id && settype($id,"integer") ){
			$user="";
			if($userId && settype($userId,"integer")){$user=" and userId='$userId'";}
			$sql = "delete from `qk_user_addr` where 1=1 $user and id='$id'";
			$this->db->query($sql);
			return true;
		}
		return false;
	}
	function delScore($id,$userId=0){
		if($id && settype($id,"integer") ){
			$user="";
			if($userId && settype($userId,"integer")){$user=" and userId='$userId'";}
			$sql = "delete from `qk_user_score` where 1=1 $user and id='$id'";
			$this->db->query($sql);
			return true;
		}
		return false;
	}

	function addrData(){
		$userId = $_SESSION['userId'];
		$sql = "select * from qk_user_addr where userId='$userId'";
		$res = $this->db->getAll($sql);
		//$tmp = '{"success":true,';
		$tmp = '{"errno":0,"data":[';
		if($res){
			$i=0;
			foreach($res as $item){
				$tmp .= "{";
				$tmp .= '"aid":'.$item['id'].',"workplace":"'.$item['workplace'].'","name":"'.$item['name'].'","district":"'.$item['district'].'","address":"'.$item['address'].'","zipCode":"'.$item['zipCode'].'","phone":"'.$item['phone'].'","mobile":"'.$item['mobile'].'"';
				$tmp .= "}";
				$i++;
				if($i<count($res)){
					$tmp .= ",";
				}
			}
		}
		$tmp .= "]}";
		return $tmp;
	}

	function getEmail($loginName){
		//if($param['loginName']){$loginName = $param['loginName'];}
		$sql = "select email from qk_user where loginName='$loginName'";
		return $this->db->getOne($sql);
	}

	function forget($params){
		global $_G;
		$wheres = "";
		$email = $params['email'];
		$mobile = $params['mobile'];
		/*
		if($_G['config']['user']['loginName']){
			$loginName = $params['loginName'];
			if(!$loginName){
					exit('{"success":false,"message":"'.$_G['lang']['user']['forget']['loginName'].'"}');			
			}else{
				$wheres .= " and loginName='$loginName'";
			}
		}
		*/
		if(!$email || !strpos($email,"@")){$this->msg='电子邮件为空或格式不正确';return false;			}
		if(!$mobile || strlen($mobile)!=11){$this->msg='手机号码不正确';return false;			}

		$wheres .= " and email='$email' and mobile='$mobile'";

		$sql = "select id from qk_user where 1=1 $wheres";
		$id = $this->db->getOne($sql);
		if(!$id){
				$this->msg=$_G['lang']['user']['forget']['notExist'];return false;
		}else{
			$newPwd = rand(100000,999999);

			$mailTitle= $_G['lang']['user']['forget']['mailTitle']." - ".$GLOBALS['siteConf']['siteName'];
			$mailvars['newPwd'] = $newPwd;
		    $sent = SendTemplateMail("forget.html",$mailvars,$email,$mailTitle);
			//$this->msg="abc";
			if($sent===true){
				$sql = "update qk_user set loginPwd='".md5($newPwd)."' where id='$id'";
				if($this->db->query($sql)){
					$this->msg=$_G['lang']['user']['forget']['success'];
					return true;
				}
			}else{
				$this->msg=$sent;
			}
		}
		return false;
	}

	function del($id){
		if($id && settype($id,"integer")){
			$groupId = $this->db->getOne("select groupId from `qk_user` where `id`='$id'");
			if($groupId=='1'){$this->msg='管理员用户不能被删除'.$groupId;return false;}
			$sql = "delete from `qk_user` where `id`='$id'";
			if($this->db->query($sql)){
				return true;
			}
		}
		return false;
	}

	function quickLogin($userId,$red=true){
		$_SESSION['userId'] = $userId;
		$userInfo = $this->db->getRow("select * from qk_user where id='$userId'");
		$nickname = $userInfo['nickname'];
		$mobile = $userInfo['mobile'];
		$email = $userInfo['email'];
		$account = $nickname?$nickname:($email?$email:($mobile?$mobile:'请完善用户资料'));
		$_SESSION['userId'] = $userId;
		$_SESSION['account'] = $account;
		setcookie("userId",$userId,time()+36000,"/");
		setcookie("account",$account,time()+36000,"/");
		$uid = strtoupper(hash_hmac('sha1',$userId,COOKIE_KEY));
        $this->ticket = $uid;
		setcookie("ueidc_uid",$uid,time()+36000,"/");
		$_SESSION['levelId'] = $userInfo['levelId'];
		$this->db->query("update qk_user set cookieId='$uid',cookieTime='".time()."',lastLoginTime=UNIX_TIMESTAMP(),lastLoginIp='".getIp()."' where id='$userId'");
		$_SESSION['level'] = $this->db->getOne("select name from qk_user_level where id='".$userInfo['levelId']."'");
						load_class("purchase");
						$pm = new PurchaseModel();
						$pm->cartMerger();
						if($userInfo['groupId']==1){
							$groupId=$userInfo['groupId'];
							$adminId = $userId;
							$adminName = $loginName;
							$_SESSION['adminId'] = $adminId;
							$_SESSION['adminName'] = $adminName;
							$_SESSION['groupId'] = $groupId;
						}
		if($red){
			header("Location:/");exit;
		}
		return true;
	}

	function addFavorite($params,$userId){
		global $_G;
		$c = true;
		if(!$userId){
			$userId = $params['userId'];
		}
		if(!$userId){$res = array("success"=>false,"message"=>"请先登录网站");$c=false;}
		if($c){
			$goodsId = $params['goodsId'];
			if(!$goodsId){$res = array("success"=>false,"message"=>"商品不存在或已经下架");$c=false;}
		}
		if($c){
			$sql = "select id from qk_user_favorite where userId='$userId' and goodsId='$goodsId'";
			if($this->db->getOne($sql)){
				$res = array("success"=>false,"message"=>"您的收藏夹中已经包含此商品");$c=false;
			}
		}
		if($c){
			$sql = "insert into qk_user_favorite set userId='$userId',goodsId='$goodsId',posttime=UNIX_TIMESTAMP()";
			if($this->db->query($sql)){
				$res = array("success"=>true,"message"=>"已成功添加到您的商品收藏夹","type"=>3);
			}
		}
		echo json_encode($res);
		return false;
	}

	function delFavorite($id,$userId){
		$c = true;
		$wheres="";
		if($userId){
			$wheres .= " and userId='$userId'";
		}
		$sql = "delete from qk_user_favorite where id='$id' $wheres";
		if($this->db->query($sql)){
			$res = array("success"=>true,"message"=>"成功删除收藏夹商品","type"=>3);
		}
		echo json_encode($res);
		return false;
	}

	function getCoupon($userId){
		$wheres = "";
		if($userId){$wheres .= " and uc.userId='$userId'";}
		$sql = "select uc.*,coupon.name from qk_user_coupon uc left join qk_coupon coupon on uc.couponId=coupon.id where uc.iStatus=1 and (uc.endtime=0 or uc.endtime>".time().") $wheres";
		$coupon = $this->db->getAll($sql);
		return $coupon;
	}

	function checkCoupon($params){
		$number = str_replace('-','',$params['number']);
		$userId = $params['userId'];
		if($number && $userId){
			$sql = "select * from qk_user_coupon where iStatus=1 and (endtime=0 or endtime>".time().") and number='$number'";
			$info = $this->db->getRow($sql);
			if($info){
				if($info['userId']!=0 && $info['userId']!=$userId){ return false; }
				return $info;
			}
		}
		return false;
	}

	function addScore($params){$params['act']='add';return $this->queryScore($params);}

	function queryScore($params){
		$act = $params['act'];
		$loginName = $params['loginName'];
		$score = $params['score'];
		$typeId = $params['typeId'];
		$iStatus = $params['iStatus'];
		$remark = $params['remark'];
		if(!$loginName){ $ret = array("success"=>false,"message"=>"用户名不能为空"); return json_encode($ret); }
		$userId = $this->db->getOne("select id from qk_user where loginName='$loginName'");
		if(!$userId){
			$ret = array("success"=>false,"message"=>"用户不存在");
			return json_encode($ret);
		}
		if($act=="add"){
			$sql = "insert into qk_user_score set ";
			$sqlEnd = ",posttime=UNIX_TIMESTAMP()";
		}else{
			$sql = "update qk_user_socre set";
			$sqlEnd = " where id='$id'";
		}
		$score = intval($score);
		$sql .= "userId='$userId',score='$score',typeId='$typeId',iStatus='$iStatus',remark='$remark'";
		$sql .= $sqlEnd;
		if($this->db->query($sql)){
			$ret = array("success"=>true,"message"=>"操作成功");
			
		}
		return json_encode($ret);
	}

	function getScore($userId){
		$sql = "select sum(score) from qk_user_score where userId='$userId' and iStatus=1";
		$score[0] = $this->db->getOne($sql);
		if(!$score[0]){$score[0]=0;}
		return $score;
	}

	function addMyOrder($params){
		return $this->queryMyOrder($params);
	}
	function editMyOrder($params){
		return $this->queryMyOrder($params);
	}
	function queryMyOrder($params){
		$act = $params['act'];
		$id = $params['id'];
		$userId = $params['userId'];
		if(!$userId){$userId = $_SESSION['userId'];}
		$merchant = $params['merchant'];
		$deliveryNumber = $params['deliveryNumber'];
		$amount = $params['amount'];
		$receiver = $params['receiver'];
		$receiveTime = $params['receiveTime'];
		$mobile = $params['mobile'];
		$content = $params['content'];
		$receiveTime = strtotime($receiveTime);
		if($act=="add"){
			$sql = "insert into qk_user_myorder set userId='$userId',";
			$sqlEnd = ",posttime=UNIX_TIMESTAMP()";
		}else if($act=="edit" && $id){
			$sql = "update qk_user_myorder set ";
			$sqlEnd = " where id='$id'";
		}
		$sql .= " merchant='$merchant',deliveryNumber='$deliveryNumber',amount='$amount',receiver='$receiver',receiveTime='$receiveTime',mobile='$mobile',content='$content'";
		$sql .= $sqlEnd;
		if($this->db->query($sql)){
			return true;
		}
	
	}
	
	function ajaxEditMyOrder($params){
		$id = $params['id'];
		$values = "";
		$iStatus = false;
		foreach($params as $key=>$val){
			if($key!="id"){
				if($key=="iStatus"){$iStatus=$val;}
				$values .= " `$key`='$val',";
			}
		}
		if($values){
			$values = substr($values,0,strlen($values)-1);
		}
		$sql = "update qk_user_myorder set $values where id='$id'";
		if($this->db->query($sql)){
			$score = getgpc("score","P");
			if($iStatus && $score){
				$userId = $this->db->getOne("select userId from qk_user_myorder where id='$id'");
				if($iStatus==25){
					$sql = "insert into qk_user_score set userId='$userId',score='$score',typeId=21,iStatus=1,remark='提交发货单 ".$id." 审核成功奖励积分'";
				}else if($iStatus==26){
					$sql = "insert into qk_user_score set userId='$userId',score='-$score',typeId=22,iStatus=1,remark='提交发货单 ".$id." 审核失败扣除积分'";				
				}
				$this->db->query($sql);
			}
			return true;
		}
		return false;
	}

	function getMyOrderInfo($id){
		if($id){
			$sql = "select * from qk_user_myorder where id='$id'";
			$res = $this->db->getRow($sql);
			$res['userInfo']['loginName'] = $this->db->getOne("select loginName from qk_user where id='".$res['userId']."'");
			return $res;
		}
	}

	function delMyOrder($id){
		if($id){
			$sql = "delete from qk_user_myorder where id='$id'";
			$this->db->query($sql);
			return $res;
		}
	}

	function getId($loginName){
		if(!$loginName){return false;}
		$wheres = "loginName='$loginName'";
		if(strpos($loginName,"@")){
			$wheres = " email='$loginName'";
		}else if(is_numeric($loginName) && strlen($loginName)==11){
			$wheres = " mobile='$loginName'";
		}else if(is_numeric($loginName)){
			$wheres = " id='$loginName'";
		}
		$sql = "select id from `qk_user` where $wheres order by id desc";
		return $this->db->getOne($sql);
	}

	function changePwd($param){
		$id  = $param['id'];
		if(!$id || !is_numeric($id)){ $this->msg='用户ID不能为空'; return false; }
		$password_old = $param['password_old'];
		$password = $param['password'];
		$password_confirm = $param['password_confirm'];
		if(!$password_old){ $this->msg='原密码不能为空';return false; }
		if(!$password){ $this->msg='新密码不能为空';return false; }
		if(strlen($password)<6 || strlen($password)>16){ $this->msg='新密码长度需在6-16位之间';return false; }
		if($password!=$password_confirm){ $this->msg='确认密码与新密码不一致';return false; }
		$sql = "select loginPwd from qk_user where id='$id'";
		$loginPwd = $this->db->getOne($sql);
		if($loginPwd!=md5($password_old)){$this->msg='原密码不正确'; return false;}
		$sql = "update qk_user set loginPwd='".md5($password)."' where id='$id'";
		$this->db->query($sql);
		$this->msg='用户 '.$id.' 密码修改成功';
		return true;
	}

	function sendActivationEmail($userId=0,$email=false){
		if(!$userId){$this->msg='用户不可为空';return false;}
		$userInfo = $this->db->getRow("select email from qk_user where id='$userId'");
		if(!$userInfo){$this->msg='用户不存在';return false;}
		if($email){
			if(strlen($email)<5 || strpos($email,'@')<=0){
				$this->msg='邮箱格式不正确';return false;
			}
		}
		$mailvars['siteName'] = $GLOBALS['siteConf']['siteName'];
		if(!$email){$email = $userInfo['email'];}else{
			if($email!=$userInfo['email']){
				$sql = "select id from `qk_user` where email='$email' and id<>'$userId'";
				if($this->db->getOne($sql)){
					$this->msg='邮箱已被其他用户占用';return false;
				}else{
					$this->db->query("update qk_user set email='$email' where id='$userId'");
				}
			}
		}
		if(!$email){$this->msg='未填写邮箱';return false;}
		$emailRand = md5(time());
		$this->db->query("update qk_user set emailRand='$emailRand',emailRandTime=UNIX_TIMESTAMP() where id='$userId'");
		$mailvars['email'] = $email;
		$base = 'http://'.$_SERVER['HTTP_HOST'].'/user/activating?';
		$param = 'username='.$email.'&rand='.$emailRand;
		$mailvars['href'] = $base.$param;
		$mailvars['url'] = $base.htmlspecialchars($param);
		$mailTitle = $GLOBALS['siteConf']['siteName']." 注册邮箱确认";
		//echo $this->parseEmail($email);exit;
		$sent = SendTemplateMail("activating.html",$mailvars,$email,$mailTitle);
		if($sent===true){
			$this->msg='发送注册邮箱确认信成功('.$this->parseEmail($email).')';
			return true;
		}
		return $sent;
	}

	function activatingEmail($email,$rand){
			$sql = "select * from qk_user where email='$email' and emailRand='$rand' order by id desc";
			$userInfo = $this->db->getRow($sql);
			if(($userInfo['emailRandTime']+48*3600)>time()){
				$sql = "update `qk_user` set emailActivationTime=UNIX_TIMESTAMP() where id='".$userInfo['id']."'";$this->db->query($sql);
				return true;
			}
			return false;
	}

	function parseEmail($email){
		if(!strpos($email,'@')){return false;}
			$emailArr = explode("@",$email);
			if(strlen($emailArr[0])>3){
				$len = strpos($email,'@')-3;
				$tou = substr($email,0,3);
			}else if(strlen($emailArr[0])>1){
				$len = strpos($email,'@')-1;
				$tou = substr($email,0,1);
			}else{
				$tou = $emailArr[0];
			}
			$s = '';
			for($i=0;$i<$len;$i++){$s.='*';}
			return $tou.$s.'@'.$emailArr[1];
	}

   function logout(){
		$_SESSION['userId'] = '';
		$_SESSION['account'] = '';
		setcookie('userId',null,time()-36000,'/');
		setcookie('account',null,time()-36000,'/');
        setcookie('ueidc_uid',null,time()-36000,'/');
	}

	function sendMobileReg($mobile=0){
		$mobile=trim($mobile);
		if(!$mobile){$this->msg='手机号码不能为空';return false;}
		if(!preg_match("/^1([0-9]{10})$/",$mobile)){$this->msg='手机号码格式不正确';return false;}
		$sql = "select id from qk_user where mobile='$mobile'";$userId=$this->db->getOne($sql);if($userId){$this->msg='该号码已注册为'.$GLOBALS['siteConf']['shortName'].'用户';return false;}
		$ip=getIp();
		$sql = "select id from qk_user_mobilecode where (mobile='$mobile' or ip='$ip') and posttime>".strtotime(date("Y-m-d 00:00:00"));
		if(count($this->db->getAll($sql))>=3){$this->msg='您今天的注册验证码申请次数已达3次，请明天再申请';return false;}
		load_class("sms");
		$sms = new SmsModel();
		$code =rand(100000,999999);
		$sql = "select code from qk_user_mobilecode where type='register' and (mobile='$mobile' and ip='$ip') and posttime>UNIX_TIMESTAMP()-1800 order by id desc";
		$reCode = $this->db->getOne($sql);
		if($reCode){$code=$reCode;}
		$return=false;
		$return=$sms->sendReg($mobile,$code);
		if($return){
			$this->msg='发送成功';
			$sql = "insert into qk_user_mobilecode set code='$code',type='register',mobile='$mobile',ip='".$ip."',validtime=1800,posttime=UNIX_TIMESTAMP()";
			$this->db->query($sql);
			$this->mobileRegCodeId = $this->db->insert_id();
			return true;
		}
		$this->msg='发送失败';
		if($sms->msg){$this->msg=$sms->msg;}
		return false;
	}
	function verifyMobileReg($mobile=0,$code=0){
		$mobile=trim($mobile);
		if(!$mobile){$this->msg='手机号码不能为空';return false;}
		if(!$code || !is_numeric($code) || strlen($code)!=6){ $this->msg='验证码格式不符合规则';return false; }
		$sql = "select code from qk_user_mobilecode where mobile='$mobile' and ip='".getIp()."' and posttime>".strtotime(date("Y-m-d 00:00:00"))." order by id desc";
		$codedb = $this->db->getOne($sql);
		if($code==$codedb){
			$this->msg='手机号码验证成功';return true;
		}
		$this->msg='手机号码验证失败';return false;
	}

	function sendMobileCode($userId=0){
		if(!$userId){$this->msg='用户ID参数丢失';return false;}
		$userInfo = $this->getInfo($userId);
		if(!$userInfo){$this->msg='用户不存在';return false;}
		if($userInfo['mobileActivationTime']){$this->msg='您的手机号码已经验证，无需重新验证';return false;}
		$mobile = $userInfo['mobile'];
		if(!$mobile || !is_numeric($mobile) || strlen($mobile)!=11){ $this->msg='手机号码未设置或不符合规则';return false; }
		$ip=getIp();
		$sql = "select id from qk_user_mobilecode where (mobile='$mobile' or ip='$ip') and posttime>".strtotime(date("Y-m-d 00:00:00"));
		if(count($this->db->getAll($sql))>2){$this->msg='您的操作受到限制';return false;}
		load_class("sms");
		$sms = new SmsModel();
		$code =rand(100000,999999);
		$sql = "select code from qk_user_mobilecode where type='register' and (mobile='$mobile' and ip='$ip') and posttime>UNIX_TIMESTAMP()-1800 order by id desc";
		$reCode = $this->db->getOne($sql);
		if($reCode){$code=$reCode;}
		$content='您正在验证手机号码，校验码'.$code.'，请在30分钟内按页面提示提交检验码';
		if($sms->sendMsg($mobile,$content)){
			$this->msg='发送成功';
			$sql = "insert into qk_user_mobilecode set code='$code',type='register',mobile='$mobile',ip='".$ip."',validtime=1800,posttime=UNIX_TIMESTAMP()";
			$this->db->query($sql);
			return true;
		}
		$this->msg='发送失败';
		if($sms->msg){$this->msg=$sms->msg;}
		return false;
	}

	function verifyMobileCode($userId=0,$code=0){
		if(!$userId){$this->msg='用户ID参数丢失';return false;}
		if(!$code || !is_numeric($code) || strlen($code)!=6){ $this->msg='验证码格式不符合规则';return false; }
		$userInfo = $this->getInfo($userId);
		if(!$userInfo){$this->msg='用户不存在';return false;}
		$mobile = $userInfo['mobile'];
		if(!$mobile || !is_numeric($mobile) || strlen($mobile)!=11){ $this->msg='手机号码未设置或不符合规则';return false; }
		$sql = "select code from qk_user_mobilecode where mobile='$mobile' and ip='".getIp()."' and posttime>".strtotime(date("Y-m-d 00:00:00"))." order by id desc";
		$codedb = $this->db->getOne($sql);
		if($code==$codedb){
			$this->db->query("update `qk_user` set mobileActivationTime=UNIX_TIMESTAMP() where id='".$userId."'");
			$this->msg='手机号码验证成功';return true;
		}
		$this->msg='手机号码验证失败';return false;
	}

	function getCreditBalance($userId=0){
		if(!$userId){return 0;}
		$sql = "select id from qk_order where divideNum>1 and payStatusId in(21) and iStatus in(3,4,5,6,21) and userId='$userId'";
		$orders = $this->db->getAll($sql);
		$overdraft = 0;	//欠款
		load_class('order');$om=new OrderModel();
		foreach($orders as $order){
			$order = $om->getInfo($order['id']);
			foreach($order['divide'] as $divide){
				if($divide['iStatus']!=1){
					$overdraft += $divide['amount'];
				}
			}
		}
		$creditLine = $this->db->getOne("select creditLine from `qk_user` where id='$userId'");
		if(!$creditLine){$creditLine=0;}
		$ret=$creditLine-$overdraft;
		if($creditLine==0){
				if(!$this->db->getOne("select id from qk_order where divideNum>1 and iStatus not in(7,8,9) and userId='$userId'")){
					$ret=-1;
				}

		}
		$ret=7000;
		return $ret;
	}
	function checkLoginName($loginName=''){
		if(!$loginName){$this->msg='登录名不得为空';return false;}
		if(!preg_match("/^[1][3,4,5,7,8][0-9]{9}$/",$loginName)){$this->msg='手机号码格式不正确';return false;}
		$sql = "select id from `qk_user` where mobile='".$loginName."'";
		if($this->db->getOne($sql)){$this->msg='该用户名已存在';return false;}
		return true;
	}
	function isMobileExists($mobile=''){
		if(!$mobile || strlen($mobile)!=11 || !is_numeric($mobile)){$this->msg='手机号码为11位数字';return false;}
		$sql = "select id from qk_user where mobile='$mobile' limit 1";
		if($this->db->getOne($sql)){
			$this->msg='手机号码已存在';
			return true;
		}else{
			$this->msg='手机号码不存在';
			return false;
		}
	}
	function checkMobile($mobile=''){
		if(!$mobile || strlen($mobile)!=11 || !is_numeric($mobile)){$this->msg='手机号码为11位数字';return false;}
		$sql = "select id from qk_user where mobile='$mobile' limit 1";
		if($this->db->getOne($sql)){
			$this->msg='手机号码已存在';
			return false;
		}else{
			$this->msg='手机号码不存在';
			return true;
		}
	}
	function checkEmail($email=''){
		if(!$email || strpos($email,'@')<1 || strlen($email)<6){$this->msg='电子邮箱格式不正确';return false;}
		$sql = "select id from qk_user where email='$email' limit 1";
		if($this->db->getOne($sql)){
			$this->msg='电子邮箱已存在';
			return false;
		}else{
			$this->msg='电子邮箱不存在';
			return true;
		}
	}
}
?>