<?php

namespace app\command;

use support\think\Db;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use think\db\exception\BindParamException;
use Webman\Console\Util;

class Model extends Command
{
    protected static string $defaultName = 'model:all';
    protected static string $defaultDescription = '统一生成Model';

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $output->writeln("生成Model开始====>".getDateFull());
        try {
            $table = Db::query("SHOW TABLES");
        } catch (BindParamException $e) {

        }
        $connection = config("think-orm.default");
        $database = config("think-orm.connections.$connection.database");
        foreach ($table as $val) {
            $dir = explode("_",$val["Tables_in_{$database}"]);
            $dirPath = app_path("model").DIRECTORY_SEPARATOR.$dir[0];
            $namespace = str_replace('/', '\\', 'app/model/' . $dir[0]);
            $class = Util::nameToClass($val["Tables_in_{$database}"]);
            $file = $dirPath . DIRECTORY_SEPARATOR . "$class.php";
            if (file_exists($file)) { // 存在，跳过
                $output->writeln("已存在，跳过====>".getDateFull()."====>".$file);
            } else {
                $path = pathinfo($file, PATHINFO_DIRNAME);
                if (!is_dir($path)) {
                    mkdir($path, 0777, true);
                }
                $properties = '';
                $pk = 'id';
                foreach (Db::query("select COLUMN_NAME,DATA_TYPE,COLUMN_KEY,COLUMN_COMMENT from INFORMATION_SCHEMA.COLUMNS where table_name = '".$val["Tables_in_{$database}"]."' and table_schema = '$database' ORDER BY ordinal_position") as $item) {
                    if ($item['COLUMN_KEY'] === 'PRI') {
                        $pk = $item['COLUMN_NAME'];
                        $item["COLUMN_COMMENT"] .= "(主键)";
                    }
                    $type = $this->getType($item["DATA_TYPE"]);
                    $properties .= " * @property $type \${$item["COLUMN_NAME"]} {$item["COLUMN_COMMENT"]}\n";
                }
                $properties = rtrim($properties) ?: ' *';
                $table_val = $val["Tables_in_{$database}"];
                $model_content = <<<EOF
<?php

namespace $namespace;

use app\\extra\\basic\\Model;


/**
$properties
 */
class $class extends Model
{
    /**
     * The connection name for the model.
     *
     * @var string|null
     */
    protected \$connection = 'mysql';
    
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected string \$table = "$table_val";
    
    /**
     * The primary key associated with the table.
     *
     * @var string
     */
    protected string \$primaryKey = "$pk";
    
    /**
     * Indicates if the model should be timestamped.
     *
     * @var bool
     */
    public bool \$timestamps = false;


}

EOF;
                file_put_contents($file, $model_content);
                $output->writeln("生成成功====>".getDateFull()."====>".$file);
            }
        }
        return self::SUCCESS;
    }


    protected function getType(string $type): string
    {
        if (str_contains($type, 'int')) {
            return 'integer';
        }
        switch ($type) {
            case 'varchar':
            case 'string':
            case 'text':
            case 'date':
            case 'time':
            case 'guid':
            case 'datetimetz':
            case 'datetime':
            case 'decimal':
            case 'enum':
                return 'string';
            case 'boolean':
                return 'integer';
            case 'float':
                return 'float';
            default:
                return 'mixed';
        }
    }

}