package com.lesingle.creation.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lesingle.creation.common.exception.BusinessException;
import com.lesingle.creation.dto.config.CreateConfigDTO;
import com.lesingle.creation.dto.config.UpdateConfigDTO;
import com.lesingle.creation.entity.SysConfig;
import com.lesingle.creation.mapper.SysConfigMapper;
import com.lesingle.creation.service.ConfigService;
import com.lesingle.creation.vo.config.ConfigDetailVO;
import com.lesingle.creation.vo.config.ConfigListVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 系统配置服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ConfigServiceImpl extends ServiceImpl<SysConfigMapper, SysConfig> implements ConfigService {

    private final SysConfigMapper sysConfigMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ConfigDetailVO create(CreateConfigDTO dto, Long tenantId, Long operatorId) {
        log.info("开始创建配置，配置键：{}", dto.getConfigKey());

        // 检查配置键是否已存在
        SysConfig existingConfig = sysConfigMapper.selectByKey(tenantId, dto.getConfigKey());
        if (existingConfig != null) {
            throw new BusinessException("配置键已存在");
        }

        // 创建配置
        SysConfig sysConfig = new SysConfig();
        sysConfig.setTenantId(tenantId);
        sysConfig.setConfigKey(dto.getConfigKey());
        sysConfig.setConfigValue(dto.getConfigValue());
        sysConfig.setConfigName(dto.getConfigName());
        sysConfig.setDescription(dto.getDescription());
        sysConfig.setValidState(1);
        sysConfig.setCreateBy(String.valueOf(operatorId));

        sysConfigMapper.insert(sysConfig);
        log.info("配置创建成功，配置 ID: {}", sysConfig.getId());

        return convertToDetailVO(sysConfig);
    }

    @Override
    public Page<ConfigListVO> pageList(Long tenantId, int page, int pageSize) {
        log.info("分页查询配置列表，租户 ID: {}, 页码：{}, 每页大小：{}", tenantId, page, pageSize);

        Page<SysConfig> configPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<SysConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysConfig::getTenantId, tenantId)
                .eq(SysConfig::getValidState, 1)
                .orderByDesc(SysConfig::getCreateTime);

        Page<SysConfig> resultPage = sysConfigMapper.selectPage(configPage, wrapper);

        // 转换为 VO
        List<ConfigListVO> voList = resultPage.getRecords().stream()
                .map(this::convertToListVO)
                .collect(Collectors.toList());

        Page<ConfigListVO> voPage = new Page<>(resultPage.getCurrent(), resultPage.getSize(), resultPage.getTotal());
        voPage.setRecords(voList);

        return voPage;
    }

    @Override
    public ConfigDetailVO getByKey(String key, Long tenantId) {
        log.info("根据键查询配置，键：{}, 租户 ID: {}", key, tenantId);

        SysConfig sysConfig = sysConfigMapper.selectByKey(tenantId, key);
        if (sysConfig == null) {
            throw new BusinessException("配置不存在");
        }

        return convertToDetailVO(sysConfig);
    }

    @Override
    public ConfigDetailVO detail(Long id, Long tenantId) {
        log.info("查询配置详情，配置 ID: {}", id);

        SysConfig sysConfig = sysConfigMapper.selectById(id);
        if (sysConfig == null) {
            throw new BusinessException("配置不存在");
        }

        return convertToDetailVO(sysConfig);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ConfigDetailVO update(Long id, UpdateConfigDTO dto, Long tenantId) {
        log.info("更新配置，配置 ID: {}", id);

        SysConfig existingConfig = sysConfigMapper.selectById(id);
        if (existingConfig == null) {
            throw new BusinessException("配置不存在");
        }

        // 更新配置信息
        SysConfig sysConfig = new SysConfig();
        sysConfig.setId(id);
        sysConfig.setConfigValue(dto.getConfigValue());
        sysConfig.setConfigName(dto.getConfigName());
        sysConfig.setDescription(dto.getDescription());

        sysConfigMapper.updateById(sysConfig);
        log.info("配置更新成功，配置 ID: {}", id);

        return convertToDetailVO(sysConfigMapper.selectById(id));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id, Long tenantId) {
        log.info("删除配置，配置 ID: {}", id);

        SysConfig sysConfig = sysConfigMapper.selectById(id);
        if (sysConfig == null) {
            throw new BusinessException("配置不存在");
        }

        // 删除配置（逻辑删除）
        sysConfigMapper.deleteById(id);
        log.info("配置删除成功，配置 ID: {}", id);
    }

    /**
     * 转换为详情 VO
     */
    private ConfigDetailVO convertToDetailVO(SysConfig sysConfig) {
        ConfigDetailVO vo = new ConfigDetailVO();
        vo.setId(sysConfig.getId());
        vo.setTenantId(sysConfig.getTenantId());
        vo.setConfigKey(sysConfig.getConfigKey());
        vo.setConfigValue(sysConfig.getConfigValue());
        vo.setConfigName(sysConfig.getConfigName());
        vo.setDescription(sysConfig.getDescription());
        vo.setValidState(sysConfig.getValidState());
        vo.setCreateBy(sysConfig.getCreateBy());
        vo.setCreateTime(sysConfig.getCreateTime());
        vo.setUpdateBy(sysConfig.getUpdateBy());
        vo.setUpdateTime(sysConfig.getUpdateTime());
        return vo;
    }

    /**
     * 转换为列表 VO
     */
    private ConfigListVO convertToListVO(SysConfig sysConfig) {
        ConfigListVO vo = new ConfigListVO();
        vo.setId(sysConfig.getId());
        vo.setTenantId(sysConfig.getTenantId());
        vo.setConfigKey(sysConfig.getConfigKey());
        vo.setConfigValue(sysConfig.getConfigValue());
        vo.setConfigName(sysConfig.getConfigName());
        vo.setDescription(sysConfig.getDescription());
        vo.setValidState(sysConfig.getValidState());
        vo.setCreateTime(sysConfig.getCreateTime());
        return vo;
    }
}
