package com.yushu.system.service.impl;

import com.yushu.common.utils.DateUtils;
import com.yushu.system.domain.SysMailConfig;
import com.yushu.system.mapper.SysMailConfigMapper;
import com.yushu.system.service.ISysMailConfigService;
import com.yushu.system.service.ISysMailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 企业邮箱配置Service业务层处理
 * 
 * @author yushu
 * @date 2024-12-13
 */
@Service
public class SysMailConfigServiceImpl implements ISysMailConfigService {

    @Autowired
    private SysMailConfigMapper sysMailConfigMapper;

    @Autowired
    private ISysMailService sysMailService;

    @Override
    public SysMailConfig selectSysMailConfigByConfigId(Long configId) {
        return sysMailConfigMapper.selectSysMailConfigByConfigId(configId);
    }

    @Override
    public List<SysMailConfig> selectSysMailConfigList(SysMailConfig sysMailConfig) {
        return sysMailConfigMapper.selectSysMailConfigList(sysMailConfig);
    }

    @Override
    public List<SysMailConfig> selectEnabledConfigList() {
        return sysMailConfigMapper.selectEnabledConfigList();
    }

    @Override
    public SysMailConfig selectDefaultConfig() {
        return sysMailConfigMapper.selectDefaultConfig();
    }

    @Override
    @Transactional
    public int insertSysMailConfig(SysMailConfig sysMailConfig) {
        sysMailConfig.setCreateTime(DateUtils.getNowDate());
        // 如果设置为默认，先重置其他默认配置
        if ("1".equals(sysMailConfig.getIsDefault())) {
            sysMailConfigMapper.resetDefaultConfig();
        }
        return sysMailConfigMapper.insertSysMailConfig(sysMailConfig);
    }

    @Override
    @Transactional
    public int updateSysMailConfig(SysMailConfig sysMailConfig) {
        sysMailConfig.setUpdateTime(DateUtils.getNowDate());
        // 如果设置为默认，先重置其他默认配置
        if ("1".equals(sysMailConfig.getIsDefault())) {
            sysMailConfigMapper.resetDefaultConfig();
        }
        return sysMailConfigMapper.updateSysMailConfig(sysMailConfig);
    }

    @Override
    public int deleteSysMailConfigByConfigIds(Long[] configIds) {
        return sysMailConfigMapper.deleteSysMailConfigByConfigIds(configIds);
    }

    @Override
    public int deleteSysMailConfigByConfigId(Long configId) {
        return sysMailConfigMapper.deleteSysMailConfigByConfigId(configId);
    }

    @Override
    public boolean testConnection(Long configId, String testEmail) {
        try {
            return sysMailService.sendMail(configId, testEmail, "邮件配置测试", 
                "这是一封测试邮件，用于验证邮箱配置是否正确。\n\n发送时间：" + DateUtils.getTime(), false);
        } catch (Exception e) {
            return false;
        }
    }
}
