package com.agileboot.codegen.service.impl;

import com.agileboot.codegen.dto.TemplateRepositoryDTO;
import com.agileboot.codegen.entity.UserTemplate;
import com.agileboot.codegen.entity.UserTemplateRepository;
import com.agileboot.codegen.mapper.UserTemplateMapper;
import com.agileboot.codegen.mapper.UserTemplateRepositoryMapper;
import com.agileboot.codegen.service.IGeneratorService;
import com.agileboot.codegen.service.ITemplateRepositoryService;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 模板仓库 Service实现类
 *
 * @author system
 * @date 2025-09-26
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TemplateRepositoryServiceImpl implements ITemplateRepositoryService {

    private final UserTemplateRepositoryMapper repositoryMapper;
    private final UserTemplateMapper userTemplateMapper;
    private final IGeneratorService generatorService;

    @Override
    public JSONArray getUserTemplateConfig(Long userId) {
        // 获取用户启用的模板仓库配置（公开模板）
        List<UserTemplateRepository> repositories = repositoryMapper.selectEnabledByUserId(userId);

        // 按分组组织模板
        Map<String, List<JSONObject>> groupedTemplates = new HashMap<>();

        for (UserTemplateRepository repo : repositories) {
            String group = repo.getTemplateGroup();

            JSONObject template = new JSONObject();
            template.put("id", repo.getTemplateId());
            template.put("name", repo.getTemplateName());
            template.put("description", repo.getTemplateName());
            template.put("source", repo.getTemplateSource()); // 添加来源标识

            groupedTemplates.computeIfAbsent(group, k -> new ArrayList<>()).add(template);
        }

        // 添加用户自己的启用模板（包括私有模板）
        List<UserTemplate> userEnabledTemplates = userTemplateMapper.selectList(
                new LambdaQueryWrapper<UserTemplate>()
                        .eq(UserTemplate::getUserId, userId)
                        .eq(UserTemplate::getIsEnabled, 1)
                        .eq(UserTemplate::getStatus, 1) // 只包含发布状态的模板
        );

        for (UserTemplate userTemplate : userEnabledTemplates) {
            // 如果是公开模板且已经在仓库配置中，跳过（避免重复）
            if (userTemplate.getIsPublic() == 1) {
                boolean alreadyInRepo = repositories.stream()
                        .anyMatch(repo -> "user".equals(repo.getTemplateSource()) &&
                                userTemplate.getId().toString().equals(repo.getTemplateId()));
                if (alreadyInRepo) {
                    continue;
                }
            }

            String group = userTemplate.getTemplateGroup();
            JSONObject template = new JSONObject();
            template.put("id", userTemplate.getId().toString());
            template.put("name", userTemplate.getTemplateName());
            template.put("description", userTemplate.getTemplateName());
            template.put("source", "user");

            groupedTemplates.computeIfAbsent(group, k -> new ArrayList<>()).add(template);
        }

        // 如果用户没有配置任何模板，先初始化用户仓库，然后重新获取
        if (groupedTemplates.isEmpty()) {
            log.info("用户 {} 没有模板配置，自动初始化用户仓库", userId);
            boolean initSuccess = initUserRepository(userId);
            if (initSuccess) {
                // 重新获取用户启用的模板仓库配置
                repositories = repositoryMapper.selectEnabledByUserId(userId);
                for (UserTemplateRepository repo : repositories) {
                    String group = repo.getTemplateGroup();

                    JSONObject template = new JSONObject();
                    template.put("id", repo.getTemplateId());
                    template.put("name", repo.getTemplateName());
                    template.put("description", repo.getTemplateName());
                    template.put("source", repo.getTemplateSource());

                    groupedTemplates.computeIfAbsent(group, k -> new ArrayList<>()).add(template);
                }
            } else {
                // 初始化失败，返回系统默认模板
                return JSONArray.parseArray(generatorService.getTemplateConfig());
            }
        }

        // 转换为JSONArray格式
        JSONArray result = new JSONArray();
        for (Map.Entry<String, List<JSONObject>> entry : groupedTemplates.entrySet()) {
            JSONObject group = new JSONObject();
            group.put("group", entry.getKey());
            group.put("templates", entry.getValue());
            result.add(group);
        }

        return result;
    }

    @Override
    public List<UserTemplateRepository> getUserRepositoryList(Long userId) {
        return repositoryMapper.selectAllByUserId(userId);
    }

    @Override
    public List<TemplateRepositoryDTO> getAvailableTemplates(Long userId) {
        List<TemplateRepositoryDTO> result = new ArrayList<>();

        // 一次性获取用户的所有仓库配置，避免N+1查询
        List<UserTemplateRepository> userRepositories = repositoryMapper.selectAllByUserId(userId);

        // 如果用户没有任何仓库配置，才进行初始化
        if (userRepositories.isEmpty()) {
            initUserRepository(userId);
            // 重新获取初始化后的配置
            userRepositories = repositoryMapper.selectAllByUserId(userId);
        }

        Map<String, UserTemplateRepository> repoMap = userRepositories.stream()
                .collect(Collectors.toMap(
                        repo -> repo.getTemplateSource() + ":" + repo.getTemplateId(),
                        repo -> repo
                ));

        // 1. 添加系统模板
        try {
            JSONArray systemTemplates = JSONArray.parseArray(generatorService.getTemplateConfig());
            for (Object groupObj : systemTemplates) {
                JSONObject group = (JSONObject) groupObj;
                String groupName = group.getString("group");
                JSONArray templates = group.getJSONArray("wol-module-codegen/src/main/resources/templates");

                for (Object templateObj : templates) {
                    JSONObject template = (JSONObject) templateObj;
                    TemplateRepositoryDTO dto = new TemplateRepositoryDTO();
                    dto.setTemplateSource("system");
                    dto.setTemplateId(template.getString("id"));
                    dto.setTemplateName(template.getString("name"));
                    dto.setTemplateGroup(groupName);
                    dto.setDescription(template.getString("description")); // 系统模板描述

                    // 从内存中获取显示状态，避免数据库查询
                    String key = "system:" + template.getString("id");
                    UserTemplateRepository userRepo = repoMap.get(key);
                    dto.setIsEnabled(userRepo != null ? userRepo.getIsEnabled() : 0); // 默认显示

                    result.add(dto);
                }
            }
        } catch (Exception e) {
            log.error("解析系统模板配置失败", e);
        }

        // 2. 添加公开的用户模板
        List<UserTemplate> publicTemplates = userTemplateMapper.selectPublicTemplates(null);
        for (UserTemplate template : publicTemplates) {
            TemplateRepositoryDTO dto = new TemplateRepositoryDTO();
            dto.setTemplateSource("user");
            dto.setTemplateId(template.getId().toString());
            dto.setTemplateName(template.getTemplateName());
            dto.setTemplateGroup(template.getTemplateGroup());
            dto.setDescription(template.getDescription()); // 用户模板描述

            // 从内存中获取显示状态，避免数据库查询
            String key = "user:" + template.getId().toString();
            UserTemplateRepository userRepo = repoMap.get(key);
            dto.setIsEnabled(userRepo != null ? userRepo.getIsEnabled() : 0); // 默认显示

            result.add(dto);
        }

        return result;
    }

    @Override
    @Transactional
    public boolean addTemplateToRepository(Long userId, String templateSource, String templateId,
                                           String templateName, String templateGroup) {
        // 检查是否已存在
        if (repositoryMapper.checkTemplateExists(userId, templateSource, templateId) > 0) {
            return false;
        }

        UserTemplateRepository repository = new UserTemplateRepository();
        repository.setUserId(userId);
        repository.setTemplateSource(templateSource);
        repository.setTemplateId(templateId);
        repository.setTemplateName(templateName);
        repository.setTemplateGroup(templateGroup);
        repository.setIsEnabled(1);
        repository.setSortOrder(repositoryMapper.getMaxSortOrder(userId) + 1);

        return repositoryMapper.insert(repository) > 0;
    }

    @Override
    @Transactional
    public boolean removeTemplateFromRepository(Long userId, String templateSource, String templateId) {
        return repositoryMapper.deleteByTemplate(userId, templateSource, templateId) > 0;
    }

    @Override
    @Transactional
    public boolean toggleTemplateStatus(Long userId, String templateSource, String templateId, Integer isEnabled) {
        // 先检查记录是否存在
        if (repositoryMapper.checkTemplateExists(userId, templateSource, templateId) == 0) {
            // 记录不存在，需要先创建
            log.info("模板记录不存在，先创建记录: userId={}, templateSource={}, templateId={}", userId, templateSource, templateId);

            // 获取模板信息
            String templateName = "";
            String templateGroup = "";

            if ("system".equals(templateSource)) {
                // 系统模板，从配置中获取信息
                try {
                    JSONArray systemTemplates = JSONArray.parseArray(generatorService.getTemplateConfig());
                    for (Object groupObj : systemTemplates) {
                        JSONObject group = (JSONObject) groupObj;
                        String groupName = group.getString("group");
                        JSONArray templates = group.getJSONArray("wol-module-codegen/src/main/resources/templates");

                        for (Object templateObj : templates) {
                            JSONObject template = (JSONObject) templateObj;
                            if (templateId.equals(template.getString("id"))) {
                                templateName = template.getString("name");
                                templateGroup = groupName;
                                break;
                            }
                        }
                        if (!templateName.isEmpty()) break;
                    }
                } catch (Exception e) {
                    log.error("获取系统模板信息失败", e);
                    return false;
                }
            } else if ("user".equals(templateSource)) {
                // 用户模板，从数据库获取信息
                try {
                    UserTemplate userTemplate = userTemplateMapper.selectById(Long.parseLong(templateId));
                    if (userTemplate != null) {
                        templateName = userTemplate.getTemplateName();
                        templateGroup = userTemplate.getTemplateGroup();
                    }
                } catch (Exception e) {
                    log.error("获取用户模板信息失败", e);
                    return false;
                }
            }

            if (templateName.isEmpty()) {
                log.error("无法获取模板信息: templateSource={}, templateId={}", templateSource, templateId);
                return false;
            }

            // 创建记录
            UserTemplateRepository repository = new UserTemplateRepository();
            repository.setUserId(userId);
            repository.setTemplateSource(templateSource);
            repository.setTemplateId(templateId);
            repository.setTemplateName(templateName);
            repository.setTemplateGroup(templateGroup);
            repository.setIsEnabled(isEnabled);
            repository.setSortOrder(repositoryMapper.getMaxSortOrder(userId) + 1);

            return repositoryMapper.insert(repository) > 0;
        } else {
            // 记录存在，直接更新状态
            return repositoryMapper.toggleTemplateStatus(userId, templateSource, templateId, isEnabled) > 0;
        }
    }

    @Override
    @Transactional
    public boolean updateTemplateSort(Long userId, List<TemplateRepositoryDTO> templates) {
        try {
            for (int i = 0; i < templates.size(); i++) {
                TemplateRepositoryDTO dto = templates.get(i);
                repositoryMapper.updateSortOrder(userId, dto.getTemplateSource(), dto.getTemplateId(), i + 1);
            }
            return true;
        } catch (Exception e) {
            log.error("更新模板排序失败", e);
            return false;
        }
    }

    @Override
    @Transactional
    public boolean initUserRepository(Long userId) {
        try {
            // 先获取用户已有的仓库配置
            List<UserTemplateRepository> existingRepos = repositoryMapper.selectAllByUserId(userId);
            Set<String> existingKeys = existingRepos.stream()
                    .map(repo -> repo.getTemplateSource() + ":" + repo.getTemplateId())
                    .collect(Collectors.toSet());

            int sortOrder = repositoryMapper.getMaxSortOrder(userId) + 1;
            List<UserTemplateRepository> toInsert = new ArrayList<>();

            // 1. 将系统默认模板添加到用户仓库（如果不存在）
            JSONArray systemTemplates = JSONArray.parseArray(generatorService.getTemplateConfig());

            for (Object groupObj : systemTemplates) {
                JSONObject group = (JSONObject) groupObj;
                String groupName = group.getString("group");
                JSONArray templates = group.getJSONArray("wol-module-codegen/src/main/resources/templates");

                for (Object templateObj : templates) {
                    JSONObject template = (JSONObject) templateObj;
                    String templateId = template.getString("id");
                    String key = "system:" + templateId;

                    // 从内存中检查是否已存在，避免数据库查询
                    if (!existingKeys.contains(key)) {
                        UserTemplateRepository repository = new UserTemplateRepository();
                        repository.setUserId(userId);
                        repository.setTemplateSource("system");
                        repository.setTemplateId(templateId);
                        repository.setTemplateName(template.getString("name"));
                        repository.setTemplateGroup(groupName);
                        repository.setIsEnabled(0); // 系统模板默认启用
                        repository.setSortOrder(sortOrder++);

                        toInsert.add(repository);
                    }
                }
            }

            // 批量插入，减少数据库交互
            for (UserTemplateRepository repo : toInsert) {
                repositoryMapper.insert(repo);
            }

            // 2. 将公开的用户模板添加到用户仓库（如果不存在）
            List<UserTemplate> publicTemplates = userTemplateMapper.selectPublicTemplates(null);
            for (UserTemplate template : publicTemplates) {
                String templateId = template.getId().toString();

                // 检查是否已存在
                if (repositoryMapper.checkTemplateExists(userId, "user", templateId) == 0) {
                    UserTemplateRepository repository = new UserTemplateRepository();
                    repository.setUserId(userId);
                    repository.setTemplateSource("user");
                    repository.setTemplateId(templateId);
                    repository.setTemplateName(template.getTemplateName());
                    repository.setTemplateGroup(template.getTemplateGroup());
                    repository.setIsEnabled(1); // 公开模板默认启用
                    repository.setSortOrder(sortOrder++);

                    repositoryMapper.insert(repository);
                }
            }

            return true;
        } catch (Exception e) {
            log.error("初始化用户模板仓库失败", e);
            return false;
        }
    }

    @Override
    public boolean checkTemplateExists(Long userId, String templateSource, String templateId) {
        return repositoryMapper.checkTemplateExists(userId, templateSource, templateId) > 0;
    }
}

