package com.qiaoba.module.tenant.util;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.StrUtil;
import com.qiaoba.common.database.util.DbUtil;
import org.springframework.core.io.ClassPathResource;

import java.nio.charset.Charset;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

/**
 * 处理菜单工具类
 *
 * @author ailanyin
 * @version 1.0
 * @since 2023/6/7 11:01
 */
public class MenuUtil {

    private MenuUtil() {
    }

    public static void handleMenu(Connection conn, String tenantId) throws Exception {
        handleSystemMenu(conn, tenantId);
        handleMonitorMenu(conn, tenantId);
    }

    private static void handleMonitorMenu(Connection conn, String tenantId) throws Exception {
        long monitorId = new Snowflake().nextId();
        String sql = "INSERT INTO sys_menu VALUES ('{}', '系统监控', 0, 2, 'monitor', NULL, '', 0, 0, 'M', '1', '', 'monitor', 'admin', '2023-05-27 22:25:03', '', NULL, '系统监控目录', '{}');";
        sql = StrUtil.format(sql, monitorId, tenantId);
        DbUtil.runSql(conn, sql);

        // 登录用户
        Long onlineUserId = handleMenu(conn, monitorId, tenantId, "init/data/sys_menu/monitor/online_user/menu");
        handleButton(conn, tenantId, onlineUserId, "init/data/sys_menu/monitor/online_user/button");
    }

    private static void handleSystemMenu(Connection conn, String tenantId) throws Exception {
        long systemId = new Snowflake().nextId();
        String sql = "INSERT INTO sys_menu VALUES ('{}', '系统管理', 0, 1, 'system', NULL, '', 0, 0, 'M', '1', '', 'system', 'admin', '2023-04-23 14:35:29', '', NULL, '系统管理目录', '{}');";
        sql = StrUtil.format(sql, systemId, tenantId);
        DbUtil.runSql(conn, sql);

        // 用户管理
        Long userId = handleMenu(conn, systemId, tenantId, "init/data/sys_menu/system/user/menu");
        handleButton(conn, tenantId, userId, "init/data/sys_menu/system/user/button");
        // 角色管理
        Long roleId = handleMenu(conn, systemId, tenantId, "init/data/sys_menu/system/role/menu");
        handleButton(conn, tenantId, roleId, "init/data/sys_menu/system/role/button");
        // 菜单管理
        Long menuId = handleMenu(conn, systemId, tenantId, "init/data/sys_menu/system/menu/menu");
        handleButton(conn, tenantId, menuId, "init/data/sys_menu/system/menu/button");
        // 部门管理
        Long deptId = handleMenu(conn, systemId, tenantId, "init/data/sys_menu/system/dept/menu");
        handleButton(conn, tenantId, deptId, "init/data/sys_menu/system/dept/button");
        // 岗位管理
        Long postId = handleMenu(conn, systemId, tenantId, "init/data/sys_menu/system/post/menu");
        handleButton(conn, tenantId, postId, "init/data/sys_menu/system/post/button");
        // 字典管理
        Long dictId = handleMenu(conn, systemId, tenantId, "init/data/sys_menu/system/dict/menu");
        handleButton(conn, tenantId, dictId, "init/data/sys_menu/system/dict/button");
        // 参数管理
        Long configId = handleMenu(conn, systemId, tenantId, "init/data/sys_menu/system/config/menu");
        handleButton(conn, tenantId, configId, "init/data/sys_menu/system/config/button");
    }

    private static Long handleMenu(Connection conn, Long systemId, String tenantId, String fileName) throws Exception {
        long tempId = new Snowflake().nextId();
        ClassPathResource resource = new ClassPathResource(fileName);
        List<String> lines = FileUtil.readLines(resource.getFile(), Charset.defaultCharset());
        StringBuilder sb = new StringBuilder();
        for (String line : lines) {
            if (StrUtil.isNotBlank(line)) {
                line = StrUtil.format(line, tempId, systemId, tenantId);
                sb.append(line);
            }
        }
        if (StrUtil.isNotBlank(sb.toString())) {
            DbUtil.runSql(conn, sb.toString());
        }
        return tempId;
    }

    private static void handleButton(Connection conn, String tenantId, Long parentId, String fileName) throws Exception {
        ClassPathResource resource = new ClassPathResource(fileName);
        List<String> lines = FileUtil.readLines(resource.getFile(), Charset.defaultCharset());
        StringBuilder sb = new StringBuilder();
        for (String line : lines) {
            if (StrUtil.isNotBlank(line)) {
                line = StrUtil.format(line, new Snowflake().nextId(), parentId, tenantId);
                sb.append(line);
            }
        }
        if (StrUtil.isNotBlank(sb.toString())) {
            DbUtil.runSql(conn, sb.toString());
        }
    }

    public static List<String> getAllMenuIdsByTenantId(Connection conn, String tenantId) throws SQLException {
        List<String> menuIds = new ArrayList<>();
        ResultSet resultSet = null;
        Statement statement = null;
        try {
            statement = conn.createStatement();
            resultSet = statement.executeQuery(StrUtil.format("SELECT menu_id FROM sys_menu where tenant_id = '{}'", tenantId));
            while (resultSet.next()) {
                String menuId = resultSet.getString("menu_id");
                if (StrUtil.isNotBlank(menuId)) {
                    menuIds.add(menuId);
                }
            }
        } finally {
            IoUtil.close(resultSet);
            IoUtil.close(statement);
        }
        return menuIds;
    }
}
