<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\Dashboard;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Column;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class ToolController extends Controller
{

    public function transformer($talbe)
    {
        $columns = $this->getTableColumns($talbe);
        $output = '<pre>';
        foreach ($columns as $column) {
            $name = $column->getName();
            $type = $column->getType()->getName();
            $default = $column->getDefault();

            $defaultValue = '';

            // set column fieldType and defaultValue
            switch ($type) {
                case 'id':
                case 'bool':
                case 'integer':
                case 'bigint':
                case 'smallint':
                case 'decimal':
                case 'float':
                    $fieldType = 'number';
                    break;
                default:
                    $fieldType = 'string';
            }
            $comment = $column->getComment()??$name;
            $output .='     *     @OA\Property(property="'.$name.'", type="'.$fieldType.'", description="'.$comment.'"),';

            $output .= "\r\n";
        }

        return $output;
    }

    protected function getTableColumns($table)
    {
        if (!DB::connection()->isDoctrineAvailable()) {
            throw new \Exception(
                'You need to require doctrine/dbal: ~2.3 in your own composer.json to get database columns. '
            );
        }

        if (!Schema::hasTable($table)) {
            throw new \Exception(
                '表不存在 '
            );
        }

        //$table = $this->model->getConnection()->getTablePrefix().$this->model->getTable();
        /** @var \Doctrine\DBAL\Schema\MySqlSchemaManager $schema */
        $schema = DB::connection()->getDoctrineSchemaManager($table);

        // custom mapping the types that doctrine/dbal does not support
        $databasePlatform = $schema->getDatabasePlatform();

        $doctrineTypeMapping = [
            'string' => [
                'enum', 'geometry', 'geometrycollection', 'linestring',
                'polygon', 'multilinestring', 'multipoint', 'multipolygon',
                'point',
            ],
        ];

        foreach ($doctrineTypeMapping as $doctrineType => $dbTypes) {
            foreach ($dbTypes as $dbType) {
                $databasePlatform->registerDoctrineTypeMapping($dbType, $doctrineType);
            }
        }

        $database = null;
        if (strpos($table, '.')) {
            list($database, $table) = explode('.', $table);
        }

        return $schema->listTableColumns($table, $database);
    }
}
