<?php
// +----------------------------------------------------------------------
// | 麦沃德科技赋能开发者，助力中小企业发展
// +----------------------------------------------------------------------
// | Copyright (c) 2017～2024  www.wdadmin.cn    All rights reserved.
// +----------------------------------------------------------------------
// | Wdadmin系统产品软件并不是自由软件，不加密，并不代表开源，未经许可不可自由转售和商用
// +----------------------------------------------------------------------
// | Author: MY WORLD Team <bd@maiwd.cn>   www.wdadmin.cn
// +----------------------------------------------------------------------

namespace app\adminapi\controller\tool;

use core\base\BaseAdminController;
use app\adminapi\service\tool\GeneratorService;

/**
 * @OA\Tag(
 *     name="代码生成",
 *     description="开发工具-代码生成"
 * )
 */
class GeneratorController extends BaseAdminController
{
    /**
     * @OA\Get(
     *     path="/tool.generator/lists",
     *     summary="数据表列表",
     *     tags={"代码生成"},
     *     security={{"token": {}}},
     *     @OA\Parameter(name="Token", in="header", description="登录Token", required=false, @OA\Schema(type="string")),
     *     @OA\Parameter(name="page", in="query", description="页码", @OA\Schema(type="integer", default=1)),
     *     @OA\Parameter(name="limit", in="query", description="每页条数", @OA\Schema(type="integer", default=10)),
     *     @OA\Parameter(name="name", in="query", description="表名关键词", @OA\Schema(type="string")),
     *     @OA\Parameter(name="type", in="query", description="类型：imported=已导入，db=未导入", @OA\Schema(type="string", default="imported")),
     *     @OA\Response(
     *         response=200,
     *         description="成功",
     *         @OA\JsonContent(
     *             @OA\Property(property="code", type="integer", example=1),
     *             @OA\Property(property="msg", type="string", example="请求成功"),
     *             @OA\Property(
     *                 property="data",
     *                 type="object",
     *                 @OA\Property(property="total", type="integer", description="总数", example=10),
     *                 @OA\Property(property="per_page", type="integer", description="每页条数", example=15),
     *                 @OA\Property(property="current_page", type="integer", description="当前页", example=1),
     *                 @OA\Property(property="last_page", type="integer", description="最后一页", example=1),
     *                 @OA\Property(
     *                     property="data",
     *                     type="array",
     *                     @OA\Items(
     *                         @OA\Property(property="id", type="integer", description="配置ID"),
     *                         @OA\Property(property="name", type="string", description="表名"),
     *                         @OA\Property(property="comment", type="string", description="表注释"),
     *                         @OA\Property(property="engine", type="string", description="引擎"),
     *                         @OA\Property(property="rows", type="integer", description="行数"),
     *                         @OA\Property(property="create_time", type="string", description="创建时间")
     *                     )
     *                 )
     *             )
     *         )
     *     )
     * )
     */
    public function lists()
    {
        $params = $this->request->get();
        $data = (new GeneratorService())->getTableList($params);
        return success('请求成功', $data);
    }


    /**
     * @OA\Get(
     *     path="/tool.generator/columns",
     *     summary="获取表字段详情",
     *     tags={"代码生成"},
     *     security={{"token": {}}},
     *     @OA\Parameter(name="Token", in="header", description="登录Token", required=false, @OA\Schema(type="string")),
     *     @OA\Parameter(name="id", in="query", description="配置ID（优先使用）", @OA\Schema(type="integer")),
     *     @OA\Parameter(name="table", in="query", description="表名（当id为空时使用）", @OA\Schema(type="string")),
     *     @OA\Response(
     *         response=200,
     *         description="成功",
     *         @OA\JsonContent(
     *             @OA\Property(property="code", type="integer", example=1),
     *             @OA\Property(property="msg", type="string", example="请求成功"),
     *             @OA\Property(
     *                 property="data",
     *                 type="object",
     *                 @OA\Property(
     *                     property="fields",
     *                     type="array",
     *                     @OA\Items(
     *                         @OA\Property(property="name", type="string", description="字段名"),
     *                         @OA\Property(property="desc", type="string", description="字段描述"),
     *                         @OA\Property(property="type", type="string", description="字段类型"),
     *                         @OA\Property(property="is_pk", type="boolean", description="是否主键"),
     *                         @OA\Property(property="is_required", type="boolean", description="是否必填"),
     *                         @OA\Property(property="is_insert", type="boolean", description="是否用于新增"),
     *                         @OA\Property(property="is_edit", type="boolean", description="是否用于编辑"),
     *                         @OA\Property(property="is_list", type="boolean", description="是否显示在列表"),
     *                         @OA\Property(property="is_query", type="boolean", description="是否用于查询"),
     *                         @OA\Property(property="query_type", type="string", description="查询类型"),
     *                         @OA\Property(property="form_type", type="string", description="表单类型"),
     *                         @OA\Property(property="validation_type", type="string", description="验证类型"),
     *                         @OA\Property(property="options", type="string", description="选项配置"),
     *                         @OA\Property(property="dict_type", type="string", description="字典类型")
     *                     )
     *                 ),
     *                 @OA\Property(
     *                     property="info",
     *                     type="object",
     *                     @OA\Property(property="id", type="integer", description="配置ID"),
     *                     @OA\Property(property="table_name", type="string", description="表名"),
     *                     @OA\Property(property="class_name", type="string", description="类名"),
     *                     @OA\Property(property="class_comment", type="string", description="类注释"),
     *                     @OA\Property(property="module_name", type="string", description="模块名"),
     *                     @OA\Property(property="config", type="object", description="其他配置")
     *                 )
     *             )
     *         )
     *     ),
     *     @OA\Response(
     *         response=400,
     *         description="参数错误",
     *         @OA\JsonContent(
     *             @OA\Property(property="code", type="integer", example=0),
     *             @OA\Property(property="msg", type="string", example="ID或表名不能为空")
     *         )
     *     )
     * )
     */
    public function columns()
    {
        $id = $this->request->get('id');
        $table = $this->request->get('table');

        // 优先使用 id 查询，否则使用 table_name
        $idOrTableName = $id ?: $table;
        if (empty($idOrTableName)) return fail('ID或表名不能为空');

        $data = (new GeneratorService())->getColumns($idOrTableName);
        return success('请求成功', $data);
    }

    /**
     * @OA\Post(
     *     path="/tool.generator/preview",
     *     summary="预览代码",
     *     tags={"代码生成"},
     *     security={{"token": {}}},
     *     @OA\Parameter(name="Token", in="header", description="登录Token", required=false, @OA\Schema(type="string")),
     *     @OA\RequestBody(
     *         required=true,
     *         @OA\JsonContent(
     *             required={"id"},
     *             @OA\Property(property="id", type="integer", description="配置ID")
     *         )
     *     ),
     *     @OA\Response(response=200, description="成功")
     * )
     */
    public function preview()
    {
        $params = $this->request->post();
        if (empty($params['id'])) {
            return fail('ID不能为空');
        }
        $data = (new GeneratorService())->preview($params);
        return success('请求成功', $data);
    }

    /**
     * @OA\Post(
     *     path="/tool.generator/generate",
     *     summary="生成代码（支持批量）",
     *     tags={"代码生成"},
     *     security={{"token": {}}},
     *     @OA\Parameter(name="Token", in="header", description="登录Token", required=false, @OA\Schema(type="string")),
     *     @OA\RequestBody(
     *         required=true,
     *         @OA\JsonContent(
     *             required={"id"},
     *             @OA\Property(
     *                 property="id", 
     *                 description="配置ID（单个：6，批量：[6,7,8]）", 
     *                 oneOf={
     *                     @OA\Schema(type="integer", example=6),
     *                     @OA\Schema(type="array", @OA\Items(type="integer"), example={6, 7, 8})
     *                 }
     *             )
     *         )
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="成功",
     *         @OA\JsonContent(
     *             @OA\Property(property="code", type="integer", example=1),
     *             @OA\Property(property="msg", type="string", example="生成成功，共处理 3 条记录")
     *         )
     *     )
     * )
     */
    public function generate()
    {
        $params = $this->request->post();
        if (empty($params['id'])) {
            return fail('ID不能为空');
        }
        $count = (new GeneratorService())->generate($params['id']);
        return success("生成成功，共处理 {$count} 条记录");
    }

    /**
     * @OA\Post(
     *     path="/tool.generator/import",
     *     summary="导入表",
     *     tags={"代码生成"},
     *     security={{"token": {}}},
     *     @OA\Parameter(name="Token", in="header", description="登录Token", required=false, @OA\Schema(type="string")),
     *     @OA\RequestBody(
     *         required=true,
     *         @OA\JsonContent(
     *             required={"tables"},
     *             @OA\Property(property="tables", type="array", @OA\Items(type="string"), description="表名数组", example={"wd_article", "wd_goods"})
     *         )
     *     ),
     *     @OA\Response(response=200, description="成功")
     * )
     */
    public function import()
    {
        $params = $this->request->post();
        if (empty($params['tables'])) {
            return fail('请选择要导入的表');
        }
        (new GeneratorService())->import($params['tables']);
        return success('导入成功');
    }

    /**
     * @OA\Post(
     *     path="/tool.generator/save",
     *     summary="保存配置",
     *     tags={"代码生成"},
     *     security={{"token": {}}},
     *     @OA\Parameter(name="Token", in="header", description="登录Token", required=false, @OA\Schema(type="string")),
     *     @OA\RequestBody(
     *         required=true,
     *         @OA\JsonContent(
     *             required={"id"},
     *             @OA\Property(property="id", type="integer", description="配置ID"),
     *             @OA\Property(property="class_name", type="string", description="类名"),
     *             @OA\Property(property="class_comment", type="string", description="类注释"),
     *             @OA\Property(property="module_name", type="string", description="模块名"),
     *             @OA\Property(property="fields", type="array", @OA\Items(type="object"), description="字段配置"),
     *             @OA\Property(property="config", type="object", description="其他配置")
     *         )
     *     ),
     *     @OA\Response(response=200, description="成功")
     * )
     */
    public function save()
    {
        $params = $this->request->post();
        if (empty($params['id'])) {
            return fail('ID不能为空');
        }
        (new GeneratorService())->saveConfig($params);
        return success('保存成功');
    }

    /**
     * @OA\Post(
     *     path="/tool.generator/delete",
     *     summary="删除（支持批量）",
     *     tags={"代码生成"},
     *     security={{"token": {}}},
     *     @OA\Parameter(name="Token", in="header", description="登录Token", required=false, @OA\Schema(type="string")),
     *     @OA\RequestBody(
     *         required=true,
     *         @OA\JsonContent(
     *             required={"id"},
     *             @OA\Property(
     *                 property="id", 
     *                 description="配置ID（单个：6，批量：[6,7,8]）", 
     *                 oneOf={
     *                     @OA\Schema(type="integer", example=6),
     *                     @OA\Schema(type="array", @OA\Items(type="integer"), example={6, 7, 8})
     *                 }
     *             )
     *         )
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="成功",
     *         @OA\JsonContent(
     *             @OA\Property(property="code", type="integer", example=1),
     *             @OA\Property(property="msg", type="string", example="删除成功")
     *         )
     *     )
     * )
     */
    public function delete()
    {
        $params = $this->request->post();
        if (empty($params['id'])) {
            return fail('ID不能为空');
        }
        (new GeneratorService())->delete($params['id']);
        return success('删除成功');
    }


    public function models()
    {
        $data = (new GeneratorService())->getModels();
        return success('请求成功', $data);
    }


    public function menus()
    {
        $data = (new GeneratorService())->getMenuTree();
        return success('请求成功', $data);
    }
}
