package org.jeecg.modules.stm.utils;

import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.dto.message.MessageDTO;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.modules.message.entity.SysMessageTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class SendMessageUtil {
    private ISysBaseAPI sysBaseAPI;
    public SendMessageUtil(ISysBaseAPI sysBaseAPI) {
        this.sysBaseAPI = sysBaseAPI;
    }
    public SendMessageUtil() {
    }

    public Result<SysMessageTemplate> sendMessage(MessageParam param) {
        Result<SysMessageTemplate> result = new Result<SysMessageTemplate>();
        try {
            MessageDTO md = new MessageDTO();
            md.setToAll(false);
            md.setTitle(param.getMsgTitle());
            md.setTemplateCode(param.getTemplateCode());
            md.setToUser(param.getReceiver());
            md.setType("system");
            if(param.getSendUser()==null) {
                md.setFromUser("admin");
            } else {
                md.setFromUser(param.getSendUser());
            }
            Map<String,Object> data = new HashMap<>();
            data.put("ts_content",param.getContent());
            data.put("ts_date",getCurTimeStr());
            md.setData(data);
            sysBaseAPI.sendTemplateMessage(md);
            return result.success("消息发送成功！");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("发送消息出错", e.getMessage());
            return result.error500("发送消息出错！");
        }
    }

    private  String getCurTimeStr() {
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String curTime = now.format(formatter);
        return curTime;
    }

}



