<?php
declare (strict_types = 1);

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Db;
use think\facade\Env;

class makeModel extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('makemodel')
            ->setDescription('the makemodel command');
    }
	static $schema = 'cxinv_v2_pre_release';
	static $prefix = 'Wsm';
	static $epp = 'cxinv';
    protected function execute(Input $input, Output $output)
    {
        $str = 'mysql_cxinv';
        self::$schema = Env("{$str}_database");
        self::$prefix =  Env("{$str}_prefix");
        self::$epp = "cxinv";
         //获取表名
        $tables = Db::query("SELECT TABLE_NAME  as 'name'
        from information_schema.tables
        WHERE TABLE_SCHEMA = :dataBase and TABLE_TYPE='BASE TABLE'", ['dataBase' => self::$schema]);
        foreach ($tables as $key => $value) {
            foreach ($value as $item) {
                //获取字段名称和备注
                $COLUMNS = Db::query('select COLUMN_NAME,DATA_TYPE,COLUMN_COMMENT
            from information_schema.COLUMNS
            where table_name = :item
            and table_schema = :dataBase', ['item' => $item, 'dataBase' => self::$schema]);

				$dir = app_path().self::$epp."/model/". self::snakeToCamel($item) . '.php';
				if(file_exists($dir)) continue;
                $file = fopen($dir, 'w');

                fwrite($file, '<?php' . PHP_EOL . 'namespace app\\' . self::$epp . '\model;' . PHP_EOL
                    
                    . PHP_EOL . 'class ' . self::snakeToCamel($item) . ' extends Base'
                    . PHP_EOL . '{' . PHP_EOL);

                $content = '//设置字段信息' . PHP_EOL .
                    '    protected $' . 'schema = [' . PHP_EOL;
                fwrite($file, $content);
                //写入字段
                foreach ($COLUMNS as $COLUMN) {
                    $content = "        '" . $COLUMN['COLUMN_NAME'] . "'" . '  =>'  ."'" . $COLUMN['DATA_TYPE'] . "'" . ',' . '//' . str_replace("\r\n","",$COLUMN['COLUMN_COMMENT']) . PHP_EOL;
                    fwrite($file, $content);
                }
                $content =  '       ];';
                fwrite($file, $content);
                fwrite($file, PHP_EOL . '}');
                fclose($file);
            }

        }
    }
    
    private static function snakeToCamel($str, $capitalized = true)
            {
                $result =str_replace([ucwords(self::$prefix),'_'], ['',""],ucwords($str,"_"),);
                echo $result."--";
                echo str_replace([ucwords(self::$prefix),'_'], ['',''],ucwords($str,'_'),);
                if (!$capitalized) {
                    $result = lcfirst($result);
                }
                return $result;
            }
      
}