<?php
namespace app\app\controller;

use think\Request;
use think\Db;
/**
*生长激素缺乏症小程序
*/
class Ghdwechat extends Base{
	//小程序appid
	private $Appid;
	//小程序秘钥
	private $Appsecret;
	//商户号
	//private $Mch_id;
	//商户key
	//private $Key;
	//访问令牌加密秘钥
	private $TokenKey;
	public function __construct(){
		$this->Appid='wxa75a76964ae7ce73';
		$this->Appsecret='e14af51b729cabdbb232147ce9ad8b30';
	//	$this->Mch_id='1611903889';
	//	$this->Key='b046hjZnS6ioMacttGA66ffae887e55f';
		$this->TokenKey='ghd340u20k4se309sa';
	}
	/********************************* 首页 *********************************/
	  /**
	  *查询资讯列表
	  */	
	public function selectRealtimeInfoList(Request $request){
		$post=$request->param();
	/*	if(!isset($post['uid']) || empty($post['uid']) ){
			$result['erro'] = -1;
		        $result['msg'] = "未传入用户id";
			return json_encode($result);
		}*/
		$page = isset($post['page']) && !empty($post['page']) ? $post['page'] : 1;//页数
    		$page_size = isset($post['page_size']) && !empty($post['page_size']) ? $post['page_size'] : 20;//每页条数
    		// 查询列表
	    	$res = Db::name('wechat_real_time_info')
		       		->field('title_plain,thumbnail,excerpt_plain,url')
		    			->order('create_time desc')
		    			->paginate($page_size,false,['page'=>$page]);
	    	
	    	$result = array();
	    	$result['lists'] =$res->items();
	    	$result['lastPage'] = $res->lastPage();//总页数
		$result['currentPage'] = $res->currentPage();//当前页
	//	$result['total'] = $res->total();//数据总条数
		$result['erro'] = 0;
		$result['msg'] = '查询成功';
		return json($result);
	}
	/********************************* 首页 *********************************/
	/********************************* 计算 *********************************/
	/***
	*计算
	**/
	public function calculate(Request $request){
		$post=$request->param();
		if(!isset($post['uid']) || empty($post['uid']) ){
			$result['erro'] = -1;
		        $result['msg'] = "未传入用户id";
			return json_encode($result);
		}
		if(!isset($post['name']) || empty($post['name']) ){
			$result['erro'] = -1;
		        $result['msg'] = "未传入姓名";
			return json_encode($result);
		}
		if(!isset($post['age']) || empty($post['age']) || !is_numeric($post['age'])){
			$result['erro'] = -1;
		        $result['msg'] = "未传入年龄";
			return json_encode($result);
		}
		if(!isset($post['height']) || empty($post['height']) || !is_numeric($post['height'])){
			$result['erro'] = -1;
		        $result['msg'] = "未传入身高";
			return json_encode($result);
		}
		if(!isset($post['bone_age']) || empty($post['bone_age']) || !is_numeric($post['bone_age'])){
			$result['erro'] = -1;
		        $result['msg'] = "未传入骨龄";
			return json_encode($result);
		}
		if(!isset($post['father_height']) || empty($post['father_height']) || !is_numeric($post['father_height'])){
			$result['erro'] = -1;
		        $result['msg'] = "未传入父亲身高";
			return json_encode($result);
		}
		if(!isset($post['mother_height']) || empty($post['mother_height']) || !is_numeric($post['mother_height'])){
			$result['erro'] = -1;
		        $result['msg'] = "未传入母亲身高";
			return json_encode($result);
		}
		if(!isset($post['LH']) || empty($post['LH']) || !is_numeric($post['LH'])){
			$result['erro'] = -1;
		        $result['msg'] = "未传入LH或数据格式不对";
			return json_encode($result);
		}
		if(!isset($post['IGF']) || empty($post['IGF'])  || !is_numeric($post['IGF'])){
			$result['erro'] = -1;
		        $result['msg'] = "未传入IGF或数据格式不对";
			return json_encode($result);
		}
		//子宫厚度
		if(!isset($post['uterus_thickness']) || empty($post['uterus_thickness'])  || !is_numeric($post['uterus_thickness'])){
			$result['erro'] = -1;
		        $result['msg'] = "未传入uterus_thickness或数据格式不对";
			return json_encode($result);
		}
		
		//计算
		//计算公式 P= (exp(-5.908+0.008*IGF-1+2.146*LH+0.286*子宫（厚）))/(1 + exp(-5.908+0.008*IGF-1+2.146*LH+0.286*子宫（厚）))
		$exp = exp(-5.908 + 0.008*$post['IGF'] + 2.146*$post['LH'] + 0.286*$post['uterus_thickness']); 
		$probability = $exp / (1 + $exp); 
		
		//保存记录数据
		$data=[];
		$data['id']=md5(time().rand(100000,999999));
		$data['uid']=$post['uid'];
		$data['name']=$post['name'];
		$data['age']=$post['age'];
		$data['height']=$post['height'];
		$data['bone_age']=$post['bone_age'];
		$data['father_height']=$post['father_height'];
		$data['mother_height']=$post['mother_height'];
		$data['IGF']=$post['IGF'];
		$data['LH']=$post['LH'];
		$data['uterus_thickness']=$post['uterus_thickness'];
		$data['calculate_resutlt']=round($probability,3);
		$data['create_time']=date('Y-m-d H:i:s');
		$res=Db::name('wechat_calculate_record')->insert($data);
		if($res===false){
			$result['erro'] = -1;
			$result['msg'] = "计算失败";
			return json_encode($result);
		}else{
			$result['erro'] = 0;
			$result['msg'] = "计算成功";
			$result['calculate_resutlt'] = $data['calculate_resutlt'];
			return json_encode($result);
		}
	}
	  /**
	  *查询历史记录列表
	  */	
	public function selectRecordList(Request $request){
		$post=$request->param();
		if(!isset($post['uid']) || empty($post['uid']) ){
			$result['erro'] = -1;
		        $result['msg'] = "未传入用户id";
			return json_encode($result);
		}
		$page = isset($post['page']) && !empty($post['page']) ? $post['page'] : 1;//页数
    		$page_size = isset($post['page_size']) && !empty($post['page_size']) ? $post['page_size'] : 30;//每页条数
    		// 查询列表
	    	$res = Db::name('wechat_calculate_record')
		       		->field('id,name,age,height,bone_age,father_height,mother_height,IGF,LH,uterus_thickness,calculate_resutlt,create_time')
		       		->where('uid',$post['uid'])
		    			->order('create_time desc')
		    			->paginate($page_size,false,['page'=>$page]);
	    	
	    	$result = array();
	    	$result['lists'] =$res->items();
	    	$result['lastPage'] = $res->lastPage();//总页数
		$result['currentPage'] = $res->currentPage();//当前页
	//	$result['total'] = $res->total();//数据总条数
		$result['erro'] = 0;
		$result['msg'] = '查询成功';
		return json($result);
	}
	  /**
	  *删除历史记录
	  */	
	public function deleteRecord(Request $request){
		$post=$request->param();
		if(!isset($post['uid']) || empty($post['uid']) ){
			$result['erro'] = -1;
		        $result['msg'] = "未传入用户id";
			return json($result);
		}
		if(!isset($post['id']) || empty($post['id']) ){
			$result['erro'] = -1;
		        $result['msg'] = "请选择要删除的记录";
			return json($result);
		}
		$id=Db::name('wechat_calculate_record')->where('id',$post['id'])->where('uid',$post['uid'])->value('id');
		if(empty($id)){
			$result['erro'] = -1;
		        $result['msg'] = "该记录异常，无法删除";
			return json($result);
		}
    		$res=Db::name('wechat_calculate_record')->where('id',$id)->delete();
    		if($res > 0){
			$result['erro'] = 0;
			$result['msg'] = '删除成功';
		}else{
			$result['erro'] = -1;
			$result['msg'] = '删除失败';
		}
		return json($result);
	}
	/********************************* 计算 *********************************/
	/********************************* 登录 *********************************/
	/**
	*小程序授权登录，获取微信用户信息
	* code: wx.login()获取到的code
	* encryptedData：wx.getUserInfo获取到的encryptedData
	* iv:wx.getUserInfo获取到的iv
	*/
	public function wechatLogin(Request $request){
		$post=$request->param();
		if(!isset($post['code']) || empty($post['code'])){
			$result['erro'] = -1;
		        $result['msg'] = "未传入code";
			return json_encode($result);
		}
		if(!isset($post['encryptedData']) || empty($post['encryptedData'])){
			$result['erro'] = -1;
		        $result['msg'] = "未传入encryptedData";
			return json_encode($result);
		}
		if(!isset($post['iv']) || empty($post['iv'])){
			$result['erro'] = -1;
		        $result['msg'] = "未传入iv";
			return json_encode($result);
		}
		
	    $encryptedData  =$post['encryptedData'];
	    $iv  = $post['iv'];
	    $code=$post['code'];
	    $URL = "https://api.weixin.qq.com/sns/jscode2session?appid=".$this->Appid."&secret=".$this->Appsecret."&js_code=$code&grant_type=authorization_code";
	    $apiData=json_decode($this->httpGet($URL),true);
	//    $apiData=['session_key'=>'dsQb6qITD2CZyBilb22dag==','openid'=>'oXcSb66vSO0_aGbL0NXJ_cxXnt5g'];
	//    var_dump($apiData);
		    if(!isset($apiData['errcode'])){
			     $sessionKey =$apiData['session_key'];//$post['sessionKey'];//
			      $errCode =$this->decryptData($sessionKey,$this->Appid,$encryptedData, $iv, $data );
			   //   LogUtils::error('小程序解析：'.$data, __METHOD__);
			      if ($errCode == 0) {
			      	  //保存用户信息
			      	  $record=json_decode($data,true);
			      	  $res=$this->saveUseInfor($record);
			      	  return json_encode($res);
			      } else {
			      	  //LogUtils::error('解析数据错误：'.$errCode, __METHOD__);
			      	  $result['erro'] = -1;
				        $result['msg'] = "解析接口返回数据失败，请重试！";
				        return json_encode($result);
			      }
			}else{
		    	//	LogUtils::error('错误码：'.$apiData['errcode'].'，错误信息：'.$apiData['errmsg'], __METHOD__);
		    		$result['erro'] = -1;
			        $result['msg'] = $apiData['errmsg'];//'获取信息失败'
			        return json_encode($result);
		    }
	}
	
	  /**
	  *保存用户的信息
	  */	
	private function saveUseInfor($record){
		$data=array();
		//用户昵称
		$data['nickname']=$record['nickName'];
		//用户头像
		$data['headimg']=$record['avatarUrl'];
		//var_dump(strlen($data['headimg']));
		//是否已经保存信息
		$rec=Db::name('ghd_wechat_user')->field('uid')->where('openid',$record['openId'])->find();
		
		if(empty($rec)){
			//用户openid
			$data['openid']=$record['openId'];
			//时间
			$data['create_time']=date('Y-m-d H:i:s');
			$res=Db::name('wechat_user')->insertGetId($data);
			$uid=$res;
		}else{
			$res=Db::name('wechat_user')->where('uid',$rec['uid'])->update($data);
			$uid=$rec['uid'];
		}
		if($res===false){
			$result['erro'] = -1;
			$result['msg'] = "保存信息失败";
			return $result;
		}else{
			$result['erro'] = 0;
			$result['msg'] = "登录成功";
			$result['uid'] = $uid;
			return $result;
		}
	}
	
	/**
	*获取访问令牌
	*/
	public function getToken(Request $request){
		$post=$request->param();
		if(!isset($post['uid']) || empty($post['uid'])){
			$result['erro'] = -1;
			$result['msg'] = "未传登录用户id";
			return json_encode($result);
		}
		if(!isset($post['phone']) || empty($post['phone'])){
			$result['erro'] = -1;
			$result['msg'] = "未传登录用户账号";
			return json_encode($result);
		}
		$arr=array();
		$arr['phone']=$post['phone'];
		$arr['status']=1;
		$res=Db::name('accounthosting')->where($arr)->value('id');
		if($res != $post['uid']){
			$result['erro'] = -1;
			$result['msg'] = "账号异常";
			return json_encode($result);
		}
		$result['erro'] = 0;
		$result['msg'] = "登录成功";
		$result['token']=$this->authcode($post['uid'].'_'.time(),'ENCODE',$this->TokenKey,60*60*3);
		return json_encode($result);
	}
	/**
 	*检测令牌是否有效
 	*/
 	private function checkToken($token,$uid){
 		$res=$this->authcode($token,'DECODE',$this->TokenKey,60*60*3); 
 		//失效过期
 		if(empty($res)){
 			return false;
 		}else{
 			$data=explode('_',$res);
 			//不正确
 			if($data[0] == $uid){
 				return true;
 			}else{
 				return false;
 			}
 		}
 	}
	/********************************* 登录 *********************************/
	/********************************* 我的 *********************************/
	/**
	*基本信息
	*/
	public function getUserBaseInfo(Request $request){
		$post=$request->param();
		if(!isset($post['version_number']) || empty($post['version_number'])){
			$result['erro'] = -1;
			$result['msg'] = "未传入版本号";
			return json_encode($result);
		}
		switch($post['version_number']){
			case '1.0.0':
				return $this->getUserBaseInfo_1_0_0($post);
				break;
			default:
				return $this->getUserBaseInfo_1_0_0($post);
				break;
		}
	}
	private function getUserBaseInfo_1_0_0($post){
		if(!isset($post['uid']) || empty($post['uid'])){
			$result['erro'] = -1;
			$result['msg'] = "未传入登录人id";
			return json_encode($result);
		}
		if(!isset($post['token']) || empty($post['token'])){
			$result['erro'] = -1;
			$result['msg'] = "未传入token";
			return json_encode($result);
		}
		if($this->checkToken($post['token'],$post['uid']) === false){
			$result['erro'] = -1;
			$result['msg'] = "token异常";
			return json_encode($result);
		}
		$result['infor']=Db::name('accounthosting')->field('name,headimg,balance')->where('id',$post['uid'])->find();
		$result['erro'] = 0;
		$result['msg'] = "获取数据成功";
		return json_encode($result);
	}
	
}
?>