package com.erp.print.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.erp.print.dto.request.PrintConfigRequest;
import com.erp.print.entity.PrintConfig;
import com.erp.print.exception.PrintException;
import com.erp.print.repository.PrintConfigRepository;
import com.erp.print.service.PrintConfigService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class PrintConfigServiceImpl implements PrintConfigService {

    private final PrintConfigRepository configRepository;

    @Override
    public List<PrintConfig> listConfigs() {
        return configRepository.selectList(null);
    }

    @Override
    public PrintConfig getConfigByKey(String configKey) {
        return configRepository.selectByConfigKey(configKey);
    }

    @Override
    @Transactional
    public PrintConfig createConfig(PrintConfigRequest request) {
        PrintConfig existing = configRepository.selectByConfigKey(request.getConfigKey());
        if (existing != null) {
            throw new PrintException("配置键已存在: " + request.getConfigKey());
        }

        PrintConfig config = new PrintConfig();
        BeanUtils.copyProperties(request, config);
        config.setStatus(request.getStatus() != null ? request.getStatus() : 1);
        configRepository.insert(config);
        log.info("创建打印配置: {}", request.getConfigKey());
        return config;
    }

    @Override
    @Transactional
    public PrintConfig updateConfig(PrintConfigRequest request) {
        PrintConfig config = configRepository.selectById(request.getId());
        if (config == null) {
            throw new PrintException("配置不存在: " + request.getId());
        }

        BeanUtils.copyProperties(request, config);
        configRepository.updateById(config);
        log.info("更新打印配置: {}", request.getConfigKey());
        return config;
    }

    @Override
    @Transactional
    public void deleteConfig(Long id) {
        configRepository.deleteById(id);
        log.info("删除打印配置: {}", id);
    }

    @Override
    public String getConfigValue(String configKey, String defaultValue) {
        PrintConfig config = configRepository.selectByConfigKey(configKey);
        return config != null ? config.getConfigValue() : defaultValue;
    }
}
