package org.xyzh.system.service.config.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.xyzh.api.system.config.SysConfigService;
import org.xyzh.common.core.domain.ResultDomain;
import org.xyzh.common.core.page.PageDomain;
import org.xyzh.common.core.page.PageParam;
import org.xyzh.common.dto.system.TbSysConfig;
import org.xyzh.system.mapper.SysConfigMapper;

import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @description 系统配置服务实现
 * @author AI Assistant
 * @since 2025-11-18
 */
@Service
public class SysConfigServiceImpl implements SysConfigService {
    
    private static final Logger logger = LoggerFactory.getLogger(SysConfigServiceImpl.class);
    
    @Autowired
    private SysConfigMapper sysConfigMapper;
    
    /**
     * 根据key查询配置
     */
    private TbSysConfig getConfigByKey(String key) {
        if (key == null || key.isEmpty()) {
            return null;
        }
        return sysConfigMapper.selectSysConfigByKey(key);
    }
    
    @Override
    public Object getSysConfig(String key) {
        try {
            TbSysConfig config = getConfigByKey(key);
            if (config == null) {
                logger.warn("配置项不存在: {}", key);
                return null;
            }
            
            String configType = config.getConfigType();
            String configValue = config.getConfigValue();
            
            if (configValue == null || configValue.isEmpty()) {
                return null;
            }
            
            // 根据config_type返回对应的类型
            if (configType == null || "string".equalsIgnoreCase(configType)) {
                return configValue;
            } else if ("number".equalsIgnoreCase(configType) || "integer".equalsIgnoreCase(configType)) {
                try {
                    // 尝试解析为Integer，如果失败则解析为Long
                    return Integer.parseInt(configValue);
                } catch (NumberFormatException e) {
                    try {
                        return Long.parseLong(configValue);
                    } catch (NumberFormatException ex) {
                        logger.error("配置项 {} 的值无法转换为数字: {}", key, configValue);
                        return configValue;
                    }
                }
            } else if ("boolean".equalsIgnoreCase(configType)) {
                String value = configValue.toLowerCase().trim();
                if ("true".equals(value) || "1".equals(value) || "yes".equals(value) || "on".equals(value)) {
                    return true;
                } else if ("false".equals(value) || "0".equals(value) || "no".equals(value) || "off".equals(value)) {
                    return false;
                } else {
                    logger.warn("配置项 {} 的值无法识别为Boolean: {}", key, value);
                    return configValue;
                }
            } else if ("double".equalsIgnoreCase(configType) || "float".equalsIgnoreCase(configType)) {
                try {
                    return Double.parseDouble(configValue);
                } catch (NumberFormatException e) {
                    logger.error("配置项 {} 的值无法转换为Double: {}", key, configValue);
                    return configValue;
                }
            } else {
                // 未知类型，直接返回字符串
                return configValue;
            }
        } catch (Exception e) {
            logger.error("获取配置失败: {}", key, e);
            return null;
        }
    }
    
    @Override
    public String getStringConfig(String key) {
        try {
            TbSysConfig config = getConfigByKey(key);
            if (config == null) {
                logger.warn("配置项不存在: {}", key);
                return null;
            }
            return config.getConfigValue();
        } catch (Exception e) {
            logger.error("获取字符串配置失败: {}", key, e);
            return null;
        }
    }
    
    @Override
    public Integer getIntConfig(String key) {
        try {
            TbSysConfig config = getConfigByKey(key);
            if (config == null) {
                logger.warn("配置项不存在: {}", key);
                return null;
            }
            
            String value = config.getConfigValue();
            if (value == null || value.isEmpty()) {
                return null;
            }
            
            return Integer.parseInt(value);
        } catch (NumberFormatException e) {
            logger.error("配置项 {} 的值无法转换为Integer: {}", key, e.getMessage());
            return null;
        } catch (Exception e) {
            logger.error("获取Integer配置失败: {}", key, e);
            return null;
        }
    }
    
    @Override
    public Boolean getBooleanConfig(String key) {
        try {
            TbSysConfig config = getConfigByKey(key);
            if (config == null) {
                logger.warn("配置项不存在: {}", key);
                return null;
            }
            
            String value = config.getConfigValue();
            if (value == null || value.isEmpty()) {
                return null;
            }
            
            // 支持多种布尔值表示：true/false, 1/0, yes/no, on/off
            value = value.toLowerCase().trim();
            if ("true".equals(value) || "1".equals(value) || "yes".equals(value) || "on".equals(value)) {
                return true;
            } else if ("false".equals(value) || "0".equals(value) || "no".equals(value) || "off".equals(value)) {
                return false;
            } else {
                logger.warn("配置项 {} 的值无法识别为Boolean: {}", key, value);
                return null;
            }
        } catch (Exception e) {
            logger.error("获取Boolean配置失败: {}", key, e);
            return null;
        }
    }
    
    @Override
    public Double getDoubleConfig(String key) {
        try {
            TbSysConfig config = getConfigByKey(key);
            if (config == null) {
                logger.warn("配置项不存在: {}", key);
                return null;
            }
            
            String value = config.getConfigValue();
            if (value == null || value.isEmpty()) {
                return null;
            }
            
            return Double.parseDouble(value);
        } catch (NumberFormatException e) {
            logger.error("配置项 {} 的值无法转换为Double: {}", key, e.getMessage());
            return null;
        } catch (Exception e) {
            logger.error("获取Double配置失败: {}", key, e);
            return null;
        }
    }
    
    @Override
    public Long getLongConfig(String key) {
        try {
            TbSysConfig config = getConfigByKey(key);
            if (config == null) {
                logger.warn("配置项不存在: {}", key);
                return null;
            }
            
            String value = config.getConfigValue();
            if (value == null || value.isEmpty()) {
                return null;
            }
            
            return Long.parseLong(value);
        } catch (NumberFormatException e) {
            logger.error("配置项 {} 的值无法转换为Long: {}", key, e.getMessage());
            return null;
        } catch (Exception e) {
            logger.error("获取Long配置失败: {}", key, e);
            return null;
        }
    }
    
    // ==================== 配置管理接口实现 ====================
    
    @Override
    public ResultDomain<TbSysConfig> getAllConfigs() {
        ResultDomain<TbSysConfig> resultDomain = new ResultDomain<>();
        try {
            List<TbSysConfig> configs = sysConfigMapper.selectAllSysConfig();
            resultDomain.success("查询成功", configs);
            return resultDomain;
        } catch (Exception e) {
            logger.error("获取所有配置失败", e);
            resultDomain.fail("获取配置失败: " + e.getMessage());
            return resultDomain;
        }
    }
    
    @Override
    public ResultDomain<TbSysConfig> getConfigsByGroup(String groupKey) {
        ResultDomain<TbSysConfig> resultDomain = new ResultDomain<>();
        try {
            List<TbSysConfig> configs = sysConfigMapper.selectSysConfigByGroup(groupKey);
            resultDomain.success("查询成功", configs);
            return resultDomain;
        } catch (Exception e) {
            logger.error("根据分组获取配置失败: {}", groupKey, e);
            resultDomain.fail("获取配置失败: " + e.getMessage());
            return resultDomain;
        }
    }
    
    @Override
    public ResultDomain<Boolean> batchSaveConfigs(List<Map<String, String>> configs) {
        ResultDomain<Boolean> resultDomain = new ResultDomain<>();
        try {
            for (Map<String, String> configMap : configs) {
                String configKey = configMap.get("configKey");
                String configValue = configMap.get("configValue");
                
                TbSysConfig existingConfig = sysConfigMapper.selectSysConfigByKey(configKey);
                if (existingConfig != null) {
                    existingConfig.setConfigValue(configValue);
                    sysConfigMapper.updateSysConfig(existingConfig);
                } else {
                    logger.warn("配置项不存在，跳过: {}", configKey);
                }
            }
            resultDomain.success("保存成功", true);
            return resultDomain;
        } catch (Exception e) {
            logger.error("批量保存配置失败", e);
            resultDomain.fail("保存配置失败: " + e.getMessage());
            return resultDomain;
        }
    }
    
    @Override
    public ResultDomain<Boolean> createConfig(TbSysConfig config) {
        ResultDomain<Boolean> resultDomain = new ResultDomain<>();
        try {
            TbSysConfig existingConfig = sysConfigMapper.selectSysConfigByKey(config.getConfigKey());
            if (existingConfig != null) {
                resultDomain.fail("配置键已存在: " + config.getConfigKey());
                return resultDomain;
            }
            
            if (config.getID() == null || config.getID().isEmpty()) {
                config.setID(UUID.randomUUID().toString());
            }
            
            int result = sysConfigMapper.insertSysConfig(config);
            if (result > 0) {
                resultDomain.success("创建成功", true);
                return resultDomain;
            } else {
                resultDomain.fail("创建配置失败");
                return resultDomain;
            }
        } catch (Exception e) {
            logger.error("创建配置失败", e);
            resultDomain.fail("创建配置失败: " + e.getMessage());
            return resultDomain;
        }
    }
    
    @Override
    public ResultDomain<Boolean> updateConfig(TbSysConfig config) {
        ResultDomain<Boolean> resultDomain = new ResultDomain<>();
        try {
            int result = sysConfigMapper.updateSysConfig(config);
            if (result > 0) {
                resultDomain.success("更新成功", true);
                return resultDomain;
            } else {
                resultDomain.fail("更新配置失败");
                return resultDomain;
            }
        } catch (Exception e) {
            logger.error("更新配置失败", e);
            resultDomain.fail("更新配置失败: " + e.getMessage());
            return resultDomain;
        }
    }
    
    @Override
    public ResultDomain<Boolean> deleteConfig(String id) {
        ResultDomain<Boolean> resultDomain = new ResultDomain<>();
        try {
            int result = sysConfigMapper.deleteSysConfig(id);
            if (result > 0) {
                resultDomain.success("删除成功", true);
                return resultDomain;
            } else {
                resultDomain.fail("删除配置失败");
                return resultDomain;
            }
        } catch (Exception e) {
            logger.error("删除配置失败: {}", id, e);
            resultDomain.fail("删除配置失败: " + e.getMessage());
            return resultDomain;
        }
    }
    
    @Override
    public ResultDomain<TbSysConfig> getConfigPage(TbSysConfig filter, PageParam pageParam) {
        ResultDomain<TbSysConfig> resultDomain = new ResultDomain<>();
        try {
            int total = sysConfigMapper.countSelectSysConfig(filter);
            List<TbSysConfig> configs = sysConfigMapper.selectSysConfigPage(filter, pageParam);
            pageParam.setTotalElements(total);
            pageParam.setTotalPages((int) Math.ceil((double) total / pageParam.getPageSize()));
            PageDomain<TbSysConfig> pageDomain = new PageDomain<>(pageParam,configs);
            resultDomain.success("查询成功", pageDomain);
            return resultDomain;
        } catch (Exception e) {
            logger.error("分页查询配置失败", e);
            resultDomain.fail("查询配置失败: " + e.getMessage());
            return resultDomain;
        }
    }
    
    @Override
    public ResultDomain<TbSysConfig> getConfigById(String id) {
        ResultDomain<TbSysConfig> resultDomain = new ResultDomain<>();
        try {
            TbSysConfig config = sysConfigMapper.selectSysConfigById(id);
            if (config != null) {
                resultDomain.success("查询成功", config);
                return resultDomain;
            } else {
                resultDomain.fail("配置不存在");
                return resultDomain;
            }
        } catch (Exception e) {
            logger.error("根据ID获取配置失败: {}", id, e);
            resultDomain.fail("获取配置失败: " + e.getMessage());
            return resultDomain;
        }
    }
}
