<?php

namespace app\appstore\controller;

use app\common\controller\Frontend;
use think\Db;
class Index extends Frontend
{
    protected $noNeedLogin = ['*'];
	protected $noNeedRight = ['*'];
   
    public function index()
    
    {   
        $opencry = Db::name('config')->where(['name'=>'opencry'])->value('value');
        $icon1 = Db::name('config')->where(['name'=>'sourceicon'])->value('value');
        $udid = isset($_GET['udid'])?$_GET['udid']:'';
		if($udid == '') {$udid = 0;}//return json(['code'=>0,'msg'=>'请上传参数UDID']);
		$kcode = isset($_GET['code'])?$_GET['code']:'';
		$data = [];
		if($kcode == ''){
		    $chkis = Db::table('fa_udidlist')->where('udid',$udid)->order('id desc')->select();
			if($chkis) {
			    
				$kdata = $chkis[0];
				
                $mp=$kdata['mp'];
                $p12=$kdata['p12'];
                
                if($mp!=''){
                $path=time();
                $dir = './p12/'.$path;
                if(!is_dir($dir)) {
                    mkdir($dir, 0777, true);
                }
                
                $locale = 'zh_CN.UTF-8';
                setlocale(LC_ALL, $locale);
                putenv('LC_ALL='.$locale);
                
                // 生成P12文件
                $url1 = $dir.'/证书文件.p12';
                $file1 = fopen($url1,"a+");
                fwrite($file1, base64_decode($p12));
                fclose($file1);
            
            
                // 生成描述文件
                $url2 = $dir.'/描述文件.mobileprovision';
                $file2 = fopen($url2,"a+");
                fwrite($file2, base64_decode($mp));
                fclose($file2);
              
            
                $url3 = $dir.'/密码.txt';
                $file3 = fopen($url3,"a+");
                fwrite($file3, "密码：1");
                fclose($file3);
                
                
                $domain = $_SERVER['REQUEST_SCHEME'] . '://'.$_SERVER['SERVER_NAME'];
                // 打包zip文件
                $fileList = [$url1, $url2,$url3];
            
                $filename = $dir.'/证书_'. $udid.'.zip';
              
                $zip = new \ZipArchive();
                $zip->open($filename,\ZipArchive::CREATE);   //打开压缩包
                foreach($fileList as $file){
                    $zip->addFile($file, basename($file));   //向压缩包中添加文件
                }
                $zip->close();
                $cer=$domain.'/p12/'.$path.'/证书_'. $udid.'.zip';
                }
               
        
                if(time() <  $kdata['dqtime'] && $m!=''){
                    $name =  Db::table('fa_config')-> where('name','name')->value('value');
                    $wb=true;
                    $data[0]['name'] = $name.'VIP证书';
					$data[0]['version'] = "1.2";
					$data[0]['versionDate'] = date('Y-m-d',$kdata['dqtime']);
					$data[0]['versionDescription'] = "证书密码为1，请下载后解压导入";
					$data[0]['lock'] = strval(0) ;
					$data[0]['downloadURL'] = $cer;
					$data[0]['isLanZouCloud'] = strval(0) ;
					$data[0]['iconURL'] = 'https://'.$_SERVER['HTTP_HOST'].$icon1;
					$data[0]['tintColor'] = '';
					$data[0]['size'] = strval(1024*13) ;
				
                    
                }else{$wb=false;}
			}else{$wb=false;}
               
               
			$chkif = Db::table('fa_kami')->where('udid',$udid)->order('id desc')->select();
			if($chkif){
			    if(time()< $chkif[0]['endtime'] ){
			        $ifend = false;
			    }else{
			        $ifend =true;
			    }
				
				$config = Db::table('fa_config')->select();
				if(empty($config)) return json(['code'=>0,'msg'=>'暂无站点数据']);
				$list = Db::table('fa_appstore')->where('status','normal')->order('weigh desc')->select();
				if(empty($list)) return json(['code'=>0,'msg'=>'暂无app数据']);
			
				
			foreach ($list as $key=>$val)
				{
				    if($wb){$key=$key+1;}
				    
				    if(strstr($val['image'], 'http')) {$img=$val['image'];}else{$img='https://'.$_SERVER['HTTP_HOST'].$val['image'];}
				    
					$data[$key]['name'] = $val['name'];
					$data[$key]['version'] = $val['nickname'];
					$data[$key]['versionDate'] = date('Y-m-d',$val['updatetime']);
					$data[$key]['versionDescription'] = str_replace("\\n",'qq1006536666',$val['keywords']);
					$data[$key]['lock'] = $val['bt2b'];
					$data[$key]['downloadURL'] = $ifend?'':$val['bt1a'];
					$data[$key]['isLanZouCloud'] = $val['flag'];
					$data[$key]['iconURL'] = $img;
					$data[$key]['tintColor'] = $val['bt1b'];
					$data[$key]['size'] = $val['bt2a'];
				}
				foreach ($config as $key=>$val)
				{
				    
					if($val['name'] == 'name') $info['name'] = $val['value'];
					if($val['name'] == 'message') $info['message'] = $val['value'];
					if($val['name'] == 'identifier') $info['identifier'] = $val['value'];
					if($val['name'] == 'sourceURL') $info['sourceURL'] = $val['value'];
					if($val['name'] == 'sourceicon') $info['sourceicon'] = $val['value'];
					if($val['name'] == 'payURL') $info['payURL'] = $val['value'];
					if($val['name'] == 'unlockURL') $info['unlockURL'] = $val['value'];
				}
				$arr = [
					'name'=>$info['name'].'源',
					'message'=>$info['message'],
					'identifier'=>$info['identifier'],
					'sourceURL'=>$info['sourceURL'],
					'sourceicon'=>'https://'.$_SERVER['HTTP_HOST'].$info['sourceicon'],
					'payURL'=>$info['payURL'],
					'unlockURL'=>$info['unlockURL'],
					'apps'=>$data
					];
					
				if($opencry=='1'){//开启接口
                        $content = json_encode($arr,320);
                        $content = base64_encode($content);
                        $native['content'] = $content;
                        $res = $this->curl('https://api.nuosike.com/api.php',$native);
                        $return["appstore"] = $res;
                        echo json_encode($return);die;
                    }else{
                        unset($arr['UDID']);
                        unset($arr['Time']);
                        $json = json_encode($arr,320);
				        $jsonStr  = str_replace('qq1006536666', '\n', $json);
                        echo $jsonStr;die;
                    }
			
			}else{
				$config = Db::table('fa_config')->select();
				if(empty($config)) return json(['code'=>0,'msg'=>'暂无站点数据']);
				$list = Db::table('fa_appstore')->where('status','normal')->order('weigh desc')->select();
				if(empty($list)) return json(['code'=>0,'msg'=>'暂无app数据']);
				
				
				foreach ($list as $key=>$val)
				{
				    if($wb){$key=$key+1;}
				    if(strstr($val['image'], 'http')) {$img=$val['image'];}else{$img='https://'.$_SERVER['HTTP_HOST'].$val['image'];}
					$data[$key]['name'] = $val['name'];
					$data[$key]['version'] = $val['nickname'];
					$data[$key]['versionDate'] = date('Y-m-d',$val['updatetime']);
					$data[$key]['versionDescription'] = str_replace("\\n",'qq1006536666',$val['keywords']);
					$data[$key]['lock'] = $val['bt2b'];
					$data[$key]['downloadURL'] = $val['bt2b']?'':$val['bt1a'];
					$data[$key]['isLanZouCloud'] = $val['flag'];
					$data[$key]['iconURL'] = $img;
					$data[$key]['tintColor'] = $val['bt1b'];
					$data[$key]['size'] = $val['bt2a'];
				}
				foreach ($config as $key=>$val)
				{
					if($val['name'] == 'name') $info['name'] = $val['value'];
					if($val['name'] == 'message') $info['message'] = $val['value'];
					if($val['name'] == 'identifier') $info['identifier'] = $val['value'];
					if($val['name'] == 'sourceURL') $info['sourceURL'] = $val['value'];
					if($val['name'] == 'sourceicon') $info['sourceicon'] = $val['value'];
					if($val['name'] == 'payURL') $info['payURL'] = $val['value'];
					if($val['name'] == 'unlockURL') $info['unlockURL'] = $val['value'];
				}
				$arr = [
					'name'=>$info['name'].'源',
					'message'=>$info['message'],
					'identifier'=>$info['identifier'],
					'sourceURL'=>$info['sourceURL'],
					'sourceicon'=>'https://'.$_SERVER['HTTP_HOST'].$info['sourceicon'],
					'payURL'=>$info['payURL'],
					'unlockURL'=>$info['unlockURL'],
					'apps'=>$data
					];
			if($opencry=='1'){//开启接口
                        $content = json_encode($arr,320);
                        $content = base64_encode($content);
                        $native['content'] = $content;
                        $res = $this->curl('https://api.nuosike.com/api.php',$native);
                        $return["appstore"] = $res;
                        echo json_encode($return);die;
                    }else{
                        unset($arr['UDID']);
                        unset($arr['Time']);
                        $json = json_encode($arr,320);
				        $jsonStr  = str_replace('qq1006536666', '\n', $json);
                        echo $jsonStr;die;
                    }
			}
		}else{
			$chkis = Db::table('fa_kami')->where('kami',$kcode)->order('id desc')->select();
			if($chkis){
				$kdata = $chkis[0];
				if(intval($kdata['jh'])){
					return json(['code'=>0,'msg'=>'解锁码已使用']);
				}else{
					//---
					$kmtp = intval($kdata['kmyp']);
					if($kmtp == 1){ $sydt = time(); $endtm = $sydt+(86400*30); }
					if($kmtp == 2){ $sydt = time(); $endtm = $sydt+(86400*30*3); }
					if($kmtp == 3){ $sydt = time(); $endtm = $sydt+(86400*30*12); }
					Db::table('fa_kami')->where('id', $kdata['id'])->update(array('udid'=>$udid, 'usetime'=>$sydt, 'endtime'=>$endtm, 'jh'=>1));
					return json(['code'=>0,'msg'=>'ok，解锁成功']);
				}
			}else{
				return json(['code'=>0,'msg'=>'解锁码不存在']);
			}
		}
    }
    public function curl($url,$native){
		$postData = http_build_query($native);
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL,$url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // stop verifying certificate
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
        curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
        $data = curl_exec($curl);
        curl_close($curl);
        return $data;
    }
   

  public function do(){
    $string='eyJuYW1lIjoi5bey6KKr5rqQ5Li75ouJ6buRIiwibWVzc2FnZSI6IuS9oOW3suiiq+a6kOS4u+aLiem7ke+8gSIsImlkZW50aWZpZXIiOiLplb/mjInmraTlpITliKDpmaTova/ku7bmupAiLCJwYXlVUkwiOiIiLCJ1bmxvY2tVUkwiOiIiLCJVRElEIjoiNjY2NjYiLCJUaW1lIjoiNTU1NSIsImFwcHMiOlt7Im5hbWUiOiLkvaDlt7LooqvmupDkuLvmi4npu5HvvIEiLCJ2ZXJzaW9uIjoiMS4wIiwidmVyc2lvbkRhdGUiOiIyMDIxLTAxLTI0IiwidmVyc2lvbkRlc2NyaXB0aW9uIjoi5L2g5bey6KKr5rqQ5Li75ouJ6buR77yBIiwibG9jayI6IjEiLCJkb3dubG9hZFVSTCI6IiIsImlzTGFuWm91Q2xvdWQiOiIwIiwidGludENvbG9yIjoiIiwic2l6ZSI6IjEyMzk3MzE0MC40OCJ9XX0=';
    $operation='E';
    $key='U2FsdGVkX19pkTKctpmkYaO3dv7QAxsIQcaegYpTo24=';
    return $this->encrypt($string,$operation,$key);
  }
    
  function encrypt($string,$operation,$key='')
  {
    $key=md5($key);
    $key_length=strlen($key);
    $string=$operation=='D'?base64_decode($string):substr(md5($string.$key),0,8).$string;
    $string_length=strlen($string);
    $rndkey=$box=array();
    $result='';
    for($i=0;$i<=255;$i++)
    {
      $rndkey[$i]=ord($key[$i%$key_length]);
      $box[$i]=$i;
    }
    for($j=$i=0;$i<256;$i++)
    {
      $j=($j+$box[$i]+$rndkey[$i])%256;
      $tmp=$box[$i];
      $box[$i]=$box[$j];
      $box[$j]=$tmp;
    }
    for($a=$j=$i=0;$i<$string_length;$i++)
    {
      $a=($a+1)%256;
      $j=($j+$box[$a])%256;
      $tmp=$box[$a];
      $box[$a]=$box[$j];
      $box[$j]=$tmp;
      $result.=chr(ord($string[$i])^($box[($box[$a]+$box[$j])%256]));
    }
    if($operation=='D')
    {
      if(substr($result,0,8)==substr(md5(substr($result,8).$key),0,8))
      {
        return substr($result,8);
      }
      else
      {
        return'';
      }
    }
    else
    {
      return str_replace('=','',base64_encode($result));
    }
  }

}
