package org.xyzh.crontab.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.xyzh.api.crontab.EmailRecipientService;
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.core.page.PageRequest;
import org.xyzh.common.dto.crontab.TbCrontabEmailRecipient;
import org.xyzh.common.utils.IDUtils;
import org.xyzh.crontab.mapper.EmailRecipientMapper;

import java.util.Date;
import java.util.List;

/**
 * @description 定时任务邮件接收人服务实现类
 * @filename EmailRecipientServiceImpl.java
 * @author yslg
 * @copyright xyzh
 * @since 2025-11-18
 */
@Service
public class EmailRecipientServiceImpl implements EmailRecipientService {

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

    @Autowired
    private EmailRecipientMapper emailRecipientMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultDomain<TbCrontabEmailRecipient> createRecipient(TbCrontabEmailRecipient recipient) {
        ResultDomain<TbCrontabEmailRecipient> resultDomain = new ResultDomain<>();
        try {
            // 生成ID
            recipient.setID(IDUtils.generateID());
            if (recipient.getRecipientId() == null || recipient.getRecipientId().isEmpty()) {
                recipient.setRecipientId(IDUtils.generateID());
            }
            recipient.setCreateTime(new Date());
            recipient.setDeleted(false);

            int count = emailRecipientMapper.insertRecipient(recipient);
            if (count > 0) {
                resultDomain.success("创建邮件接收人成功", recipient);
            } else {
                resultDomain.fail("创建邮件接收人失败");
            }
        } catch (Exception e) {
            logger.error("创建邮件接收人异常: {}", e.getMessage(), e);
            resultDomain.fail("创建邮件接收人失败: " + e.getMessage());
        }
        return resultDomain;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultDomain<Boolean> batchCreateRecipient(List<TbCrontabEmailRecipient> recipients) {
        ResultDomain<Boolean> resultDomain = new ResultDomain<>();
        try {
            for (TbCrontabEmailRecipient recipient : recipients) {
                recipient.setID(IDUtils.generateID());
                if (recipient.getRecipientId() == null || recipient.getRecipientId().isEmpty()) {
                    recipient.setRecipientId(IDUtils.generateID());
                }
                recipient.setCreateTime(new Date());
                recipient.setDeleted(false);
            }

            int count = emailRecipientMapper.batchInsertRecipient(recipients);
            if (count > 0) {
                resultDomain.setSuccess(true);
                resultDomain.setMessage("批量创建邮件接收人成功");
            } else {
                resultDomain.fail("批量创建邮件接收人失败");
            }
        } catch (Exception e) {
            logger.error("批量创建邮件接收人异常: {}", e.getMessage(), e);
            resultDomain.fail("批量创建邮件接收人失败: " + e.getMessage());
        }
        return resultDomain;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultDomain<TbCrontabEmailRecipient> updateRecipient(TbCrontabEmailRecipient recipient) {
        ResultDomain<TbCrontabEmailRecipient> resultDomain = new ResultDomain<>();
        try {
            recipient.setUpdateTime(new Date());
            int count = emailRecipientMapper.updateRecipient(recipient);
            if (count > 0) {
                resultDomain.success("更新邮件接收人成功", recipient);
            } else {
                resultDomain.fail("更新邮件接收人失败");
            }
        } catch (Exception e) {
            logger.error("更新邮件接收人异常: {}", e.getMessage(), e);
            resultDomain.fail("更新邮件接收人失败: " + e.getMessage());
        }
        return resultDomain;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultDomain<Boolean> deleteRecipient(String recipientId) {
        ResultDomain<Boolean> resultDomain = new ResultDomain<>();
        try {
            int count = emailRecipientMapper.deleteRecipient(recipientId);
            if (count > 0) {
                resultDomain.success("删除邮件接收人成功", true);
            } else {
                resultDomain.fail("删除邮件接收人失败");
            }
        } catch (Exception e) {
            logger.error("删除邮件接收人异常: {}", e.getMessage(), e);
            resultDomain.fail("删除邮件接收人失败: " + e.getMessage());
        }
        return resultDomain;
    }

    @Override
    public ResultDomain<TbCrontabEmailRecipient> getRecipientById(String recipientId) {
        ResultDomain<TbCrontabEmailRecipient> resultDomain = new ResultDomain<>();
        try {
            TbCrontabEmailRecipient recipient = emailRecipientMapper.selectRecipientById(recipientId);
            if (recipient != null) {
                resultDomain.success("查询邮件接收人成功", recipient);
            } else {
                resultDomain.fail("邮件接收人不存在");
            }
        } catch (Exception e) {
            logger.error("查询邮件接收人异常: {}", e.getMessage(), e);
            resultDomain.fail("查询邮件接收人失败: " + e.getMessage());
        }
        return resultDomain;
    }

    @Override
    public ResultDomain<TbCrontabEmailRecipient> getRecipientsByTaskId(String taskId) {
        ResultDomain<TbCrontabEmailRecipient> resultDomain = new ResultDomain<>();
        try {
            List<TbCrontabEmailRecipient> list = emailRecipientMapper.selectRecipientsByTaskId(taskId);
            resultDomain.success("查询邮件接收人列表成功", list);
        } catch (Exception e) {
            logger.error("查询邮件接收人列表异常: {}", e.getMessage(), e);
            resultDomain.fail("查询邮件接收人列表失败: " + e.getMessage());
        }
        return resultDomain;
    }

    @Override
    public ResultDomain<TbCrontabEmailRecipient> getRecipientPage(PageRequest<TbCrontabEmailRecipient> request) {
        ResultDomain<TbCrontabEmailRecipient> resultDomain = new ResultDomain<>();
        try {
            PageParam pageParam = request.getPageParam();
            List<TbCrontabEmailRecipient> list = emailRecipientMapper.selectRecipientPage(request.getFilter(), pageParam);
            int total = emailRecipientMapper.countSelectRecipient(request.getFilter());
            
            PageDomain<TbCrontabEmailRecipient> pageDomain = new PageDomain<>();
            pageDomain.setPageParam(pageParam);
            pageParam.setTotalElements(total);
            pageDomain.setDataList(list);
            
            resultDomain.success("分页查询邮件接收人成功", pageDomain);
        } catch (Exception e) {
            logger.error("分页查询邮件接收人异常: {}", e.getMessage(), e);
            resultDomain.fail("分页查询邮件接收人失败: " + e.getMessage());
        }
        return resultDomain;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultDomain<Boolean> deleteRecipientsByTaskId(String taskId) {
        ResultDomain<Boolean> resultDomain = new ResultDomain<>();
        try {
            int count = emailRecipientMapper.deleteRecipientsByTaskId(taskId);
            resultDomain.success("删除任务的所有接收人成功，共" + count + "条", true);
        } catch (Exception e) {
            logger.error("删除任务的所有接收人异常: {}", e.getMessage(), e);
            resultDomain.fail("删除任务的所有接收人失败: " + e.getMessage());
        }
        return resultDomain;
    }
}
