<?php
class PrepaidcardModel extends BaseModel{
	public $msg='';
	function create($number,$amount){
			$id = $this->db->getOne("select id from `qk_prepaidcard` where number='$number'");
			if($id){ $this->msg='卡号 '.$number.' 重复';return false; }
			$password = rand(100000,999999);
			$sql = "insert into `qk_prepaidcard` set number='$number',amount='$amount',password='$password',iStatus=1,posttime=UNIX_TIMESTAMP()";
			$this->db->query($sql);
			return true;

	}
	function add($param){$param['act']='add';return $this->query($param);}
	function query($param){
		$act = $param['act'];
		$number = $param['number'];
		$start = $param['start'];
		$end = $param['end'];
		$amount = $param['amount'];
		if(!$amount || !is_numeric($amount) || $amount<=0){ $this->msg='充值卡金额需要为数字且为正数';return false; }
		if(strlen($number)>32){ $this->msg='卡号太长 不得长于32位';return false; }
		if(strpos($number,'*')===false){
			return $this->create($number,$amount);
		}else if(preg_match("/^([0-9a-zA-Z]+)\*{1,32}$/",$number) || preg_match("/^([0-9a-zA-Z]+)(\*{1,32})([0-9a-zA-Z]+)$/",$number) || preg_match("/^(\*{1,32})([0-9a-zA-Z]+)$/",$number)){
			if(!$start || !is_numeric($start)){ $this->msg='开始序号不正确';return false; }
			if(!$end || !is_numeric($end) || $end<=$start){ $this->msg='结束序号不正确';return false; }
			$strstart = '';
			$strend = '';
			if(preg_match("/^([0-9a-zA-Z]+)\*{1,32}$/",$number,$matches)){
				$strstart = $matches[1];
				$strend = '';
			}else if(preg_match("/^(\*{1,32})([0-9a-zA-Z]+)$/",$number,$matches)){
				$strstart = '';
				$strend = $matches[1];			
			}else if(preg_match("/^([0-9a-zA-Z]+)(\*{1,32})([0-9a-zA-Z]+)$/",$number,$matches)){
				$strstart = $matches[1];
				$strend = $matches[3];			
			}
			$var = preg_replace("/([0-9a-zA-Z]+)/",'',$number);
			$len = strlen($var);
			//echo $start;
			//echo $end;	
			//echo $len;
			for($i=$start;$i<=$end;$i++){
				settype($i,'integer');
				$tmp = str_replace('*','0',$var).$i;
				$number=$strstart.substr($tmp,-$len,$len).$strend;
				if(!$this->create($number,$amount)){
					return false;
				};
				//echo $number."\r\n";
			}
			$this->msg='添加成功';
			return true;
		}

			$this->msg='处理失败';return false;
	}


	function del($id){$sql = "delete from qk_prepaidcard where id='$id' limit 1";$this->msg='删除成功';return $this->db->query($sql);}
	function ajaxColEdit($param){
				$col = $param['col'];
				$val = $param['val'];
				$id = $param['id'];
				if($col && settype($id,"integer")){
					if($col=='iStatus' && $val!='0'){
						$info = $this->db->getRow("select * from qk_prepaidcard where id='$id'");
						if(!$info){$this->msg='充值卡不存在';return false;}else if($info['userId'] || $info['useoftime']){$this->msg='该充值卡已经被用户使用';return false;}
					}
					$sql = "update `qk_prepaidcard` set `$col`='$val' where id='".$id."'";
					if($this->db->query($sql)){
						return true;
					}
				}else{
					$this->msg = '参数不完整';
				}
		return false;
	}

}
?>