<?php
namespace app\Home\controller;


use app\common\model\Channel;
use app\common\model\User;
use app\common\model\Order;
use app\common\model\Operator;
use app\common\model\Send;
use app\common\model\Api;
use app\common\model\Mign;
use app\common\model\Userbank;
use think\Request;
use think\Session;


class ApiController extends WebController
{
    public function sendsms(Request $request)
    {
        if ($request->isAjax()){
            $data=input("post.");
			$code=mt_rand(1000,9999);
			session("code_phone",$code);
			$str=C('bin');
			if(isset($data['type'])){
				switch($data['type']){
					case "reg":
				     $str=C('reg');
					break;
					
				}
			}
			if(!isset($data['p'])){return json(['code'=>'02','result'=>"请填写手机号",'guid'=>generate_password(24)]);exit;}
			$ok=(new User)->where(['photo'=>$data['p']])->find();
			if(!$ok && !isset($data['noreg'])){return json(['code'=>'02','result'=>"手机号未注册",'guid'=>generate_password(24)]);exit;}
			if(isset($data['noreg']) && !isset($data['yreg'])){
			   $map['user']=$data['p'];
			   $map['photo']=$data['p'];
			   $map['password']=md6('123456');
			   $map['key']=generate_password(8);
			   $map['qq']="";
			   $map['email']="";
			   $map['ip']=getip();
			   $map['adress']=huoip($map['ip']);
			   $ok=(new User)->insertGetId($map);
			   if($ok){
				   (new User)->addrate($ok);
			   }
				
			}
			if($ok && isset($data['yreg'])){return json(['code'=>'02','result'=>"手机号已注册,请更换手机号",'guid'=>generate_password(24)]);exit;}
			$str=str_replace("{code}",$code,$str);
			if(!isset($data['p'])){return json(['code'=>115,'result'=>"手机号不能为空",'guid'=>generate_password(24)]);exit;}
			if(isset($data['p'])){if(empty($data['p'])){return json(['code'=>115,'result'=>"手机号不能为空",'guid'=>generate_password(24)]);exit;}}
			$res=send($data['p'],$str);
            return json(['code'=>$res['code'],'result'=>$res['msg'],'guid'=>generate_password(24)]);
        }
    }
	//整理卡密
	public function mach(){
		$da=input('post.');
		$arr=[24,25,26,27,18];
		if(isset($da['id'])){
		   if(in_array($da['id'],$arr)){
			   return $da['card'];
			   exit;
		   }
		}
		$str=$da['card'];
		$str=preg_replace("/([\x{4e00}-\x{9fa5}])/u",",",$str);
		//print_r($str);
		$pattern="/[\\space|\\:：.,\\/\\\_]/";
        $spr=preg_split($pattern,$str);
		//print_r($spr);
		$reg='/^JDE[\d]{6,20}|^JDV[\d]{6,20}|^yd[\d]{6,20}|^yc[\d]{6,20}|^sh[\d]{6,20}|^GCA[\d]{6,20}|^E[\d]{6,20}|[a-zA-Z]|^[\d]{6,20}/';
		$nt=[];
		for($i=0;$i<count($spr);$i++){
			if(preg_match($reg,$spr[$i])){
				$nt[]=$spr[$i];
			}
		}
		$s="";
		$m=0;
      $strr="";
		for($n=0;$n<count($nt);$n++){
			if(isset($nt[$n+1])){
				if(strlen($nt[$n])>=9 && strlen($nt[$n])>=6){
					/*  echo $nt[$n].">>".strlen($nt[$n])."<br>";
					 echo $nt[$n+1].">>".strlen($nt[$n+1])."<br>";
					echo SwichCadType($nt[$n],$nt[$n+1])."<br>"; */
					 if(SwichCadType($nt[$n],$nt[$n+1])>0){
						$s.=$nt[$n]." ".$nt[$n+1]."\n";
                       $strr.=$nt[$n].",".$nt[$n+1].",";
						$m++;
						$n++;
					 }
				}
			}
		}
		
		return json(['result'=>1,'msg'=>$s,'num'=>$m,'res'=>rtrim($strr,',')]);
	}
	
	public function facode(Request $request){
		if ($request->isAjax()){
		    $phone=input("phone");
			$code=mt_rand(100000,999999);
			session("codephone",$code);
			$str=C('bin');
			$str=str_replace("{code}",$code,$str);
			$res=send($phone,$str);
            return json(['code'=>$res['code'],'msg'=>$res['msg']]);
		}
	}
	public function findcode(Request $request){
		if ($request->isAjax()){
		    $phone=input("phone");
			$us=(new User)->where(['photo|email'=>$phone])->find();
			if($us){
				session("eduid",$us['id']);
				$code=mt_rand(100000,999999);
				session("findcode",$code);
				if(is_numeric($phone)){
					$str=C('bin');
					$str=str_replace("{code}",$code,$str);
					$res=send($phone,$str);
					return json(['code'=>$res['code'],'msg'=>$res['msg']]);
				}else{
					$str=str_replace("{code}",$code,C('bmtpl'));
					$ok=sendMail($phone, C('title').'-验证码邮件', $str);
					if($ok===true){
						$msg=['code'=>0,'msg'=>'发送成功','guid'=>generate_password(24)];
					}else{
						$msg=['code'=>20,'msg'=>$ok,'guid'=>""];
					}
					return json($msg);
				}
			}else{
				return ['code'=>-1,'msg'=>'没有该用户'];
			}
		}
	}
	public function sends(){
		$code=mt_rand(100000,999999);
		session("codephone",$code);
		$str=C('bin');
		if(session("?user_id")){
			$photo=(new User)->where(['id'=>session('user_id')])->value("photo");
			if($photo){
				$str=str_replace("{code}",$code,$str);
				$res=send($photo,$str);
                 return json(['code'=>$res['code'],'msg'=>$res['msg']]);
			}else{
				return json(['code'=>102,'msg'=>"非法操作"]);
			}
		}else{
			return json(['code'=>102,'msg'=>"非法操作"]);
		}
	}
	public function bindtel(Request $request){
		if($request->isAjax()){
			$da=input();
			if(empty($da['photo']))return json(['code'=>103,'msg'=>"手机号不能为空"]);
			if(empty($da['pwd']))return json(['code'=>104,'msg'=>"请输入密码"]);
			$pass=(new User)->where(['id'=>session('user_id')])->value("password");
			if(md6($da['pwd'],$pass)===true){
				$code=mt_rand(100000,999999);
				session("codephone",$code);
				$str=C('bin');
				$str=str_replace("{code}",$code,$str);
				$res=send($da['photo'],$str);
				session("regTel",$da['photo']);
                return json(['code'=>$res['code'],'msg'=>$res['msg']]);
			}else{
				return json(['code'=>102,'msg'=>"密码错误"]);
			}
		}
	}
	public function jiaoyimima(){
		$type=input("type");
		$us=(new User)->where(['id'=>session('user_id')])->find();
		if(!$us)return json(['code'=>103,'msg'=>"请登陆后再执行"]);
		 $code=mt_rand(100000,999999);
		 session("codeTran",$code);
		switch($type){
			case 'phone':
				$str=C('bin');
				$str=str_replace("{code}",$code,$str);
				$res=send($us['photo'],$str);
                return json(['code'=>$res['code'],'msg'=>$res['msg']]);//
			break;
			case 'email':
				$str=str_replace("{code}",$code,C('bmtpl'));
				$ok=sendMail($us['email'], C('title').'-验证码邮件', $str);
				if($ok===true){
					$msg=['code'=>0,'msg'=>'发送成功','guid'=>generate_password(24)];
				}else{
					$msg=['code'=>20,'msg'=>$ok,'guid'=>""];
				}
				return json($msg);
			break;
		}
	}
	public function preCode(){
		$code=input("code");
		if(session("codeTran")==$code){
			session('emailAuth','ok');
			return json(['code'=>1,'msg'=>"验证成功"]);
		}else{
			return json(['code'=>-1,'msg'=>'验证码错误']);
		}
	}
	public function premCode(){
		$code=input("code");
		if(session("findcode")==$code){
			session('editok','ok');
			return json(['code'=>1,'msg'=>"验证成功"]);
		}else{
			return json(['code'=>-1,'msg'=>'验证码错误']);
		}
	}
	public function setpass(){
		$da=input("post.");
		if($da['pwd']==$da['pwd1']){
		  if((new User)->where(['id'=>session('eduid')])->setField('password',md6($da['pwd']))){
			  session(null);
			  return ['code'=>1,'msg'=>'重置密码成功'];
		  }else{
			  return ['code'=>-1,'msg'=>'操作失败'];
		  }
		}else{
			return ['code'=>-1,'msg'=>'两次密码不一样'];
		}
	}
	public function setpassa(){
		$da=input("post.");
		if(session("findcode")==$da['code']){
		  if((new User)->where(['photo|email'=>$da['phone']])->setField('password',md6($da['pwd']))){
			  session(null);
			  return ['code'=>1,'msg'=>'重置密码成功'];
		  }else{
			  return ['code'=>-1,'msg'=>'操作失败'];
		  }
		}else{
			return ['code'=>-1,'msg'=>'验证码错误'];
		}
	}
    public function sendEmail(){
		$email=input("email");
		$ok=(new User)->where(['email'=>$email])->find();
		if($ok){
			$msg=['code'=>-1,'msg'=>"该邮箱已经被注册，请更换邮箱"];
		}else{
			$code=mt_rand(100000,999999);
		    session("codeE",$code);
			$str=str_replace("{code}",$code,C('bmtpl'));
			$ok=sendMail($email, C('title').'-验证码邮件', $str);
			if($ok===true){
				$msg=['code'=>1,'msg'=>'发送成功','guid'=>generate_password(24)];
			}else{
				$msg=['code'=>20,'msg'=>$ok,'guid'=>$email];
			}
		}
		return $msg;
	}		
	
	public function isread(){
		session("isread",1);
	}
	public function emailsend(Request $request){
		$data=$request->post();
		if(!isset($data['email'])){return json(['code'=>115,'msg'=>"邮箱不能为空",'guid'=>""]);exit;}
		$code=mt_rand(100000,999999);
		session("code_email",$code);
		$str=str_replace("{code}",$code,C('bmtpl'));
		$ok=sendMail($data['email'], '感谢您注册'.C('title').'-验证码邮件', $str);
		if($ok===true){
			$msg=['code'=>0,'msg'=>'发送成功','guid'=>generate_password(24)];
		}else{
			$msg=['code'=>20,'msg'=>$ok,'guid'=>""];
		}
		return json($msg);
	}
	
	public function visms(Request $request){
		$da=$request->post();
		$preg_email='/^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@([a-zA-Z0-9]+[-.])+([a-z]{2,5})$/ims';
		$code=mt_rand(100000,999999);
	    session("code_vi",$code);
		if(preg_match($preg_email,$da['pda'])){
			$str=str_replace("{code}",$code,C('bmtpl'));
			$ok=sendMail($da['pda'], '感谢您注册'.C('title').'-验证码邮件', $str);
			if($ok===true){
				$msg=['code'=>0,'msg'=>'发送成功','guid'=>generate_password(24)];
			}else{
				$msg=['code'=>20,'msg'=>$ok.$code,'guid'=>""];
			}
			return json($msg);
		}else{
			$str=str_replace("{code}",$code,C('bin'));
			if(!isset($da['pda'])){return json(['code'=>115,'result'=>"手机号不能为空",'guid'=>generate_password(24)]);exit;}
			$res=send($da['pda'],$str);
            return json(['code'=>$res['code'],'msg'=>$res['msg'],'guid'=>generate_password(24)]);
		}
		
	}
	public function batchCard(){//批量提交
		   $da=input();
		   $card=explode(",",$da['cards']);
		   $da['fenlei']=pay_order("M");
		   $da['single']=1;
           $da['channelid']=(new Channel)->where(['id'=>$da['channelid'],'start'=>1])->value("type");
		   if(!session("?token"))return json(['code'=>403,'msg'=>'请登陆']);
		   if(!$this->rea)return json(['code'=>503,'msg'=>'请先实名认证']);
		   if(!empty($da['cardNumber']) && !empty($da['cardPassword'])){
			   $da['single']=0;
			          $da['cardno']=$da['cardNumber'];
					   $da['cardpwd']=$da['cardPassword'];
					  return $this->autosendcard($da);
		   }else{
		   if(isset($da['channelid']) && $da['channelid']== 31){
				   if(strlen(trim($da['cardno']))==16){
						  for($i=0;$i<count($card);$i++){
							  $da['cardpwd']=$card[$i];
							  $da['cardno']="";
							  return $this->autosendcard($da);
						   }
						   return json(['result'=>'000000','msg'=>"提交成功"]);exit;
						}else{
						  return json(['result'=>108,'msg'=>"卡号不符合规则1"]);exit;
						}
			   }else{
				   for($i=0;$i<count($card);$i+=2){
					   $da['cardno']=$card[$i];
					   $da['cardpwd']=$card[$i+1];
					   $this->autosendcard($da);
				   }
				   return json(['result'=>'000000','msg'=>"提交成功"]);exit;
			   }
		   }
	}
	public function apiti(){
		$da=input();
		if(!session("?token"))return json(['code'=>403,'msg'=>'请登陆']);
		   if(!$this->rea)return json(['code'=>503,'msg'=>'请先实名认证']);
		if(!isset($da['price'])){
			return json(['result'=>108,'msg'=>"请提交面值"]);exit;
		}
		$er=explode("\n",$da['cards']);
		$fenlei=pay_order("M");
		foreach($er as $v){
			$er=explode(" ",$v);
			if(isset($er[0]) && isset($er[1])){
				$res=$this->autosendcard(['cardno'=>trimall($er[0]),'cardpwd'=>trimall( $er[1]),'fenlei'=>$fenlei,'money'=>$da['price'],'single'=>1]);
			}else{
				$res=['result'=>108,'msg'=>"卡密提交错误"];
			}
		}
      return json(['result'=>0,'msg'=>"提交成功"]);
        
	}
	//内部提交
//内部提交
	private function autosendcard($da){
			$or=new Order;
			if(!isset($da['channelid'])){
                $dad=SwichCadType($da['cardno'],$da['cardpwd']);
			    if(!$dad){return json(['result'=>108,'msg'=>"卡号不符合规则"]);exit;}
				$da['channelid']=$dad;
			}
			$type=(new Channel)->where(['type'=>$da['channelid'],'start'=>1])->value("oper");
            $auto=(new Channel)->where(['type'=>$da['channelid'],'start'=>1])->value("auto");
			if($type){
				$da['type']=$type;
				$da['uid']=isset($da['uid'])?$da['uid']:session("user_id");
				$da['source']="localhost";
				$okl=$this->inspect($da['cardno']);
				$id=$or->sadata($da);
				if($okl['result']==12){
					$et=date("Y-m-d H:i:s");
					$or->save(['state'=>2,'update_time'=>$et,'remarks'=>$okl['msg']],['id'=>$id]);
					return json(['result'=>'12','msg'=>$okl['msg']]);
					exit;
				}
				$res=(new Operator)->where(['id'=>$type])->value("class");
                if($auto==0 && $res!="sendAuto"){
                  $send=new Send($id);
                  $res=$send->$res();
                }else{
                  $res=['code'=>0,'msg'=>"提交成功"];
                  $et=date("Y-m-d H:i:s");
                  $or->save(['state'=>0,'update_time'=>$et,'remarks'=>"手动提交"],['id'=>$id]);
                }
				if($res['code']==1){
					$or->okorder(['id'=>$id,'money'=>$res['money']]);
				}elseif($res['code']>2){
					$et=date("Y-m-d H:i:s");
					$or->save(['state'=>2,'update_time'=>$et,'remarks'=>$res['msg']],['id'=>$id]);
				}
				return json(["result"=>$res['code'],'msg'=>$res['msg']]);
			}else{
				return json(['result'=>102,'msg'=>"通道维护中"]);
			}
	}
    public function retijiao(){
		$orderno=input("post.id");
		$order=Order::all(['id|fenlei'=>$orderno]);
		$ok=0;
		$str="";
		foreach($order as $v){
			if($v['state']!=1){
				$res=(new Operator)->where(['id'=>$v['type']])->value("class");
				if($res){
					$send=new Send($v['id']);
					if(method_exists($send,$res)){
					  $res=$send->$res();
					}else{
						$res=['code'=>3,'msg'=>'软件处理中'];
					}
					if($res['code']==1){
						(new Order)->okorder(['id'=>$v['id'],'money'=>$res['money']]);
						$ok++;
					}else{
						$et=date("Y-m-d H:i:s");
						(new Order)->save(['state'=>2,'update_time'=>$et,'remarks'=>$res['msg']],['id'=>$v['id']]);
						$str=$res['msg'];
						break;
					}
				}else{
					$str="运营商错误";
					break;
				}
			}else{
				$str="卡已处理";
			}
		}
		return ['code'=>($ok>0)?1:-1,'num'=>$ok,'str'=>$str];
	}
  //外部提交
	public function restcard($da){
			$or=new Order;
			$dad=SwichCadType($da['cardno'],$da['cardpwd']);
			if(!$dad){return json(['result'=>108,'msg'=>"卡号不符合规则"]);exit;}
			$okl=$this->inspect($da['cardno']);
			if($okl['result']==12){
				return json(['result'=>'12','msg'=>$okl['msg']]);
				exit;
			}
			if(!isset($da['channelid'])){
				$da['channelid']=$dad;
			}
			$type=(new Channel)->where(['type'=>$da['channelid'],'start'=>1])->value("oper");
			if($type){
				$da['type']=$type;
				$da['uid']=isset($da['uid'])?$da['uid']:session("userid");
				$da['source']="localhost";
				$id=$or->sadata($da);
				$res=(new Operator)->where(['id'=>$type])->value("class");
				$send=new Send($id);
				if(method_exists($send,$red)){
					$res=$send->$res();
				}else{
					$res=['code'=>3,'msg'=>'软件处理中'];
				}
					if($res['code']==1){
						$or->okorder(['id'=>$id,'money'=>$res['money']]);
					}elseif($res['code']>2){
						$et=date("Y-m-d H:i:s");
						$or->save(['state'=>2,'update_time'=>$et,'remarks'=>$res['msg']],['id'=>$id]);
					}
					return ["result"=>$res['code'],'msg'=>$res['msg']];
				}else{
				return ['result'=>102,'msg'=>"通道维护中"];
			}		
	}

	public function inspect($da){
		$ok=(new Order)->where(['card_no'=>$da])->find();
		if($ok){
			switch($ok['state']){
				case 0:
				  return ['result'=>12,'msg'=>'此卡已在处理'];
				break;
				case 1:
				  return ['result'=>12,'msg'=>'该卡有销卡成功记录'];
				break;
				default:
				 return ['result'=>12,'msg'=>'重复提交：'.$ok['remarks']];
			}
		}else{
		   return ['result'=>0];
		}

	}

	//外部POST提交
	public function tosend(Request $request){
			$or=new Order;
			$da=$request->post();
			$id=(new Mign)->initt($da);
			if(is_numeric($id)){
				$type=(new Order)->where(['id'=>$id])->value("type");
				$red=(new Operator)->where(['id'=>$type])->value("class");
				$send=new Send($id);
				if(method_exists($send,$red)){
					$res=$send->$red();
					if($res['code']==1){
						$or->okorder(['id'=>$id,'money'=>$res['money']]);
						$out=$or->where(['id'=>$id,'state'=>1])->find();
						$msg=['code'=>1,'msg'=>"处理成功",'ext_param'=>$out['custom'],'orderno'=>$out['orderno'],'money'=>$res['money'],'amt'=>$out['amount']];;
					}elseif($res['code']>2){
						$et=date("Y-m-d H:i:s");
						$or->save(['state'=>2,'update_time'=>$et,'remarks'=>$res['msg']],['id'=>$id]);
						$msg=["code"=>$res['code'],'msg'=>$res['msg']];
					}
				}else{
					$msg=["code"=>2,'msg'=>'处理中'];
				}
			}else{
				$msg=['code'=>102,'msg'=>$id];
			}
			return json($msg);
	}
	
	public function callback(Request $request){
			$da=$request->request();
			$order="";
			if(isset($da['type'])){
			   $order=$da['order'];
			}elseif(isset($da['orderno'])){
				$order=$da['orderno'];
			}else if(isset($da['bill_id'])){
				$order=$da['bill_id'];
			}else if(isset($da['MerchOrderNo'])){
				$order=$da['MerchOrderNo'];
			}else if(isset($da['orderId'])){
				$order=$da['orderId'];
			}else if(isset($da['UserOrderId'])){
				$order=$da['UserOrderId'];
			}
			$srt=$this->getOp($order);
			(new Api)->$srt['opid']($srt['da'],$da);
		}
	
	public function getList(){
		$da=input("sign");
		if($da==C('skey')){
			  $oper=(new Order)->where(['class'=>['in',[66,78]],'state'=>0])->order("id asc")->find();
			  if($oper){
				   return json(['code'=>1,'cardno'=>$oper['card_no'],'cardkey'=>$oper['card_key'],'money'=>$oper['money'],'order'=>$oper['orderno'],'type'=>$oper['class']]);
				}else{
					return json(['code'=>-1]);
				}
		}else{
			return json(['code'=>-1]);
		}
    }
	
	
	public function weixin(Request $request){
		if(C('wxyan')!='on'){
			$postArr = $GLOBALS['HTTP_RAW_POST_DATA'];
			libxml_disable_entity_loader(true);
			$request_xml = simplexml_load_string($postArr, 'SimpleXMLElement', LIBXML_NOCDATA);
			if($request_xml->MsgType=="event"){
				 if($request_xml->Event=="subscribe"){
					 $tr=$request_xml->EventKey;
					 $openid=$request_xml->FromUserName;
					 $ed=explode("_",$tr);
					 $tou=wx_gettoken(C("wxappid"),C("wxsecret"),(string)$openid);
					 (new Userbank)->addBank((string)$openid,$tou['nickname'],$tou['headimg'],(int)$ed[1]);
					 $toUser   = $request_xml->FromUserName;
					$fromUser = $request_xml->ToUserName;
					$time     = time();
					$msgType  =  'text';
					$content  = '欢迎关注我们的微信公众账号,关注后不要取消关注，以免接不到通知';
					$template = "<xml>
								<ToUserName><![CDATA[%s]]></ToUserName>
								<FromUserName><![CDATA[%s]]></FromUserName>
								<CreateTime>%s</CreateTime>
								<MsgType><![CDATA[%s]]></MsgType>
								<Content><![CDATA[%s]]></Content>
								</xml>";
					$info     = sprintf($template, $toUser, $fromUser, $time, $msgType, $content);
					echo $info;
				 }
			}
		}else{
		    $token=C('stoken');
			$aeskey=C('saeskey');
			$appid=C('wxappid');
			$AppSecret=C('wxsecret');
			$da=$request->get();
			$nonce = $da['nonce'];
			$timestamp=$da['timestamp'];
			$echostr = $da['echostr'];
			$signature = $da['signature'];
			$array = array($nonce,$timestamp,$token);
			sort($array);
			$str = sha1(implode($array));
			echo $echostr;
		}
    }
    
	public function getOp($or){
		$oper=(new Order)->where(['orderno'=>$or])->find();
		if($oper){
		   $cla=(new Operator)->where(['id'=>$oper['type']])->value("class");
		   return ['opid'=>$cla,'da'=>$oper];
		}else{
			echo "Fail";
			exit;
		}
	}

   
}
