package me.zhengjie.modules.quartz.task;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Joiner;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.dm.announce.domain.DmAnnounce;
import me.zhengjie.modules.dm.announce.repository.DmAnnounceRepository;
import me.zhengjie.modules.dm.messageSendLog.domain.DmMessageSendLog;
import me.zhengjie.modules.dm.messageSendLog.service.DmMessageSendLogService;
import me.zhengjie.modules.dm.messageSendLog.util.SendMessageUtils;
import me.zhengjie.modules.system.repository.UserRepository;
import me.zhengjie.modules.system.service.UserService;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.List;

/**
 * 发送系统公告信息
 * @author Sky
 */
@Slf4j
@RequiredArgsConstructor
@Component
public class AnnounceTask {

    private final DmAnnounceRepository dmAnnounceRepository;
    private final DmMessageSendLogService dmMessageSendLogService;
    private final UserRepository userRepository;
    private final UserService userService;

    public void run(){
        log.info("timingSendAnnounce 执行开始");
        timingSendAnnounce();
        log.info("timingSendAnnounce 执行结束");
    }

    public void timingSendAnnounce(){
        //根据当前时间，获取当前时间之前未发送未取消的数据
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<DmAnnounce> dmAnnounceList = dmAnnounceRepository.findNotSendAnnounce(simpleDateFormat.format(System.currentTimeMillis()));
        for(DmAnnounce dmAnnounce : dmAnnounceList){
            DmMessageSendLog dmMessageSendLog = new DmMessageSendLog();
            dmMessageSendLog.setSystemName("中控平台");
            dmMessageSendLog.setSendId("dm_announce|id|"+dmAnnounce.getId());
            dmMessageSendLog.setSendUserId(userService.findByName(dmAnnounce.getCreateBy()).getId());
            JSONObject sendContentJSON = new JSONObject();
            sendContentJSON.put("text",dmAnnounce.getAnnounceContent());
            dmMessageSendLog.setSendContent(sendContentJSON);
            dmMessageSendLog.setUsernames(Joiner.on(",").join(userRepository.getAllUsername()));
            dmMessageSendLog.setCreateTime(simpleDateFormat.format(System.currentTimeMillis()));
            Boolean isSuccess = SendMessageUtils.sendChatMessage(dmMessageSendLog);
            if(isSuccess){
                dmMessageSendLogService.create(dmMessageSendLog);
                dmAnnounce.setSendState(1l);
                dmAnnounceRepository.save(dmAnnounce);
            }
        }
    }
}
