<?php

namespace app\install\controller;

use think\App;
use think\Controller;
use think\Db;

class Index extends Controller
{


    public function __construct(App $app = null)
    {
        parent ::__construct($app);
        if (is_installed()) {
            $this -> error('网站已经安装', '/');
        }
    }


    public function index()
    {
        return $this -> fetch(":index");
    }


    public function step2()
    {

        $data = [];
        $data['phpversion'] = @phpversion();
        $data['os'] = PHP_OS;
        $tmp = function_exists('gd_info') ? gd_info() : [];
        $err = 0;
        if (empty($tmp['GD Version'])) {
            $gd = '<font color=red>[×]Off</font>';
            $err ++;
        } else {
            $gd = '<font color=green>[√]On</font> ' . $tmp['GD Version'];
        }
        if (class_exists('pdo')) {
            $data['pdo'] = '<i class="fa fa-check correct"></i> 已开启';
        } else {
            $data['pdo'] = '<i class="fa fa-remove error"></i> 未开启';
            $err ++;
        }
        if (extension_loaded('pdo_mysql')) {
            $data['pdo_mysql'] = '<i class="fa fa-check correct"></i> 已开启';
        } else {
            $data['pdo_mysql'] = '<i class="fa fa-remove error"></i> 未开启';
            $err ++;
        }
        if (extension_loaded('curl')) {
            $data['curl'] = '<i class="fa fa-check correct"></i> 已开启';
        } else {
            $data['curl'] = '<i class="fa fa-remove error"></i> 未开启';
            $err ++;
        }
        if (extension_loaded('gd')) {
            $data['gd'] = '<i class="fa fa-check correct"></i> 已开启';
        } else {
            $data['gd'] = '<i class="fa fa-remove error"></i> 未开启';
            if (function_exists('imagettftext')) {
                $data['gd'] .= '<br><i class="fa fa-remove error"></i> FreeType Support未开启';
            }
            $err ++;
        }
        if (extension_loaded('mbstring')) {
            $data['mbstring'] = '<i class="fa fa-check correct"></i> 已开启';
        } else {
            $data['mbstring'] = '<i class="fa fa-remove error"></i> 未开启';
            if (function_exists('imagettftext')) {
                $data['mbstring'] .= '<br><i class="fa fa-remove error"></i> FreeType Support未开启';
            }
            $err ++;
        }
        if (extension_loaded('fileinfo')) {
            $data['fileinfo'] = '<i class="fa fa-check correct"></i> 已开启';
        } else {
            $data['fileinfo'] = '<i class="fa fa-remove error"></i> 未开启';
            $err ++;
        }
        if (ini_get('file_uploads')) {
            $data['upload_size'] = '<i class="fa fa-check correct"></i> ' . ini_get('upload_max_filesize');
        } else {
            $data['upload_size'] = '<i class="fa fa-remove error"></i> 禁止上传';
        }
        if (function_exists('session_start')) {
            $data['session'] = '<i class="fa fa-check correct"></i> 支持';
        } else {
            $data['session'] = '<i class="fa fa-remove error"></i> 不支持';
            $err ++;
        }
        $folders = [
                realpath(OA_DATA . '/data') . DIRECTORY_SEPARATOR,
                realpath('./upload') . DIRECTORY_SEPARATOR,
        ];
        $newFolders = [];
//        foreach ($folders as $dir) {
//            $testDir = $dir;
//            sp_dir_create($testDir);
//            if (sp_testwrite($testDir)) {
//                $newFolders[$dir]['w'] = true;
//            } else {
//                $newFolders[$dir]['w'] = false;
//                $err ++;
//            }
//            if (is_readable($testDir)) {
//                $newFolders[$dir]['r'] = true;
//            } else {
//                $newFolders[$dir]['r'] = false;
//                $err ++;
//            }
//        }
        $data['folders'] = $newFolders;
        $this -> assign($data);
        return $this -> fetch(":step2");
    }


    public function step3()
    {
        return $this -> fetch(":step3");
    }


    public function step4()
    {
        session(null);
        if ($this -> request -> isPost()) {
            //创建数据库
            $dbConfig = [];
            $dbConfig['type'] = "mysql";
            $dbConfig['hostname'] = $this -> request -> param('dbhost');
            $dbConfig['username'] = $this -> request -> param('dbuser');
            $dbConfig['password'] = $this -> request -> param('dbpw');
            $dbConfig['hostport'] = $this -> request -> param('dbport');
            $dbConfig['charset'] = $this -> request -> param('dbcharset', 'utf8mb4');

            $db = Db ::connect($dbConfig);
            $dbName = $this -> request -> param('dbname');
            $sql = "CREATE DATABASE IF NOT EXISTS `{$dbName}` DEFAULT CHARACTER SET " . $dbConfig['charset'];
            $db -> execute($sql);
            $dbConfig['database'] = $dbName;
            $dbConfig['prefix'] = $this -> request -> param('dbprefix', '', 'trim');
            session('install.db_config', $dbConfig);
            $sql = split_sql(dirname(__DIR__) . '/data/oa.sql', $dbConfig['prefix'], $dbConfig['charset']);
            $apps = scan_dir(OA_ROOT . 'app/*', GLOB_ONLYDIR);
            foreach ($apps as $app) {
                $appDbSqlFile = OA_ROOT . "app/{$app}/data/{$app}.sql";
                if (file_exists($appDbSqlFile)) {
                    $sqlList = split_sql($appDbSqlFile, $dbConfig['prefix'], $dbConfig['charset']);
                    $sql = array_merge($sql, $sqlList);
                }
            }
            session('install.sql', $sql);
            $this -> assign('sql_count', count($sql));
            session('install.error', 0);
            //安装程序
            $url = config('api.xigu.domain') . config('api.xigu.install');
            $data = [
                    'sitename' => $this -> request -> param('sitename'),
                    'domain' => $this -> request -> param('domain'),
                    'real_domain' => get_domain() . '/',    //当前安装程序域名
                    'mobile' => $this -> request -> param('mobile'),
                    'ip' => $this -> request -> ip(),
            ];
            json_decode(curl($url, $data), true);
            session('site_name', $data['sitename']);
            return $this -> fetch(":step4");

        } else {
        }
    }

    public function step5()
    {
        if (session("install.step") == 4) {
            @touch(OA_DATA . 'install.lock');
            set_option('site_name', ['value' => session('site_name')]);
            return $this -> fetch(":step5");
        } else {
            $this -> error("非法安装！");
        }
    }


    public function install()
    {
        $dbConfig = session('install.db_config');
        $sql = session('install.sql');
        if (empty($dbConfig) || empty($sql)) {
            $this -> error("非法安装!");
        }
        $sqlIndex = $this -> request -> param('sql_index', 0, 'intval');
        $db = Db ::connect($dbConfig);
        if ($sqlIndex >= count($sql)) {
            $installError = session('install.error');
            $this -> success("安装完成!", '', ['done' => 1, 'error' => $installError]);
        }
        $sqlToExec = $sql[$sqlIndex] . ';';
        $result = sp_execute_sql($db, $sqlToExec);
        if (!empty($result['error'])) {
            $installError = session('install.error');
            $installError = empty($installError) ? 0 : $installError;
            session('install.error', $installError + 1);
            $this -> error($result['message'], '', [
                    'sql' => $sqlToExec,
                    'exception' => $result['exception']
            ]);
        } else {
            $this -> success($result['message'], '', [
                    'sql' => $sqlToExec
            ]);
        }
    }


    public function setDbConfig()
    {
        $dbConfig = session('install.db_config');
        $result = sp_create_db_config($dbConfig);
        if ($result) {
            session("install.step", 4);
            $this -> success("数据配置文件写入成功!");
        } else {
            $this -> error("数据配置文件写入失败!");
        }
    }


    public function testDbPwd()
    {
        if ($this -> request -> isPost()) {
            $dbConfig = $this -> request -> param();
            $dbConfig['type'] = "mysql";
            $supportInnoDb = false;
            try {
//                Db::connect($dbConfig)->query("SELECT VERSION();");
                $engines = Db ::connect($dbConfig) -> query("SHOW ENGINES;");
                foreach ($engines as $engine) {
                    if ($engine['Engine'] == 'InnoDB' && $engine['Support'] != 'NO') {
                        $supportInnoDb = true;
                        break;
                    }
                }
            } catch (\Exception $e) {
                $this -> error('数据库账号或密码不正确！' . $e -> getMessage());
            }
            if ($supportInnoDb) {
                $this -> success('验证成功！');
            } else {
                $this -> error('数据库账号密码验证通过，但不支持InnoDb!');
            }
        } else {
            $this -> error('非法请求方式！');
        }

    }

}
