<?php
namespace app\admin\logic;
use app\admin\model\SystemLog;
use think\exception\ValidateException;
use app\BaseController;
use think\facade\Db;
class SystemForm extends  Base
{

    public $version="1.0.8";
    public $download_url='';
    public $log_content='';
    public $is_system_update=0;
    //每次更新都需要更换的文件
    private $qytpl='app.qytpl.js';
    private $repfile='app.33bb401c.js';

    public function __construct()
    {
        parent::__construct();
        $url='http://auth.whfjkj.com/index.php/index/index/update';
        $version=SystemLog::where(['status'=>1])->order('id DESC')->value('version');
        $json=httpRequest($url,"POST",[
            'url'=>request()->host(),
            'module'=>'sharedTeahouse',
            'version'=>!empty($version)?$version:'0'
        ]);
        $res=json_decode($json,1);
        if(isset($res['code'])){
            if($res['code']==0){
                $form=SystemLog::where(['version'=>$res['data']['version']])->order('id DESC')->find();
                if($form){
                    if($form['status']==0){
                        $this->download_url=$res['data']['download_url'];
                        $this->log_content=$res['data']['log'];
                        $this->is_system_update=1;
                        $this->version=$res['data']['version'];
                        $this->repfile=$res['data']['repfile_js'];
                    }else{
                         $this->is_system_update=0;
                    }
                }else{
                    (new SystemLog())->save([
                        'version'=>$res['data']['version']
                    ]);
                    $this->is_system_update=1;
                }
            }
        }
    }
     //列表
    public  function logList(){
        $list=SystemLog::where(['status'=>1])->page($this->page)->limit($this->limit)
        ->order('id DESC')
        ->select()->toArray();
        $count=SystemLog::where(['status'=>1])->count();
        return fetchJson([
            'is_update'=>$this->is_system_update,
            'log_content'=>$this->log_content,
            'list'=>$list,
            'count'=>$count
        ]);
    }
    public  function updata(){
        if($this->is_system_update==0){
            return fetchJson([],'暂无文件可更新',0);
        }
        if(!is_dir(app()->getRuntimePath().'system')){
             mkdir(app()->getRuntimePath().'system');
        }
        $fileZip=app()->getRuntimePath().'system/'.$this->version.'.zip';
        if(!is_file($fileZip)){
            if(!$this->download_url){
                return fetchJson([],'暂无文件可更新',0);
            }
            //远程下载文件
            $fileContnets=file_get_contents($this->download_url);
            file_put_contents($fileZip,$fileContnets);
        }
        //实例化ZipArchive类
        $zip = new \ZipArchive();
        //打开压缩文件，打开成功时返回true
        if ($zip->open($fileZip) === true) {
            $zip->extractTo(app()->getRootPath());
            //关闭
            $zip->close();
            $form=SystemLog::where([
                'version'=>$this->version,
            ])->find();
            if(!$form){
                $form=new SystemLog();
            }
            $form->save([
                'status'=>1,
                'version'=>$this->version,
                'log'=>$this->log_content
            ]);
            self::create_web();
            $this->updateSql();
            unlink($fileZip);
            return fetchJson([],'更新成功');
        } else {
             return fetchJson([],'ZipArchive 服务器不支持',0);
        }
    }
    //更新数据库
    private function updateSql(){
        $sql=app()->getRootPath().'sql/'.$this->version.'.sql';
        if(!is_file($sql))return false;
        $sql = Sql::getSqlFromFile($sql);  
        foreach ($sql as $value) {  
            @Db::execute($value);
        }
    }
    private function create_web(){
        $url_base=app()->getRootPath().'public/web';
        if(is_file($url_base.'/tpl.zip')){
            if(is_dir($url_base.'/static')){
                //清除
                 self::QyDeldir($url_base.'/static',1);
            }
            if(is_file($url_base.'/index.html')){
                unlink($url_base.'/index.html');
            }
            if(is_file($url_base.'/index.html')){
                unlink($url_base.'/report.html');
            }
            $zip = new \ZipArchive();
            //打开压缩文件，打开成功时返回true
            if ($zip->open($url_base.'/tpl.zip') === true) {
                $zip->extractTo($url_base);
                //关闭
                $zip->close();
            }
            $url=request()->domain().request()->baseFile();
            $baseUrl=$url.'?s=';
            $file=$url_base.'/static/js/'.$this->qytpl;
            $repfile=$url_base.'/static/js/'.$this->repfile;
            $url=$baseUrl;
            $txt='https://qianya.whfjkj.com/index.php?s=';
            $rep_txt=$url;  
            self::replace_data($file,$txt,$rep_txt,$repfile);
            if(is_file($url_base.'/tpl.zip')){
               unlink($url_base.'/tpl.zip');
            }
        }
    }
    private function replace_data($source_file,$source_text,$change_text,$repfile){
        if(!is_file($source_file))return 0;
        $getcontent=file_get_contents($source_file);
        $put=str_replace($source_text,$change_text,$getcontent);
        file_put_contents($repfile,$put);
    }
    //删除指定文件夹以及文件夹下的所有文件
    private function QyDeldir($dir=null,$present=false) {
          if(!is_dir($dir))return 0;
           //先删除目录下的文件：
           $dh=opendir($dir);
           while ($file=readdir($dh)) {
              if($file!="." && $file!="..") {
                 $fullpath=$dir."/".$file;
                 if(!is_dir($fullpath)) {
                    unlink($fullpath);
                 } else {
                    self::QyDeldir($fullpath,$present);
                 }
              }
           }
           closedir($dh);
           if($present){
                //删除当前文件夹：
               if(rmdir($dir)) {
                  return true;
               } else {
                  return false;
               }
           }
           return true;
    }
}
class Sql
{
    /**
     * 从sql文件获取纯sql语句
     * @param  string $sql_file sql文件路径
     * @param  bool $string 如果为真，则只返回一条sql语句，默认以数组形式返回
     * @param  array $replace 替换前缀，如：['my_' => 'me_']，表示将表前缀"my_"替换成"me_"
     *         这种前缀替换方法不一定准确，比如正常内容内有跟前缀相同的字符，也会被替换
     * @return mixed
     */
   static public function getSqlFromFile($sql_file = '', $string = false, $replace = [])
    {
        if (!file_exists($sql_file)) {
            return false;
        }

        // 读取sql文件内容
        $handle = self::read_file($sql_file);

        // 分割语句
        $handle = self::parseSql($handle, $string, $replace);

        return $handle;
    }

    /**
     * 分割sql语句
     * @param  string $content sql内容
     * @param  bool $string 如果为真，则只返回一条sql语句，默认以数组形式返回
     * @param  array $replace 替换前缀，如：['my_' => 'me_']，表示将表前缀my_替换成me_
     * @return array|string 除去注释之后的sql语句数组或一条语句
     */
    public static function parseSql($content = '', $string = false, $replace = [])
    {
        // 被替换的前缀
        $from = '';
        // 要替换的前缀
        $to = '';

        // 替换表前缀
        if (!empty($replace)) {
            $to   = current($replace);
            $from = current(array_flip($replace));
        }

        if ($content != '') {
            // 纯sql内容
            $pure_sql = [];

            // 多行注释标记
            $comment = false;

            // 按行分割，兼容多个平台
            $content = str_replace(["\r\n", "\r"], "\n", $content);
            $content = explode("\n", trim($content));

            // 循环处理每一行
            foreach ($content as $key => $line) {
                // 跳过空行
                if ($line == '') {
                    continue;
                }

                // 跳过以#或者--开头的单行注释
                if (preg_match("/^(#|--)/", $line)) {
                    continue;
                }

                // 跳过以/**/包裹起来的单行注释
                if (preg_match("/^\/\*(.*?)\*\//", $line)) {
                    continue;
                }

                // 多行注释开始
                if (substr($line, 0, 2) == '/*') {
                    $comment = true;
                    continue;
                }

                // 多行注释结束
                if (substr($line, -2) == '*/') {
                    $comment = false;
                    continue;
                }

                // 多行注释没有结束，继续跳过
                if ($comment) {
                    continue;
                }

                // 替换表前缀
                if ($from != '') {
                    $line = str_replace('`'.$from, '`'.$to, $line);
                }

                // sql语句
                array_push($pure_sql, $line);
            }

            // 只返回一条语句
            if ($string) {
                return implode($pure_sql, "");
            }

            // 以数组形式返回sql语句
            $pure_sql = implode($pure_sql, "\n");
            $pure_sql = explode(";\n", $pure_sql);
            return $pure_sql;
        } else {
            return $string == true ? '' : [];
        }
    }

    /**
     * 读取文件内容
     * @param $filename  文件名
     * @return string 文件内容
     */
    public static function read_file($filename) {
        $content = '';
        if(function_exists('file_get_contents')) {
            @$content = file_get_contents($filename);
        } else {
            if(@$fp = fopen($filename, 'r')) {
                @$content = fread($fp, filesize($filename));
                @fclose($fp);
            }
        }
        return $content;
    }
}