<?php
/**
* @author 龙虾 <15108148@qq.com>
* @version 2.0 2020-08-13
* @copyright 睿谷信息 <www.rgxx.com>
*/
namespace app\admin\controller;
use think\Controller;
use \rg\Backup;
use Request;
use think\Db;

class Data extends Base
{
	// 表首页
	public function index()
	{
		if(strtolower(config('database.type')) == 'mysql') {
			$Backup = new Backup();
			$data = $Backup->dataList();
			foreach ($data as $k => $v) {
				$data[$k]['data_length'] = format_bytes($v['data_length']);
			}
			$tablelist = json_encode($data);
			return $this->fetch('',compact('tablelist'));
		} else {
			$data = Db::query('SELECT * FROM sqlite_master WHERE TYPE="table" AND NAME<>"sqlite_sequence"');
			foreach ($data as $k => $v) {
				$data[$k]['count'] = Db::table($v['name'])->count();
			}
			$tablelist = json_encode($data);
			return $this->fetch('sqlite',compact('tablelist'));
		}
		
		// if(request()->isPost()){
		// 	$Backup = new Backup();
		// 	$data = $Backup->dataList();
		// 	foreach ($data as $k => $v) {
		// 		$data[$k]['data_length'] = format_bytes($v['data_length']);
		// 	}
		// 	return json(['code'=>0,'msg'=>lang('getdatatrue'),'data'=>$data,'count'=>count($data)]);
		// }
		// return $this->fetch();
	}
	// 备份列表	
	public function backuplist()
	{
		if(strtolower(config('database.type')) == 'mysql') {
			$Backup = new Backup();
			$data = $Backup->fileList();
			$backuplist = json_encode($data);
			return $this->fetch('',compact('backuplist'));
		} else {
			$filelist = read_allfile('data'.DS.'beifen',1);
			foreach ($filelist as $k => $v) {
				if($v['ext'] !== 'db') unset($filelist[$k]);
			}
			$backuplist = json_encode($filelist);
			return $this->fetch('sqlitebackuplist',compact('backuplist'));
		}
	}

	// 备份
	public function backup()
	{
		if(Request::isPost()) {
			if(strtolower(config('database.type') == 'mysql')) {
				$data = Request::post();
				$tablenames = Request::post('tablenames/a');
				try{
					if(empty($tablenames)){
						return json(['code' => 2,'msg' => lang('noselect')]);
					} else {
						$Backup = new Backup();
						$intresult = $Backup->setFile()->Backup_Init();
						if($intresult === false) {
							return json(['code' => 2,'msg' => lang('backupfalse')]);
						} else {
							foreach ($tablenames as $v) {
								$result = $Backup->backup($v,0);
								if($result === false) return json(['code' => 2,'msg' => lang('backupfalse')]);
							}
						}
						adminlog(2,'数据库备份');
						return json(['code' => 1,'msg' => lang('backuptrue')]);
					}
				}catch(\Exception $e){
					return json(['code' => 2,'msg' => $e->getMessage()]); // 异常捕获
				}
			} else {
				$dbname = substr(config('database.dsn'),strripos(config('database.dsn'),":")+1);
				$result = copy('./'.$dbname, './data/beifen/' . date('YmdHis') . '_rgcms.db');
				if ($result) {
					$this->success(lang('backuptrue'));
				} else {
					$this->error(lang('backupfalse'));
				}
			}
		}
	}

	// 修复
	public function repair()
	{
		if(Request::isPost()) {
			$data = Request::post();
			$tablenames = Request::post('tablenames/a');
			try{
				if(empty($tablenames)){
					return json(['code' => 2,'msg' => lang('noselect')]);
				} else {
					$Backup = new Backup();
					$result = $Backup->repair($tablenames);
					if($result){
						return json(['code' => 1,'msg' => lang('repairtrue')]);
					}else{
						return json(['code' => 2,'msg' => lang('repairfalse')]);
					}
				}
			}catch(\Exception $e){
				return json(['code' => 2,'msg' => $e->getMessage()]); // 异常捕获
			}
		}
	}

	// 优化
	public function optimize()
	{
		if(Request::isPost()) {
			$data = Request::post();
			$tablenames = Request::post('tablenames/a');
			try{
				if(empty($tablenames)){
					return json(['code' => 2,'msg' => lang('noselect')]);
				} else {
					$Backup = new Backup();
					$result = $Backup->optimize($tablenames);
					if($result){
						return json(['code' => 1,'msg' => lang('optimizetrue')]);
					}else{
						return json(['code' => 2,'msg' => lang('optimizefalse')]);
					}
				}
			}catch(\Exception $e){
				return json(['code' => 2,'msg' => $e->getMessage()]); // 异常捕获
			}
		}
	}

	// 重建索引
	public function reset()
	{
		if(Request::isPost()) {
			if(strtolower(config('database.type') == 'mysql')) {
				$data = Request::post();
				$tablenames = Request::post('tablenames/a');
				try{
					if(empty($tablenames)){
						return json(['code' => 2,'msg' => lang('noselect')]);
					} else {
						$Backup = new Backup();
						$data = $Backup->dataList();
						foreach ($data as $k => $v) {
							if($v['rows'] == 0 && in_array($v['name'], $tablenames)) {
								\think\Db::execute("TRUNCATE TABLE `".$v['name']."`");
							}
						}
						adminlog(2,'Mysql数据库重建索引');
						return json(['code' => 1,'msg' => lang('resettrue')]);
					}
				}catch(\Exception $e){
					return json(['code' => 2,'msg' => $e->getMessage()]); // 异常捕获
				}
			} else {
				try{
					$tablelist = Db::query('SELECT * FROM sqlite_master WHERE TYPE="table" AND NAME<>"sqlite_sequence"');
			        foreach ($tablelist as $k => $v) {
			            if(Db::table($v['name'])->count()==0) {
			                Db::query('DELETE FROM sqlite_sequence WHERE name="'.$v['name'].'"');
			            }
			        }
			        adminlog(2,'Sqlite数据库重建索引');
			        return json(['code' => 1,'msg' => lang('resettrue')]);
				}catch(\Exception $e){
					return json(['code' => 2,'msg' => $e->getMessage()]); // 异常捕获
				}
			}
		}
	}

	// 删除备份
	public function delbackup()
	{
		if(Request::isPost()) {
			$data = Request::post();
			if(strtolower(config('database.type')) == 'mysql') {
				$time = strtotime(Request::post('time'));
				try{
					$Backup = new Backup();
					$result = $Backup->delFile($time);
					if($result){
						return json(['code' => 1,'msg' => lang('deltrue')]);
					}
					return json(['code' => 2,'msg' => lang('delbackupfalse')]);
				}catch(\Exception $e){
					return json(['code' => 0,'msg' => $e->getMessage()]); // 异常捕获
				}
			} else {
				if(@unlink($data['path'])) {
					$this->success(lang('deltrue'));
				}
				$this->error(lang('delbackupfalse'));
			}
			
		}
	}

	// 还原
	public function importbackup()
	{
		if(Request::isPost()) {
			$data = Request::post();
			if(strtolower(config('database.type')) == 'mysql') {
				$time = strtotime(Request::post('time'));
				try {
					$Backup = new Backup();
		    		$start = 0;
		    		$file = $Backup->getFile('timeverif',$time);
		    		$result = $Backup->setFile($file)->import($start);
		    		if($result===false){
		    			return ['code' => 2,'msg' => lang('importfalse')];
		    		}else{
		    			return ['code' => 1,'msg' => lang('importtrue')];
		    		}
				} catch(\Exception $e) {
					return json(['code' => 2,'msg' => $e->getMessage()]); // 异常捕获
				}
			} else {
				$dbname = substr(config('database.dsn'),strripos(config('database.dsn'),":")+1);
				if(copy('./data/beifen/'.$data['title'],'./'.$dbname)) {
					$this->success(lang('importtrue'));
				}
				$this->error(lang('importfalse'));
			}
		}
	}

	// 下载备份
	public function downbackup()
    {
    	$time = strtotime(Request::param('time'));
    	$Backup = new Backup();
    	$Backup->downloadFile($time);
    }
}