package cn.com.ctop.check.component.execute;

import cn.com.ctop.check.entity.CtopCheckTaskExecuteLog;
import cn.com.ctop.check.entity.CtopCheckTaskList;
import cn.com.ctop.check.service.ICtopCheckTaskExecuteLogService;
import cn.com.ctop.notice.handler.SendWeChatHandle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Created by JQ.bi on 2020.8.18
 */
@Component
public class ScriptProcessLogExecutor {

    private final ICtopCheckTaskExecuteLogService checkTaskExecuteLogService;

    private final SendWeChatHandle sendWeChatHandle;

    @Autowired
    public ScriptProcessLogExecutor(ICtopCheckTaskExecuteLogService checkTaskExecuteLogService, SendWeChatHandle sendWeChatHandle) {
        this.checkTaskExecuteLogService = checkTaskExecuteLogService;
        this.sendWeChatHandle = sendWeChatHandle;
    }

     void insertLogExecute(CtopCheckTaskList checkTaskList, Long startDate, Long endDate) {
        boolean save = this.insertLog(checkTaskList.getId(), startDate, endDate, true, true);
        if (!save) {
            sendWeChat(checkTaskList.getMail());
        }
    }

     void insertLogExecute(CtopCheckTaskList checkTaskList, Long startDate, Long endDate, boolean exeState) {
        boolean save = this.insertLog(checkTaskList.getId(), startDate, endDate, exeState, true);
        if (!save) {
            sendWeChat(checkTaskList.getMail());
        }
    }

     void insertLogExecute(CtopCheckTaskList checkTaskList, Long startDate, Long endDate, boolean exeState, boolean notify) {
        boolean save = this.insertLog(checkTaskList.getId(), startDate, endDate, exeState, notify);
        if (!save) {
            sendWeChat(checkTaskList.getMail());
        }
    }

    private boolean insertLog(int taskId, Long startDate, Long endDate, boolean exeState, boolean notify) {
        CtopCheckTaskExecuteLog ctopCheckTaskExecuteLog = new CtopCheckTaskExecuteLog();
        ctopCheckTaskExecuteLog.setCheckTaskId(taskId);
        ctopCheckTaskExecuteLog.setStartDate(startDate);
        ctopCheckTaskExecuteLog.setEndDate(endDate);
        ctopCheckTaskExecuteLog.setExeResult(exeState);
        ctopCheckTaskExecuteLog.setNotifyState(notify);
        return checkTaskExecuteLogService.save(ctopCheckTaskExecuteLog);
    }

    private void sendWeChat(String mail) {
        sendWeChatHandle.sendWeChatByMail(mail, "检查数据服务日志处理失败");
    }
}
