<?php
namespace app\install\controller;
use \think\Controller;
use PDO;
use PDOStatement;
use think\Db;

class Index extends Controller {

	protected $status;

	public function initialize() {
		$this->status = array(
			'index'    => 'info',
			'check'    => 'info',
			'config'   => 'info',
			'sql'      => 'info',
			'complete' => 'info',
		);
		// config('tpl_replace_string',['__NAME__'=>'abce']);
		$this->replace('__NAME__','abcde');
		if (request()->action() != 'complete' && is_file(APP_PATH . '/install.lock')) {
			return $this->redirect('/index/index');
		}
		View::config('view_path',APP_PATH.Request::module().'/view/');
		$this->assign('stlUrl',Request::domain().'/index.php');
        if(!$data['init'] && !session('sx_admin')){
            return $this->redirect('crm/index/login');
        }
        //判断如果配置完成生成过Suxuan.php就直接重定向
        if(file_exists(APP_PATH.'../runtime'.DS.'Suxuan.php'))
        {
            $this->redirect('crm/index/login');
            exit();
        }
        //判断是否在有效期        
        $lib = new \app\index\lib\Lib();
        $res = $lib->check_auth_key();
        if ($res == 202) {
            unlink("./../runtime/Suxuan.php");
            $this->error("产品已过期",'/install/index');
        }else if ($res == 203) {
            unlink("./../runtime/Suxuan.php");
            $this->error("产品验证码失败",'/install/index');
        }
	}

	public function index() {
        //判断如果配置完成生成过Suxuan.php就直接重定向
        if(file_exists(APP_PATH.'../runtime'.DS.'Suxuan.php'))
        {
            $this->redirect('crm/index/login');
            exit();
        }	
		//var_dump(config());
		$this->status['index'] = 'success';
		$this->assign('status', $this->status);
		return $this->fetch();
	}

	public function check() {
        //判断如果配置完成生成过Suxuan.php就直接重定向
        if(file_exists(APP_PATH.'../runtime'.DS.'Suxuan.php'))
        {
            $this->redirect('crm/index/login');
            exit();
        }
		
		session('error', false);
		$next = 1;
		//环境检测
		$env = check_env();
		foreach ($env as $key => $value) {
			if ($value['4']=='error') {
				$next = 0;
			}
		}
		//目录文件读写检测
		if (IS_WRITE) {
			$dirfile = check_dirfile();
			$this->assign('dirfile', $dirfile);
			foreach ($dirfile as $key => $value) {
				if ($value['2']=='error') {
					$next = 0;
				}
			}
		}
		//函数检测
		$func = check_func();
		session('step', 1);
		foreach ($func as $key => $value) {
			if ($value['2']=='error') {
				$next = 0;
			}
		}
		$this->assign('next', $next);
		$this->assign('env', $env);
		$this->assign('func', $func);
		$this->status['index'] = 'primary';
		$this->status['check'] = 'success';
		$this->assign('status', $this->status);
		return view();
	}

	public function config($db = null, $admin = null) {
		if (request()->IsPost()) {
	        $return = ['code'=>200,'msg'=>'','data'=>''];
	        $post = input('post.');
	        //var_dump($post);
	        if(empty($post['ext'])||empty($post['ext']['app_secret']) || empty($post['ext']['mc_url'])){
	            $return['code'] = 201;
	            $return['msg'] = '通讯密钥和MC地址不可以为空。';
	            return json($return);die;
	        }
	        if(empty($post['database'])||empty($post['database']['hostname']) || empty($post['database']['username'])){
	            $return['code'] = 202;
	            $return['msg'] = '主数据库配置不可为空。';
	            return json($return);die;
	        }
	        if(empty($post['db_logs'])||empty($post['db_logs']['hostname']) || empty($post['db_logs']['username'])){
	            $return['code'] = 203;
	            $return['msg'] = '日志数据库配置不可为空。';
	            return json($return);die;
	        }

	        if(empty($post['product_id'])){
	            $return['code'] = 204;
	            $return['msg'] = '产品注册码不可为空。';
	            return json($return);die;
	        }
	        /************* 主 db config *************/
	        $initConfig = $this->initConfig();
	        $database = $post['database'];
	        unset($post['database'],$initConfig['database']);//不在config内的key都要删除
	        $res = $this->getDbList(['hostname'=>$database['hostname'],'username'=>$database['username'],'password'=>$database['password'],'hostport'=>$database['hostport']]);
	        if(!$res){
	            $return['code'] = 301;
	            $return['msg'] = '主数据库无法连接，请检查数据库配置。';
	            return json($return);die;
	        }
	        if(!in_array($database['database'],$res)){
	            $return['code'] = 302;
	            $return['msg'] = '主数据库没有：'.$database['database'].'数据库，请创建并给予相应用户权限。';
	            return json($return);die;
	        }
	        if(!empty(trim($database['hostname2']))){
	            $host2 = explode(',', $database['hostname2']);
	            foreach ($host2 as $k => $v) {
	                $res = $this->getDbList(['hostname'=>$v,'username'=>$database['username'],'password'=>$database['password'],'hostport'=>$database['hostport']]);
	                if(!$res){
	                    $return['code'] = 303;
	                    $return['msg'] = '主数据库从库：'.$v.',无法连接，请检查数据库配置。';
	                    return json($return);die;
	                }
	            }
	            unset($host2);
	        }

	        /************* 日志 db config *************/
	        $dbLogs = $post['db_logs'];
	        $res = $this->getDbList(['hostname'=>$dbLogs['hostname'],'username'=>$dbLogs['username'],'password'=>$dbLogs['password'],'hostport'=>$dbLogs['hostport']]);
	        if(!$res){
	            $return['code'] = 311;
	            $return['msg'] = '日志数据库配置有问题。';
	            return json($return);die;
	        }
	        if(!in_array($dbLogs['database'],$res)){
	            $return['code'] = 312;
	            $return['msg'] = '日志库没有：'.$dbLogs['database'].'数据库，请创建并给予相应用户权限。';
	            return json($return);die;
	        }
	        if(!empty(trim($dbLogs['hostname2']))){
	            $host2 = explode(',', $dbLogs['hostname2']);
	            foreach ($host2 as $k => $v) {
	                $res = $this->getDbList(['hostname'=>$v,'username'=>$dbLogs['username'],'password'=>$dbLogs['password'],'hostport'=>$dbLogs['hostport']]);
	                if(!$res){
	                    $return['code'] = 313;
	                    $return['msg'] = '日志数据库从库：'.$v.',无法连接，请检查数据库配置。';
	                    return json($return);die;
	                }
	            }
	            unset($host2);
	        }
	        $post['db_logs'] = array_merge($initConfig['db_logs'],$dbLogs);
	        unset($dbLogs);
	        /*************** REDIS测试配置  **********************/
	        if($post['redis']['host']){
	            $redis = $post['redis'];
	            $redis['port'] = $redis['port']?$redis['port']:6379;
	            $configTmp = [
	                // 驱动方式
	                'type'   => 'Redis',
	                // 缓存保存目录
	                'host'   => $redis['host'],
	                // 缓存前缀
	                'port'=>$redis['port'],
	                'select'=>$redis['select'],
	                // 缓存有效期 0表示永久缓存--测试，60秒后过期
	                'expire' => 60,
	                'timeout'=>5,
	            ];
	            try{
	                cache('test_install_redis','1',$configTmp);
	            }catch(\Exception $e){
	                $return['code'] = 401;
	                $return['msg'] = 'Redis队列连接失败，请检查参数。';
	                return json($return);die;
	            }
	            
	            //$res = cache('?test_install_redis','',$configTmp);
	            $post['redis'] = array_merge($initConfig['redis'],$redis);
	            unset($redis);
	        }else{
	            unset($post['redis']);
	        }
	        if($post['session']['host']){
	            $session = $post['session'];
	            $session['port'] = $session['port']?$session['port']:6379;
	            $session['type'] = 'Redis';
	            $configTmp = [
	                // 驱动方式
	                'type'   => 'Redis',
	                // 缓存保存目录
	                'host'   => $session['host'],
	                // 缓存前缀
	                'port'=>$session['port'],
	                'select'=>$session['select'],
	                // 缓存有效期 0表示永久缓存--测试，60秒后过期
	                'expire' => 60,
	                'timeout'=>5,
	            ];
	            try{
	                cache('test_install_session','1',$configTmp);
	            }catch(\Exception $e){
	                $return['code'] = 402;
	                $return['msg'] = 'Session服务连接失败，请检查参数。';
	                return json($return);die;
	            }
	            $post['session'] = array_merge($initConfig['session'],$session);
	            unset($session);
	        }else{
	            unset($post['session']);
	        }
	        if($post['cache']['host']){
	            $cache = $post['cache'];
	            $cache['port'] = $cache['port']?$cache['port']:6379;
	            $cache['type']='Redis';
	            $configTmp = [
	                // 驱动方式
	                'type'   => 'Redis',
	                // 缓存保存目录
	                'host'   => $cache['host'],
	                // 缓存前缀
	                'port'=>$cache['port'],
	                'select'=>$cache['select'],
	                // 缓存有效期 0表示永久缓存--测试，60秒后过期
	                'expire' => 60,
	                'timeout'=>5,
	            ];
	            try{
	                cache('test_install_cache','1',$configTmp);
	            }catch(\Exception $e){
	                $return['code'] = 402;
	                $return['msg'] = 'Cache服务连接失败，请检查参数。';
	                return json($return);die;
	            }
	            $post['cache'] = array_merge($initConfig['cache'],$cache);
	            unset($cache);
	        }else{
	            unset($post['cache']);
	        }

	        /***************** 产品注册 ********************/
	        $lib = new \app\index\lib\Lib();
	        $auth = $lib->getProductAuthFile();
	        if(!$auth){
	            $error = $lib->getError();
	            $return['msg'] = '获取授权信息出错，错误信息：('.$error['errid'].')'.$error['error'];
	            $return['code'] = 502;
	            return json($return);die;
	        }
	        unset($post['product_id']);
	        $authInfo = $lib->get_auth_key();
	        //var_dump($authInfo);
	        $return['msg'] = '<br/>授权到期时间：'.$authInfo['auth'][0];
	        if (time()>strtotime($authInfo['auth'][0]." 23:59:59")) {
	        	unlink(RUNTIME_PATH."Suxuan.php");
	        	$return['msg'] = '授权时间已到期：'.$authInfo['auth'][0];
	            $return['code'] = 503;
	            return json($return);die;
	        }
	        unset($authInfo);
	        /*************************************/

	        /*********** 保存database 配置 ***************/
	        $database = $this->mergeDbconfig($database);
	        $dbContent = $this->arrayToString($database);
	        file_put_contents(APP_PATH.DS.'database.php', $dbContent);
	        /*************** 保存 EXT文件**********************/
	        $initConfig['ext']['app_config']['sx_mc'] = array_merge($initConfig['ext']['app_config']['sx_mc'],['addr'=>$post['ext']['mc_url']]);
	        $initConfig['ext']['app_secret'] = $post['ext']['app_secret']?$post['ext']['app_secret']:$initConfig['ext']['app_secret'];
	        $ext = $initConfig['ext'];
	        $extContent = $this->arrayToString($ext);
	        file_put_contents(APP_PATH.DS.'extra'.DS.'ext.php', $extContent);
	        if($initConfig['ext'] != $post['ext']['app_secret']){
	            $tmp = [
	                'app_secret'=>$post['ext']['app_secret'],
	            ];
	            $res = db('api_app',$database)->where('1=1')->update($tmp);
	            if($res === false){
	                $return['msg'] = '更新数据库通迅密钥出错，请检查数据库配置后重试。';
	                $return['code'] = 601;
	            }
	        }
	        unset($post['ext'],$initConfig['ext']);
	        if ($initConfig['type']) {unset($initConfig['type']);};
	        if ($initConfig['view_path']) {unset($initConfig['view_path']);};
	        if ($initConfig['view_depr']) {unset($initConfig['view_depr']);};
	        if ($initConfig['tpl_begin']) {unset($initConfig['tpl_begin']);};
	        if ($initConfig['tpl_end']) {unset($initConfig['tpl_end']);};
	        if ($initConfig['taglib_begin']) {unset($initConfig['taglib_begin']);};
	        if ($initConfig['taglib_end']) {unset($initConfig['taglib_end']);};
	        //儿童性别配置拆分组合
	        $baby_sex = explode(",",trim($post['baby_sex'],","));
	        if(is_array($baby_sex)){
	        	foreach ($baby_sex as $key => $value) {
	        		$baby_sex[$key] = array('sex' => $value);
	        	}
	        }
	        $post['baby_sex'] = $baby_sex;
	        //消费类型配置拆分组合
	        if (is_string($post['exclude_consultation_type'])) {
	        	$post['exclude_consultation_type'] = explode(",",trim($post['exclude_consultation_type'],","));
	        }
	        $config = array_merge($initConfig,$post);	        
	        $configContent = $this->arrayToString($config);
	        file_put_contents(APP_PATH.DS.'config.php', $configContent);
	        return json($return);die;
			// //检测管理员信息
			// if (!is_array($admin) || empty($admin[0]) || empty($admin[1]) || empty($admin[3])) {
			// 	return $this->error('请填写完整管理员信息');
			// } else if ($admin[1] != $admin[2]) {
			// 	return $this->error('确认密码和密码不一致');
			// } else {
			// 	$info = array();
			// 	list($info['username'], $info['password'], $info['repassword'], $info['email'])
			// 	= $admin;
			// 	//缓存管理员信息
			// 	session('admin_info', $info);
			// }

			// //检测数据库配置
			// if (!is_array($db) || empty($db[0]) || empty($db[1]) || empty($db[2]) || empty($db[3])) {
			// 	return $this->error('请填写完整的数据库配置');
			// } else {
			// 	$DB = array();
			// 	list($DB['type'], $DB['hostname'], $DB['database'], $DB['username'], $DB['password'],
			// 		$DB['hostport'], $DB['prefix']) = $db;
			// 	//缓存数据库配置
			// 	session('db_config', $DB);

			// 	//创建数据库
			// 	$dbname = $DB['database'];
			// 	unset($DB['database']);
			// 	$db  = \think\Db::connect($DB);
			// 	$sql = "CREATE DATABASE IF NOT EXISTS `{$dbname}` DEFAULT CHARACTER SET utf8";
			// 	if (!$db->execute($sql)) {
			// 		return $this->error('创建数据库失败');
			// 	} else {
			// 		return $this->redirect('install/index/sql');
			//	}
			// }
		} else {
			$this->status['index']  = 'primary';
			$this->status['check']  = 'primary';
			$this->status['config'] = 'success';
			$this->assign('status', $this->status);

			$this->checkWriteable();
	        config('app_debug',true);
	        $data = $this->initConfig();
	        if(!$data['init'] && !session('sx_admin')){
	            return $this->redirect('crm/index/login');
	        }
	        $data['ext']['app_secret'] = config('ext.app_secret');
	        $mcUrl = config('ext.app_config')['sx_mc']['addr'];
	        $data['ext']['mc_url'] = $mcUrl;
	        $database = $data['database'];
	        // if($database['deploy'] == 1 && $database['rw_separate'] === true){
	        $databaseHost = explode(',', $database['hostname']);
	        if(count($databaseHost) > 1){
	            $database['hostname'] = $databaseHost[0];
	            unset($databaseHost[0]);
	            $database['hostname2'] = implode(',', $databaseHost);
	        }
	        //}
	        if($data['init'] && $database['hostname'] && $database['username']){
	            $dbList = $this->getDbList(['hostname'=>$database['hostname'],'username'=>$database['username'],'password'=>$database['password'],'hostport'=>$database['hostport']]);
	            $this->assign('db_list',$dbList);
	            // if($data['init'] == 1){
	            //     //初始安装
	            //     $data['account'] = [
	            //         'username'=>'root',
	            //         'password'=>get_rand_string(8,1),
	            //     ];
	            // }
	        }
	        $data['database'] = $database;

	        $dblogs = $data['db_logs'];
	        $databaseHost = explode(',', $dblogs['hostname']);
	        if(count($databaseHost) > 1){
	            $dblogs['hostname'] = $databaseHost[0];
	            unset($databaseHost[0]);
	            $dblogs['hostname2'] = implode(',', $databaseHost);
	        }

	        if($data['init'] && $dblogs['hostname'] && $dblogs['username']){
	            $dbLogsList = $this->getDbList(['hostname'=>$dblogs['hostname'],'username'=>$dblogs['username'],'password'=>$dblogs['password'],'hostport'=>$dblogs['hostport']]);
	            $this->assign('db_logs_list',$dbLogsList);
	        }
	        $data['db_logs'] = $dblogs;
	        $data['product_id'] = getProductId();
	        //取出儿童性别配置拼接成字符串
	        if (is_array($data['baby_sex'])) {
		        foreach ($data['baby_sex'] as $key => $value) {
		        	$baby_sex .= $value['sex'].",";
		        }	        	
	        }
	        $data['baby_sex'] = trim($baby_sex,",");
	        //取出消费类型配置拼接成字符串
	        if (is_array($data['exclude_consultation_type'])) {
		        foreach ($data['exclude_consultation_type'] as $key => $value) {
		        	$exclude_consultation_type .= $value.",";
		        }	        	
	        }
	        $data['exclude_consultation_type'] = trim($exclude_consultation_type,",");
//print_r($data['baby_sex']);
	        
	        $this->assign('data',$data);

			return $this->fetch();
		}
	}
	public function testMc($config){
		#TODO。。。。。
		if(!$config['mc_url'] || !$config['app_secret']){
			return false;
		}
		config('ext.app_secret',$config['app_secret']);
		config('ext.app_config',['sx_mc'=>['addr'=>$config['mc_url']]]);
		$res = sx_call('5a0a9ddc8f9d9',['']);

	}
	public function sql() {
        set_time_limit(0);
		session('error', false);
		$this->status['index']  = 'success';
		$this->status['check']  = 'success';
		$this->status['config'] = 'success';
		$this->status['sql']    = 'primary';
		$this->assign('status', $this->status);
		echo $this->fetch();
		if (session('update')) {

		} else {
			//连接数据库
			$dbconfig = session('db_config');
			$db       = \think\Db::connect($dbconfig);
			//创建数据表
			create_tables($db, $dbconfig['prefix']);
			//注册创始人帐号
			$admin = session('admin_info');
			register_administrator($db, $dbconfig['prefix'], $admin);

			//创建配置文件
			$conf = write_config($dbconfig);
			session('config_file', $conf);
		}

		if (session('error')) {
			show_msg('失败');
		} else {
			echo '<script type="text/javascript">location.href = "'.url('install/index/complete').'";</script>';
		}
	}

	public function complete() {
		$this->status['index']    = 'success';
		$this->status['check']    = 'success';
		$this->status['config']   = 'success';
		$this->status['sql']      = 'success';
		$this->status['complete'] = 'primary';
        $data=[];
        $app=[];
        $result=getAppAndWindvaneByApi();
        if($result != false){
            if(isset($result['status']) && isset($result['data'])){
                if($result['status']==1){
                    $data=isset($result['data'])?$result['data']:[];
                    $app=isset($result['app'])?$result['app']:[];
                }
            }
        }
        $this->assign('app_by_api',$app);
        $this->assign('data_by_api',$data);
		$this->assign('status', $this->status);
		$this->assign('status', $this->status);
		return $this->fetch();
	}











    public function saveProduct(){
        $return = ['code'=>200,'msg'=>'','data'=>''];
        $productId = input('product_id');
        $currentProductId = getProductId();
        if($productId != $currentProductId){
            $reg = ['product_id'=>$productId];
            $productIdContent = $this->arrayToString($reg);
            $fileName = ROOT_PATH.DS.'runtime'.DS.'Suxuan.php';
            $res = file_put_contents($fileName, $productIdContent);
            if(!$res){
                $return['msg'] = '更新授权文件出错，请确保runtime目录可写';
                $return['code'] = 501;
                return json($return);die;
            }else{
                return json($return);die;
            }
        }
        return json($return);die;
    }
    public function checkDb(){
        $hostname = input('hostname');
        $username = input('username');
        $password = input('password');
        $port = input('hostport');
        $res = $this->getDbList(['hostname'=>$hostname,'username'=>$username,'password'=>$password,'hostport'=>$port]);
        if($res === false){
            return json(['code'=>500,'msg'=>'数据库连接失败，请检查配置或权限']);
        }
        if(is_array($res) && empty($res)){
            return json(['code'=>501,'msg'=>'未找到数据库']);
        }
        return json(['code'=>200,'data'=>$res]);
    }

    function check_dirfile(){
        $items = array(
            array('dir',  '可写', 'success', '/../runtime'),
            array('file', '可写', 'success', '/../Application/config.php'),
        );
        foreach ($items as &$val) {
            if('dir' == $val[0]){
                if(!is_writable(INSTALL_APP_PATH . $val[3])) {
                    if(is_dir($items[1])) {
                        $val[1] = '可读';
                        $val[2] = 'error';
                        session('error', true);
                    } else {
                        $val[1] = '不存在';
                        $val[2] = 'error';
                        session('error', true);
                    }
                }
            } else {
                if(file_exists(INSTALL_APP_PATH . $val[3])) {
                    if(!is_writable(INSTALL_APP_PATH . $val[3])) {
                        $val[1] = '不可写';
                        $val[2] = 'error';
                        session('error', true);
                    }
                } else {
                    if(!is_writable(dirname(INSTALL_APP_PATH . $val[3]))) {
                        $val[1] = '不存在';
                        $val[2] = 'error';
                        session('error', true);
                    }
                }
            }
        }
        return $items;
    }
	private function checkWriteable(){
        $fileList = [
            ROOT_PATH . 'runtime',
            APP_PATH . 'extra',
            APP_PATH ,
            ROOT_PATH . 'public',
        ];
        $unwrite = '';
        foreach ($fileList as $key => $value) {
            if(!is_writeable($value)){
                $unwrite .= $value . "<br/>\r\n";
            }
        }
        if($unwrite){
            echo "以下文件不可写，请确保文件可写。<br/>\r\n";
            echo $unwrite;
            exit();
        }
    }

    private function initConfig(){
        $config = config();
        if(!file_exists(APP_PATH.DS.'config.php') && file_exists(APP_PATH.DS.'config.php.example')){
            $example = include(APP_PATH.DS.'config.php.example');
            $config = array_merge($config,$example);
        }
        if(!file_exists(APP_PATH.DS.'database.php') && file_exists(APP_PATH.DS.'database.php.example')){
            $example = include(APP_PATH.DS.'database.php.example');
            $config['database'] = array_merge($config['database'],$example);
            
        }
        if(!file_exists(APP_PATH.DS.'extra'.DS.'ext.php') && file_exists(APP_PATH.DS.'extra'.DS.'ext.php.example')){
            $example = include(APP_PATH.DS.'extra'.DS.'ext.php.example');
            if (!is_array($config['ext'])){$config['ext']=array();}
            $config['ext'] = array_merge($config['ext'],$example);
        }
        if(!file_exists(ROOT_PATH.DS.'runtime'.DS.'Suxuan.php')){
            $config['init'] = 1;
        }
        return $config;
    }
    private function getDbList($params){
        $config = $this->mergeDbconfig($params);
        //配置时，超时时间设置短点。
        $config['params'] = [PDO::ATTR_TIMEOUT => 3];
        $config['database'] = null;
        $db = Db::connect($config);
        $sql = "show databases;";
        try{
            $res = $db->master()->query($sql);
        }catch(\Exception $e){
            return false;
        }
        $databases= [];
        foreach ($res as $key => $value) {
            if($value['Database']){
                $databases[] = $value['Database'];
            }
        }
        return $databases;
    }
    /**
     * 将设置的config与默认配置进行合并
     * 
     * @param  [array] $config [设置的config]
     * @return [array]         [返回最终的数据库全的配置参数]
     */
    private function mergeDbconfig($config){
        if(file_exists(APP_PATH.DS.'database.php.example')){
            $default = include(APP_PATH.DS.'database.php.example');
        }else{
            $default = config()['database'];
        }
        
        if(trim($config['hostname2'])){
            $config['hostname'] = $config['hostname'].','.$config['hostname2'];
            unset($config['hostname2']);
            $default['deploy'] = 1;
        }
        unset($config['hostname2']);
        $default['rw_separate'] = true;
        $config = array_merge($default, $config);
        return $config;
    }
    private function arrayToString($arr,$in=0,$sp="\t"){
        if(!is_array($arr)){
            return $arr;
        }
        if(empty($arr)){
            return '';
        }
        $res = $in?'':'<?php '."\r\n"."return [\r\n";
        foreach ($arr as $key => $value) {
            if(is_array($value)){

                $res .= $sp."'{$key}'=>[\r\n".$this->arrayToString($value,1,$sp."\t").$sp.'],'."\r\n";
            }else{
                if(!is_numeric($key)){
                    $key = "'".$key."'";
                }
                if(is_string($value)){
                    $value = str_replace('\\', '\\\\', $value);
                    $res .= $sp."{$key}=>'{$value}',\r\n";
                }elseif (is_int($value)) {
                    $res .= $sp."{$key}=>{$value},\r\n";
                }elseif (is_bool($value)) {
                    if($value === true){
                        $res .= $sp."{$key}=>true,\r\n";
                    }else{
                        $res .= $sp."{$key}=>false,\r\n";
                    }
                }else{
                    $res .= $sp."{$key}=>'{$value}',\r\n";
                }
            }
        }
        $res .= $in?"":'];';
        return $res;
    }


}