package org.hzhub.erp.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import lombok.RequiredArgsConstructor;
import org.hzhub.erp.common.domain.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ERP 数据库探查工具
 */
@SaIgnore
@RestController
@RequestMapping("/erp/test")
@RequiredArgsConstructor
public class ErpExploreController {

    private static final Logger log = LoggerFactory.getLogger(ErpExploreController.class);
    private final JdbcTemplate jdbcTemplate;

    @Value("${spring.datasource.url}")
    private String datasourceUrl;

    @Value("${spring.datasource.username}")
    private String datasourceUsername;

    /**
     * 探查数据库所有表，返回统计信息
     */
    @GetMapping("/explore")
    public R<Map<String, Object>> exploreDatabase() {
        Map<String, Object> result = new HashMap<>();
        try {
            // 获取数据库名
            String dbName = jdbcTemplate.queryForObject("SELECT DB_NAME()", String.class);
            result.put("database", dbName);

            // 获取所有用户表及其基本信息
            String sql =
                "SELECT " +
                "    t.name AS tableName, " +
                "    SCHEMA_NAME(t.schema_id) AS schemaName, " +
                "    p.rows AS rowCount, " +
                "    c2.columnCount, " +
                "    CASE WHEN pk.colCount > 0 THEN 1 ELSE 0 END AS hasPrimaryKey " +
                "FROM sys.tables t " +
                "CROSS APPLY ( " +
                "    SELECT COUNT(*) AS columnCount " +
                "    FROM sys.columns c " +
                "    WHERE c.object_id = t.object_id " +
                ") c2 " +
                "LEFT JOIN sys.partitions p ON t.object_id = p.object_id AND p.index_id IN (0, 1) " +
                "OUTER APPLY ( " +
                "    SELECT COUNT(*) AS colCount " +
                "    FROM sys.index_columns ic " +
                "    INNER JOIN sys.indexes i ON ic.object_id = i.object_id AND ic.index_id = i.index_id " +
                "    WHERE ic.object_id = t.object_id AND i.is_primary_key = 1 " +
                ") pk " +
                "WHERE t.type = 'U' " +
                "ORDER BY p.rows DESC";

            List<Map<String, Object>> tables = jdbcTemplate.queryForList(sql);
            result.put("tables", tables);
            result.put("totalTables", tables.size());

            return R.ok("数据库探查成功", result);
        } catch (Exception e) {
            log.error("数据库探查失败", e);
            return R.fail("数据库探查失败: " + e.getMessage());
        }
    }

    /**
     * 查看指定表的列信息
     */
    @GetMapping("/explore/table")
    public R<Map<String, Object>> exploreTable(@org.springframework.web.bind.annotation.RequestParam String tableName) {
        Map<String, Object> result = new HashMap<>();
        try {
            String sql =
                "SELECT " +
                "    c.name AS columnName, " +
                "    TYPE_NAME(c.user_type_id) AS dataType, " +
                "    c.max_length AS maxLength, " +
                "    c.is_nullable AS nullable, " +
                "    c.is_identity AS isIdentity, " +
                "    ep.value AS description " +
                "FROM sys.columns c " +
                "INNER JOIN sys.tables t ON c.object_id = t.object_id " +
                "LEFT JOIN sys.extended_properties ep ON c.object_id = ep.major_id " +
                "    AND c.column_id = ep.minor_id AND ep.name = 'MS_Description' " +
                "WHERE t.name = ? " +
                "ORDER BY c.column_id";
            List<Map<String, Object>> columns = jdbcTemplate.queryForList(sql, tableName);
            result.put("tableName", tableName);
            result.put("columns", columns);
            return R.ok(result);
        } catch (Exception e) {
            return R.fail("查询表结构失败: " + e.getMessage());
        }
    }
}
