package com.emotion.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.emotion.common.PageResult;
import com.emotion.dto.request.aiconfig.AiConfigCreateRequest;
import com.emotion.dto.request.aiconfig.AiConfigPageRequest;
import com.emotion.dto.request.aiconfig.AiConfigTestUpdateRequest;
import com.emotion.dto.request.aiconfig.AiConfigUpdateRequest;
import com.emotion.dto.response.aiconfig.AiConfigResponse;
import com.emotion.entity.AiConfig;
import com.emotion.mapper.AiConfigMapper;
import com.emotion.service.AiConfigService;
import com.emotion.util.SnowflakeIdGenerator;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

/**
 * AI配置服务实现类
 * 
 * @author system
 * @date 2025-10-30
 */
@Service
public class AiConfigServiceImpl extends ServiceImpl<AiConfigMapper, AiConfig> implements AiConfigService {

    @Autowired
    private SnowflakeIdGenerator snowflakeIdGenerator;

    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    public IPage<AiConfig> getPage(AiConfigPageRequest request) {
        Page<AiConfig> page = new Page<>(request.getCurrent(), request.getSize());
        LambdaQueryWrapper<AiConfig> wrapper = new LambdaQueryWrapper<>();
        
        // 关键词搜索
        if (StringUtils.hasText(request.getKeyword())) {
            wrapper.and(w -> w.like(AiConfig::getConfigName, request.getKeyword())
                    .or().like(AiConfig::getConfigKey, request.getKeyword())
                    .or().like(AiConfig::getDescription, request.getKeyword()));
        }
        
        // 配置类型过滤
        if (StringUtils.hasText(request.getConfigType())) {
            wrapper.eq(AiConfig::getConfigType, request.getConfigType());
        }
        
        // 服务提供商过滤
        if (StringUtils.hasText(request.getProvider())) {
            wrapper.eq(AiConfig::getProvider, request.getProvider());
        }
        
        // 使用场景过滤
        if (StringUtils.hasText(request.getUsageScenario())) {
            wrapper.eq(AiConfig::getUsageScenario, request.getUsageScenario());
        }
        
        // 是否启用过滤
        if (request.getIsEnabled() != null) {
            wrapper.eq(AiConfig::getIsEnabled, request.getIsEnabled());
        }
        
        // 是否为默认配置过滤
        if (request.getIsDefault() != null) {
            wrapper.eq(AiConfig::getIsDefault, request.getIsDefault());
        }
        
        // 环境过滤
        if (StringUtils.hasText(request.getEnvironment())) {
            wrapper.eq(AiConfig::getEnvironment, request.getEnvironment());
        }
        
        // 排序
        if (StringUtils.hasText(request.getOrderBy())) {
            if ("asc".equalsIgnoreCase(request.getOrderDirection())) {
                wrapper.orderByAsc(getLambdaByField(request.getOrderBy()));
            } else {
                wrapper.orderByDesc(getLambdaByField(request.getOrderBy()));
            }
        } else {
            wrapper.orderByDesc(AiConfig::getCreateTime);
        }
        
        return this.page(page, wrapper);
    }

    @Override
    public PageResult<AiConfigResponse> getPageWithResponse(AiConfigPageRequest request) {
        IPage<AiConfig> page = getPage(request);
        List<AiConfigResponse> responses = page.getRecords().stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList());
        
        PageResult<AiConfigResponse> result = new PageResult<>();
        result.setCurrent(page.getCurrent());
        result.setSize(page.getSize());
        result.setTotal(page.getTotal());
        result.setPages(page.getPages());
        result.setRecords(responses);
        return result;
    }

    @Override
    public AiConfigResponse getAiConfigResponseById(String id) {
        AiConfig aiConfig = this.getById(id);
        return aiConfig != null ? convertToResponse(aiConfig) : null;
    }

    @Override
    public AiConfigResponse createAiConfigWithResponse(AiConfigCreateRequest request) {
        AiConfig aiConfig = new AiConfig();
        BeanUtils.copyProperties(request, aiConfig);
        aiConfig.setId(String.valueOf(snowflakeIdGenerator.nextId()));
        
        // 处理JSON字段，防止空字符串导致数据库报错
        if (!StringUtils.hasText(aiConfig.getCustomHeaders())) {
            aiConfig.setCustomHeaders("{}");
        }
        if (!StringUtils.hasText(aiConfig.getCustomParams())) {
            aiConfig.setCustomParams("{}");
        }
        
        boolean saved = this.save(aiConfig);
        return saved ? convertToResponse(aiConfig) : null;
    }

    @Override
    public AiConfigResponse updateAiConfigWithResponse(AiConfigUpdateRequest request) {
        AiConfig aiConfig = this.getById(request.getId());
        if (aiConfig == null) {
            return null;
        }
        
        BeanUtils.copyProperties(request, aiConfig);
        
        // 处理JSON字段，防止空字符串导致数据库报错
        if (request.getCustomHeaders() != null && !StringUtils.hasText(request.getCustomHeaders())) {
            aiConfig.setCustomHeaders("{}");
        }
        if (request.getCustomParams() != null && !StringUtils.hasText(request.getCustomParams())) {
            aiConfig.setCustomParams("{}");
        }
        
        boolean updated = this.updateById(aiConfig);
        return updated ? convertToResponse(aiConfig) : null;
    }

    @Override
    public List<AiConfig> getByConfigType(String configType) {
        LambdaQueryWrapper<AiConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AiConfig::getConfigType, configType);
        wrapper.orderByDesc(AiConfig::getPriority);
        return this.list(wrapper);
    }

    @Override
    public List<AiConfigResponse> getByConfigTypeWithResponse(String configType) {
        return getByConfigType(configType).stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList());
    }

    @Override
    public List<AiConfig> getByProvider(String provider) {
        LambdaQueryWrapper<AiConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AiConfig::getProvider, provider);
        wrapper.orderByDesc(AiConfig::getPriority);
        return this.list(wrapper);
    }

    @Override
    public List<AiConfigResponse> getByProviderWithResponse(String provider) {
        return getByProvider(provider).stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList());
    }

    @Override
    public List<AiConfig> getByUsageScenario(String usageScenario) {
        LambdaQueryWrapper<AiConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AiConfig::getUsageScenario, usageScenario);
        wrapper.eq(AiConfig::getIsEnabled, 1);
        wrapper.orderByDesc(AiConfig::getPriority);
        return this.list(wrapper);
    }

    @Override
    public List<AiConfigResponse> getByUsageScenarioWithResponse(String usageScenario) {
        return getByUsageScenario(usageScenario).stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList());
    }

    @Override
    public List<AiConfig> getByEnvironment(String environment) {
        LambdaQueryWrapper<AiConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AiConfig::getEnvironment, environment);
        wrapper.orderByDesc(AiConfig::getPriority);
        return this.list(wrapper);
    }

    @Override
    public List<AiConfigResponse> getByEnvironmentWithResponse(String environment) {
        return getByEnvironment(environment).stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList());
    }

    @Override
    public List<AiConfig> getEnabledConfigs() {
        LambdaQueryWrapper<AiConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AiConfig::getIsEnabled, 1);
        wrapper.orderByDesc(AiConfig::getPriority);
        return this.list(wrapper);
    }

    @Override
    public List<AiConfigResponse> getEnabledConfigsWithResponse() {
        return getEnabledConfigs().stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList());
    }

    @Override
    public List<AiConfig> getDisabledConfigs() {
        LambdaQueryWrapper<AiConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AiConfig::getIsEnabled, 0);
        wrapper.orderByDesc(AiConfig::getCreateTime);
        return this.list(wrapper);
    }

    @Override
    public List<AiConfigResponse> getDisabledConfigsWithResponse() {
        return getDisabledConfigs().stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList());
    }

    @Override
    public List<AiConfig> getDefaultConfigs() {
        LambdaQueryWrapper<AiConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AiConfig::getIsDefault, 1);
        wrapper.orderByDesc(AiConfig::getPriority);
        return this.list(wrapper);
    }

    @Override
    public List<AiConfigResponse> getDefaultConfigsWithResponse() {
        return getDefaultConfigs().stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList());
    }

    @Override
    public AiConfig getByConfigKey(String configKey) {
        LambdaQueryWrapper<AiConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AiConfig::getConfigKey, configKey);
        wrapper.eq(AiConfig::getIsEnabled, 1);
        return this.getOne(wrapper);
    }

    @Override
    public AiConfigResponse getByConfigKeyWithResponse(String configKey) {
        AiConfig aiConfig = getByConfigKey(configKey);
        return aiConfig != null ? convertToResponse(aiConfig) : null;
    }

    @Override
    public boolean enableConfig(String id) {
        LambdaUpdateWrapper<AiConfig> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(AiConfig::getId, id);
        wrapper.set(AiConfig::getIsEnabled, 1);
        return this.update(wrapper);
    }

    @Override
    public boolean disableConfig(String id) {
        LambdaUpdateWrapper<AiConfig> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(AiConfig::getId, id);
        wrapper.set(AiConfig::getIsEnabled, 0);
        return this.update(wrapper);
    }

    @Override
    public boolean setAsDefault(String id) {
        LambdaUpdateWrapper<AiConfig> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(AiConfig::getId, id);
        wrapper.set(AiConfig::getIsDefault, 1);
        return this.update(wrapper);
    }

    @Override
    public boolean unsetDefault(String id) {
        LambdaUpdateWrapper<AiConfig> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(AiConfig::getId, id);
        wrapper.set(AiConfig::getIsDefault, 0);
        return this.update(wrapper);
    }

    @Override
    public AiConfig getBestConfig(String usageScenario, String environment) {
        LambdaQueryWrapper<AiConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AiConfig::getUsageScenario, usageScenario);
        wrapper.eq(AiConfig::getEnvironment, environment);
        wrapper.eq(AiConfig::getIsEnabled, 1);
        wrapper.orderByDesc(AiConfig::getIsDefault);
        wrapper.orderByDesc(AiConfig::getPriority);
        wrapper.last("LIMIT 1");
        return this.getOne(wrapper);
    }

    @Override
    public AiConfigResponse getBestConfigWithResponse(String usageScenario, String environment) {
        AiConfig aiConfig = getBestConfig(usageScenario, environment);
        return aiConfig != null ? convertToResponse(aiConfig) : null;
    }

    @Override
    public Long countEnabledConfigs() {
        LambdaQueryWrapper<AiConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AiConfig::getIsEnabled, 1);
        return this.count(wrapper);
    }

    @Override
    public Long countDisabledConfigs() {
        LambdaQueryWrapper<AiConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AiConfig::getIsEnabled, 0);
        return this.count(wrapper);
    }

    @Override
    public Long countDefaultConfigs() {
        LambdaQueryWrapper<AiConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AiConfig::getIsDefault, 1);
        return this.count(wrapper);
    }

    @Override
    public Long countByConfigType(String configType) {
        LambdaQueryWrapper<AiConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AiConfig::getConfigType, configType);
        return this.count(wrapper);
    }

    @Override
    public Long countByProvider(String provider) {
        LambdaQueryWrapper<AiConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AiConfig::getProvider, provider);
        return this.count(wrapper);
    }

    /**
     * 将实体转换为响应对象
     */
    private AiConfigResponse convertToResponse(AiConfig aiConfig) {
        AiConfigResponse response = new AiConfigResponse();
        BeanUtils.copyProperties(aiConfig, response);
        
        // 格式化时间
        if (aiConfig.getCreateTime() != null) {
            response.setCreateTime(aiConfig.getCreateTime().format(DATE_TIME_FORMATTER));
        }
        if (aiConfig.getUpdateTime() != null) {
            response.setUpdateTime(aiConfig.getUpdateTime().format(DATE_TIME_FORMATTER));
        }
        
        // 管理端不需要脱敏，直接返回完整的API Token
        response.setApiToken(aiConfig.getApiToken());
        
        // 转换BigDecimal为Double
        if (aiConfig.getTemperature() != null) {
            response.setTemperature(aiConfig.getTemperature().doubleValue());
        }
        if (aiConfig.getTopP() != null) {
            response.setTopP(aiConfig.getTopP().doubleValue());
        }
        if (aiConfig.getInputPricePer1k() != null) {
            response.setInputPricePer1k(aiConfig.getInputPricePer1k().doubleValue());
        }
        if (aiConfig.getOutputPricePer1k() != null) {
            response.setOutputPricePer1k(aiConfig.getOutputPricePer1k().doubleValue());
        }
        
        return response;
    }

    /**
     * 根据字段名获取对应的Lambda表达式
     */
    private com.baomidou.mybatisplus.core.toolkit.support.SFunction<AiConfig, ?> getLambdaByField(String field) {
        switch (field) {
            case "configName":
                return AiConfig::getConfigName;
            case "configKey":
                return AiConfig::getConfigKey;
            case "configType":
                return AiConfig::getConfigType;
            case "provider":
                return AiConfig::getProvider;
            case "usageScenario":
                return AiConfig::getUsageScenario;
            case "priority":
                return AiConfig::getPriority;
            case "createTime":
                return AiConfig::getCreateTime;
            case "updateTime":
                return AiConfig::getUpdateTime;
            default:
                return AiConfig::getCreateTime;
        }
    }

    @Override
    public AiConfigResponse updateFromTestRequest(AiConfigTestUpdateRequest request) {
        // 查询现有配置
        AiConfig aiConfig = this.getById(request.getId());
        if (aiConfig == null) {
            return null;
        }

        // 更新字段
        if (StringUtils.hasText(request.getApiBaseUrl())) {
            aiConfig.setApiBaseUrl(request.getApiBaseUrl());
        }
        
        if (StringUtils.hasText(request.getApiToken())) {
            aiConfig.setApiToken(request.getApiToken());
        }
        
        if (StringUtils.hasText(request.getClientId())) {
            aiConfig.setClientId(request.getClientId());
        }
        
        if (StringUtils.hasText(request.getClientSecret())) {
            aiConfig.setClientSecret(request.getClientSecret());
        }
        
        if (StringUtils.hasText(request.getGrantType())) {
            aiConfig.setGrantType(request.getGrantType());
        }
        
        if (StringUtils.hasText(request.getBotId())) {
            aiConfig.setBotId(request.getBotId());
        }
        
        if (StringUtils.hasText(request.getWorkflowId())) {
            aiConfig.setWorkflowId(request.getWorkflowId());
        }
        
        if (StringUtils.hasText(request.getCustomHeaders())) {
            aiConfig.setCustomHeaders(request.getCustomHeaders());
        }
        
        if (StringUtils.hasText(request.getCustomParams())) {
            aiConfig.setCustomParams(request.getCustomParams());
        }
        
        if (request.getSupportStream() != null) {
            aiConfig.setSupportStream(request.getSupportStream());
        }

        // 保存更新
        this.updateById(aiConfig);

        // 返回响应对象
        return convertToResponse(aiConfig);
    }
}
