<?php
use Addons\QyWechat\Services\ProvidersApi;
use Addons\QyWechat\Helper;
use EasyWeChat\Factory;

$domain=$_SERVER['HTTP_HOST'];
$agency=new Model('user_agency');
$agency->find(array('domain'=>$domain));
$is_scan=$agency->is_scan;
// dump($agency);die;
// qvmh_qy_agency_thirdappsetting
$thirdappsetting=(new Model('qy_agency_thirdappsetting'))->find(['pid'=>$agency->id]);
// dump($setdata);die;
$h = Helper::getInstance();
$ProvidersApi = ProvidersApi::getInstance();
$redirect_uri = urlencode($h->get_http_server_name() . '/login.html');
// $agency->recharge_appid
$qyurl="https://open.work.weixin.qq.com/wwopen/sso/3rd_qrConnect?appid=".$thirdappsetting->corpid."&redirect_uri=".$redirect_uri."&state=web_login@gyoss9&usertype=admin";
// dump($_GET);
if($_GET['auth_code']){
	Page::ignore_view();
	$config = [
		'corp_id'          => $thirdappsetting->corpid?$thirdappsetting->corpid:'',
		'secret'           => $thirdappsetting->providerSecret?$thirdappsetting->providerSecret:'',
		'suite_id'         => $thirdappsetting->suite_id?$thirdappsetting->suite_id:'',
		'suite_secret'     => $thirdappsetting->suite_secret?$thirdappsetting->suite_secret:'',
		'token'            => $thirdappsetting->token?$thirdappsetting->token:'',
		'aes_key'          => $thirdappsetting->encodingAESKey?$thirdappsetting->encodingAESKey:'',
		'reg_template_id'  => '',

	 ];
	 $app = Factory::openWork($config);

	 $userinfo=$app->provider->getLoginInfo($_GET['auth_code']);
	//  dump($userinfo);d
	//  qvmh_qy_providers_permanent_code
	 if($userinfo['corp_info']['corpid']){
		// $corpinfo=(new Model('qy_providers_permanent_code'))->find(['corpid'=>$userinfo['corp_info']['corpid']]);
		$corpinfo=(new Model('qy_wechat_config'))->find(['corp_id'=>$userinfo['corp_info']['corpid']]);
		if($corpinfo->corp_id){
			//
			// dump($corpinfo);
			// $user_inf=(new Model('qy_user_list'))->find(['wid'=>$corpinfo->wid,'userid'=>$userinfo['user_info']['userid']]);
			// dump($user_inf);die;
			// if($user_inf->id){
				$user_i=(new Model('pubs'))->find(['id'=>$corpinfo->wid]);
				// dump($user_i);
				$c_uu=(new Model('user'))->find($user_i->uid);
					// Cookie::set('weixinid',$c_uu->id);
					// Cookie::set('weixinuuid',md5(Conf::$management_center_password.$c_uu->id));
					
				set_user_login($c_uu);
			// }else{
			// 	// echo '你不是该企业授权员工!';
			// 	echo "<meta http-equiv='Refresh' content='1;URL=http://{$_SERVER['HTTP_HOST']}/login.html'>";
			// 	die();
			// }
			
		}else{
			echo '<script>alert("该企业暂未入驻!");</script>';
			// $pUrl = $h->get_http_server_name() . '/login.html';
			echo "<meta http-equiv='Refresh' content='1;URL=http://{$_SERVER['HTTP_HOST']}/login.html'>";
			// \Redirect::to("{$pUrl}");
			die();
		}
	 }else{
		echo '<script>alert("授权失败!");</script>';
		// $pUrl = $h->get_http_server_name() . '/login.html';
		echo "<meta http-equiv='Refresh' content='1;URL=http://{$_SERVER['HTTP_HOST']}/login.html'>";
		// \Redirect::to("{$pUrl}");
		die();
	 }
	
	 
}

function parse_qq_callback($response){
	if(strpos($response, "callback") !== false){
		$lpos = strpos($response, "(");
		$rpos = strrpos($response, ")");
		$response  = substr($response, $lpos + 1, $rpos - $lpos -1);

		$msg = json_decode($response,true);

		if(isset($msg['error'])){
			Redirect::to('/main');
		}
		return $msg;
	}
	Redirect::to('/main');
}

if(Request::get('uid') && Request::get('upwd')){
	$u = new Model('user');
	$u->find(Request::get('uid'));
	
	// if($u->has_id() && md5($u->pwd)==Request::get('upwd')){
		if($u->has_id() && $u->pwd==Request::get('upwd')){
		set_user_login($u);
	}
}

$gkw = "DOXCX";
$gde = "DOXCX";
$gti = "DOXCX";

$u = new SampleModel();
function set_user_login($mu){
	Auth::im_user();
    Session::set('wid',$mu->id);
	Session::set('uid',$mu->id);
	Session::set('mainuid',$mu->id);
	$uid = Session::get('uid');
	// dump($mu);
	// dump($uid);
	// dump($_SESSION);die;
	//user_upgrade($uid);
	if(!Session::has('level_id')){
		Session::set('level_id',$mu->level_id);
	}
	Session::set('un',$mu->un);
	Session::set('ue',$mu->email);
	Session::set('ut',$mu->telephone);
	Session::set('upc',$mu->ispwdcg);

	if($mu->isadmin=='a'){
		Auth::im_admin('admin');
	}
	Session::set('upath','/ups/'.date('Y/m',strtotime($mu->rtime)).'/'.$mu->id.'/');
	File::creat_dir(DOXCX_FRAME_PATH.DOXCX_PUB.'/'.Session::get('upath'));
	Session::set('headpic',trim($mu->headpic));
	Cookie::set('uid',$mu->id);
	$pub =(new Model("pubs"))->where(['uid'=>$mu->id])->find();
	if($pub->id)Cookie::set('wid',$pub->id);
	Cookie::set('uuid',md5($mu->un.Request::ip().$mu->pwd));
    Cookie::set('ts','1');
	Redirect::to('/start');
}


if($u->try_post()){
	// dump($u);die;
		$mu = new Model('user');
		$mu->un = $u->un;
		$mu->pwd = md5($u->pwd);
		$mu->email = $u->un;
		$mu->telephone = $u->un;
		if(!empty($u->un) && !empty($u->pwd) && ($mu->is_real(array('un','pwd')) || $mu->is_real(array('email','pwd')) || $mu->is_real(array('telephone','pwd')))){
			if($mu->isstop != '0'){
				Page::view('login');
				tusi('账号审核中或已停用,请联系管理员');
			}else if(strtotime($mu->mendtime)<time()){
				Page::view('login');
				tusi('账号已经到期,请联系管理员升级续费');
			}else{
				if('1'== Request::post('remme')){
					//记住登录
					Cookie::set('weixinid',$mu->id);
					Cookie::set('weixinuuid',md5(Conf::$management_center_password.$mu->id));
				}
				set_user_login($mu);
			}

		}else{
			$u->pwd = '';
			Page::view('index');
			tusi('登录信息不正确');
		}
}else if(Cookie::has('weixinid')){
	$uid = Cookie::get('weixinid');
	$uuid = Cookie::get('weixinuuid');
	if($uuid==md5(Conf::$management_center_password.$uid)){
		$mu = new Model('user');
		$mu->find($uid);
		set_user_login($mu);
	}
}
if($_SERVER['IS_OEM']){
	Page::view('login');
}
//会员升级或降级操作
function user_upgrade($uid){
	$user = new Model('user');
	$user->find($uid);
	Session::remove('level_id');
	/**
	// uesr upgrade
	if((strtotime($user->mendtime) < time() || $user->level_id == 1) && $user->next_level_id != 0){
		$user->level_id = $user->next_level_id;
		Session::set('level_id',$user->next_level_id);
		$user->mendtime = $user->next_mendtime;
		if($user->save()){
			$user->next_level_id = '';
			$user->next_mendtime = '';
			$user->save();
			return true;
		}
	}
	//user donwgrading
	if(strtotime($user->mendtime)<time() && $user->next_level_id == 0){
		$user->level_id = 1;
		Session::set('level_id',1);
		$user->mendtime = '';
		$user->save();
		return true;
	}
	*/
	if(strtotime($user->mendtime)<time()){
		$user->level_id = 1;
		Session::set('level_id',1);
		$user->mendtime = '';
		$user->save();
	}else{
		Session::set('level_id',$user->level_id);
	}
}

//注册
$reg = new SampleModel();
$register_check=$agency->register_check;
if(Request::post('register')=='register'){
$ut= new Model('user_register');
$ut->find(1);
if($ut->has_id()){
	$registerlevel=$ut->registerlevel;
	$registerdays=$ut->registerdays;
	$registerisstop=$ut->registerisstop;
}else{
	$registerlevel=1;
	$registerdays=7;
	$registerisstop=0;
}
$domain=$_SERVER['HTTP_HOST'];
$agency=new Model('user_agency');
$agency->find(array('domain'=>$domain));
$agid=$agency->id;
$pagetype=$agency->user_pc;
$register_check=$agency->register_check;
if($reg->try_post()){
	if(!$agency->isadmin){//当前用户不是管理员
		$agencyCheck=new Model('user_agency');
		$agencyCheck->find($agency->pid);//代理商上级用户
		if($agencyCheck->isadmin && !$agency->isyg ){//如果是一级代理并且不是员工
			//当前一级代理允许开通的用户量
			$taoshu = new Model('agency_taoshu');
			$jgres = $taoshu->find($agency->level);
			$usercount=$jgres->usercount+$agency->taoshu;
			//一级代理的用户量
			$users=new Model('user');
			$counts=$users->where(array('agid'=>$agency->id))->count();
			//一级代理下级代理开通的总套数加上开通的用户量总和
			$allTaosu=totals($agency->id)+$counts;
			if($jgres->usercount!=0){//如果限制用户量的话
				if($usercount<=$allTaosu){
					//tusi('当前网站用户量已达上限');
					echo '<script type="text/javascript">alert("当前网站用户量已达上限!");</script>';
					exit;
					$taoshuCheck=1;
				}
			}
		}else if(!$agencyCheck->isadmin){//不是一级代理
			$users=new Model('user');
			$counts=$users->where(array('agid'=>$agency->id))->count();
			//代理商下级代理开通的总套数加上开通的用户量总和
			$allTaosu=totals($agency->id)+$counts;
			if($allTaosu>=$agency->taoshu){
				//tusi('当前网站用户量已达上限');
				echo '<script type="text/javascript">alert("当前网站用户量已达上限!");</script>';
				exit;
				$taoshuCheck=1;
			}
		}
   }
    $mu = new User();
    $mu->un = Request::post('telephone');
    $mu->pwd = $reg->pwd;
    $mu->email = $reg->email;
    $mu->telephone = Request::post('telephone');
	$mu->agid=$agid;
	$mu->pagetype=$pagetype;
	//默认注册用户关闭，如果新注册用户需要审核，请把此项注释去掉(暂时不用)
    //$mu->isstop = 1;

	//获取后台设置是否审核
	$mu->isstop=$registerisstop;

	//注册用户时间
	$mu->rtime = date('Y-m-d h:i:s',time());
	//用户试用时间为1周(暂时不用)
	//$mu->mendtime = date('Y-m-d h:i:s',strtotime('+1 week'));

	//获取后台设置天数
	/**if($registerlevel!=1){
		$mu->mendtime=date('Y-m-d',time()+86400*$registerdays);
	}*/
	$mu->mendtime=date('Y-m-d',time()+86400*$registerdays);

	//获取后台设置级别
	$mu->level_id =$registerlevel;

	$yzm=Request::post('yzm');
	$code = Cache::get('sms_code');
	$telephone=Request::post('telephone');
	if($taoshuCheck!=1){
		if($register_check==1&&($yzm==null||$yzm!=$code)){
			//tusi('验证码错误');
			echo '<script type="text/javascript">alert("验证码错误!");</script>';
			exit;
		}elseif(!empty($telephone) && !empty($reg->pwd) && !$mu->is_real('un')) {
			$mu->pwd = md5($reg->pwd);
			$info = $mu->save();
			if($mu->errors()){
				foreach($mu->errors() as $item){
					$msg .= implode(',',array_values($item));
				}
			}
			$msg = $msg ?  : '注册已成功!' ;
			//tusi($msg);
			echo "<script>alert('".$msg."');</script>";
			//$info && Redirect::delay_to('/login',3);
		} elseif ($mu->is_real('un')) {
			//tusi('用户名已存在，请重新填写');
			echo '<script type="text/javascript">alert("用户名已存在，请重新填写");</script>';
			exit;
		}
	}

}
}
//查询当前代理商无限极下级代理总套数
function totals($id){
	static $all;
	$agency=new Model('user_agency');
	$aglist=$agency->where(array('pid'=>$id))->order('id')->list_all();
	foreach($aglist as $as){
		if($as->id){
			$taoshu=$as->taoshu;
			$all=$all+$taoshu;
			totals($as->id);
		}
	}
	return $all;
}
