package com.ktg.iscs.service.impl;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ktg.common.core.domain.entity.SysUser;
import com.ktg.iscs.domain.IsMailSendTaskItem;
import com.ktg.iscs.domain.IsMailTemplate;
import com.ktg.iscs.mapper.IsMailSendTaskItemMapper;
import com.ktg.iscs.service.IIsMailSendTaskItemService;
import com.ktg.iscs.service.IIsMailTemplateService;
import com.ktg.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;

/**
 * 系统邮件任务Service业务层处理
 *
 * @author cgj
 * @date 2025-01-16
 */
@Service
public class IsMailSendTaskItemServiceImpl extends ServiceImpl<IsMailSendTaskItemMapper, IsMailSendTaskItem> implements IIsMailSendTaskItemService {

    @Autowired
    private IsMailSendTaskItemMapper isMailSendTaskItemMapper;
    @Autowired
    private IIsMailTemplateService iIsMailTemplateService;
    @Autowired
    private ISysUserService iSysUserService;

    @Override
    public Page<IsMailSendTaskItem> getIsMailSendTaskItemPage(Page<IsMailSendTaskItem> page, IsMailSendTaskItem isMailSendTaskItem) {
        Page<IsMailSendTaskItem> result = page(page, Wrappers.<IsMailSendTaskItem>lambdaQuery()
                .orderByDesc(IsMailSendTaskItem::getMailId));
        return result;
    }

    @Override
    public Boolean insertIsMailSendTaskItem(IsMailSendTaskItem taskItem, HashMap<String, String> map) {
        // 1.断言告警
        Assert.notNull(taskItem.getSendToUserId(), "收取用户不能为空");
        Assert.notNull(taskItem.getEmailTemplateId(), "邮件模板不能为空");
        Assert.notNull(taskItem.getScheduledSendTime(), "计划发送时间不能为空");
        SysUser user = iSysUserService.getById(taskItem.getSendToUserId());
        Assert.isFalse(user == null, "接收人不存在!");
        // 2.根据模板获取邮件内容
        IsMailTemplate template = iIsMailTemplateService.getById(taskItem.getEmailTemplateId());
        map.keySet().forEach(key -> {
            template.setTemplateTitle(template.getTemplateTitle().replace(key, map.get(key)));
            template.setTemplateContent(template.getTemplateContent().replace(key, map.get(key)));
        });
        taskItem.setTitle(template.getTemplateTitle());
        taskItem.setContent(template.getTemplateContent());
        save(taskItem);
        return true;
    }

}
