package org.xyzh.system.service.impl;

import org.apache.dubbo.config.annotation.DubboService;
import org.xyzh.api.system.service.SysConfigService;
import org.xyzh.api.system.vo.SysConfigVO;
import org.xyzh.common.core.domain.ResultDomain;
import org.xyzh.common.core.page.PageRequest;
import org.xyzh.common.dto.sys.TbSysConfigDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jakarta.annotation.Resource;
import java.util.Date;
import java.util.Collections;
import java.util.List;
import org.xyzh.common.core.page.PageParam;
import org.xyzh.common.core.page.PageDomain;

import org.xyzh.common.utils.id.IdUtil;
import org.xyzh.common.utils.StringUtils;
import org.xyzh.system.mapper.config.TbSysConfigMapper;

/**
 * @description    系统配置服务实现类
 * @filename    SysConfigServiceImpl.java
 */
@DubboService(
    version = "1.0.0",
    group = "system",
    timeout = 3000,
    retries = 0
)
public class SysConfigServiceImpl implements SysConfigService {

    private static final Logger logger = LoggerFactory.getLogger(SysConfigServiceImpl.class);

    private static final String MSG_CONFIG_PARAM_REQUIRED = "配置参数不能为空";
    private static final String MSG_CONFIG_ID_REQUIRED = "配置ID不能为空";
    private static final String MSG_QUERY_PARAM_REQUIRED = "查询条件不能为空";
    private static final String MSG_PAGE_PARAM_REQUIRED = "分页参数不能为空";

    @Resource
    private TbSysConfigMapper configMapper;

    /**
     * 根据key查询配置
     */
    private TbSysConfigDTO getConfigByKey(String key) {
        if (key == null || key.isEmpty()) {
            return null;
        }
        return configMapper.selectSysConfigByKey(key);
    }
    
    public Object getSysConfig(String key) {
        try {
            TbSysConfigDTO config = getConfigByKey(key);
            if (config == null) {
                logger.warn("配置项不存在: {}", key);
                return null;
            }
            
            String configType = config.getConfigType();
            String configValue = config.getValue();
            
            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 {
            TbSysConfigDTO config = getConfigByKey(key);
            if (config == null) {
                logger.warn("配置项不存在: {}", key);
                return null;
            }
            return config.getValue();
        } catch (Exception e) {
            logger.error("获取字符串配置失败: {}", key, e);
            return null;
        }
    }
    
    @Override
    public Integer getIntConfig(String key) {
        try {
            TbSysConfigDTO config = getConfigByKey(key);
            if (config == null) {
                logger.warn("配置项不存在: {}", key);
                return null;
            }
            
            String value = config.getValue();
            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 {
            TbSysConfigDTO config = getConfigByKey(key);
            if (config == null) {
                logger.warn("配置项不存在: {}", key);
                return null;
            }
            
            String value = config.getValue();
            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 {
            TbSysConfigDTO config = getConfigByKey(key);
            if (config == null) {
                logger.warn("配置项不存在: {}", key);
                return null;
            }
            
            String value = config.getValue();
            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 {
            TbSysConfigDTO config = getConfigByKey(key);
            if (config == null) {
                logger.warn("配置项不存在: {}", key);
                return null;
            }
            
            String value = config.getValue();
            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<TbSysConfigDTO> insertConfig(TbSysConfigDTO configDTO) {
        if (configDTO == null) {
            return ResultDomain.failure(MSG_CONFIG_PARAM_REQUIRED);
        }
        if (StringUtils.isBlank(configDTO.getConfigId())) {
            configDTO.setConfigId(IdUtil.generateID());
        }
        if (configDTO.getCreateTime() == null) {
            configDTO.setCreateTime(new Date());
        }
        if (configDTO.getDeleted() == null) {
            configDTO.setDeleted(false);
        }
        int rows = configMapper.insertConfig(configDTO);
        if (rows > 0) {
            logger.info("新增配置成功, configId={}", configDTO.getConfigId());
            return ResultDomain.success("新增配置成功", configDTO);
        }
        logger.warn("新增配置失败, configId={}", configDTO.getConfigId());
        return ResultDomain.failure("新增配置失败");
    }

    @Override
    public ResultDomain<TbSysConfigDTO> updateConfig(TbSysConfigDTO configDTO) {
        if (configDTO == null || StringUtils.isBlank(configDTO.getConfigId())) {
            return ResultDomain.failure(MSG_CONFIG_ID_REQUIRED);
        }
        configDTO.setUpdateTime(new Date());
        int rows = configMapper.updateConfig(configDTO);
        if (rows > 0) {
            logger.info("更新配置成功, configId={}", configDTO.getConfigId());
            return ResultDomain.success("更新配置成功", configDTO);
        }
        logger.warn("更新配置失败, configId={}", configDTO.getConfigId());
        return ResultDomain.failure("更新配置失败");
    }

    @Override
    public ResultDomain<Boolean> deleteConfig(TbSysConfigDTO configDTO) {
        if (configDTO == null || StringUtils.isBlank(configDTO.getConfigId())) {
            return ResultDomain.failure(MSG_CONFIG_ID_REQUIRED);
        }
        int rows = configMapper.deleteConfig(configDTO);
        if (rows > 0) {
            logger.info("删除配置成功, configId={}", configDTO.getConfigId());
            return ResultDomain.success("删除配置成功", Boolean.TRUE);
        }
        logger.warn("删除配置失败, configId={}", configDTO.getConfigId());
        return ResultDomain.failure("删除配置失败");
    }

    @Override
    public ResultDomain<SysConfigVO> getConfig(SysConfigVO filter) {
        TbSysConfigDTO dto = SysConfigVO.toDTO(filter);
        if (dto == null) {
            return ResultDomain.failure(MSG_QUERY_PARAM_REQUIRED);
        }
        List<SysConfigVO> list = configMapper.getConfigByFilter(dto);
        if (list == null || list.isEmpty()) {
            return ResultDomain.failure("未找到配置");
        }
        return ResultDomain.success("获取配置成功", list.get(0));
    }

    @Override
    public ResultDomain<SysConfigVO> getConfigList(SysConfigVO filter) {
        TbSysConfigDTO dto = SysConfigVO.toDTO(filter);
        List<SysConfigVO> list = configMapper.getConfigByFilter(dto);
        if (list == null) {
            list = Collections.emptyList();
        }
        return ResultDomain.success("获取配置列表成功", list);
    }

    @Override
    public ResultDomain<SysConfigVO> getConfigPage(PageRequest<SysConfigVO> pageRequest) {
        if (pageRequest == null) {
            return ResultDomain.failure(MSG_PAGE_PARAM_REQUIRED);
        }
        PageParam pageParam = pageRequest.getPageParam();
        TbSysConfigDTO filter = SysConfigVO.toDTO(pageRequest.getFilter());
        int total = configMapper.getConfigCount(filter);
        pageParam.setTotal(total);
        pageParam.setTotalPages(pageParam.getPageSize() == 0 ? 0 : (int) Math.ceil((double) total / pageParam.getPageSize()));
        List<SysConfigVO> data = configMapper.getConfigPageByFilter(filter, pageParam);
        if (data == null) {
            data = Collections.emptyList();
        }
        PageDomain<SysConfigVO> pageDomain = new PageDomain<>(pageParam, data);
        return ResultDomain.success("分页查询配置成功", pageDomain);
    }

    @Override
    public ResultDomain<String> getConfigValueByKey(String key) {
        if (StringUtils.isBlank(key)) {
            return ResultDomain.failure("配置键不能为空");
        }
        TbSysConfigDTO filter = new TbSysConfigDTO();
        filter.setKey(key);
        List<SysConfigVO> list = configMapper.getConfigByFilter(filter);
        if (list == null || list.isEmpty()) {
            return ResultDomain.failure("未找到配置");
        }
        String value = list.get(0).getValue();
        return ResultDomain.success("获取配置值成功", value);
    }

    @Override
    public ResultDomain<SysConfigVO> getConfigListByModuleId(String moduleId) {
        if (StringUtils.isBlank(moduleId)) {
            return ResultDomain.failure("模块ID不能为空");
        }
        TbSysConfigDTO filter = new TbSysConfigDTO();
        filter.setModuleId(moduleId);
        List<SysConfigVO> list = configMapper.getConfigByFilter(filter);
        if (list == null) {
            list = Collections.emptyList();
        }
        return ResultDomain.success("根据模块ID获取配置列表成功", list);
    }

    
}

