package com.brilliance.isc.esb.executors;

import com.brilliance.isc.esb.ITaskRegister;
import com.brilliance.isc.esb.newmodel.tasks.Task;
import com.brilliance.isc.mda.dao.ExtorMapper;
import com.brilliance.isc.mda.dao.TaskMapper;
import com.brilliance.isc.utils.DateUtils;
import com.brilliance.isc.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
public abstract class TaskExecutor {

    @Resource
    private TaskMapper taskMapper;
    @Resource
    private ExtorMapper extorMapper;

    public void execute(String tasktyp) {
        log.info("############当前执行任务类型为 {}", tasktyp);
        List<Task> tasklist = taskMapper.selectByType(tasktyp);
        if (CollectionUtils.isEmpty(tasklist)) {
            log.info("############当前任务类型{}列表没有待执行的任务", tasktyp);
        }
        for (Task task : tasklist) {
            try {
                task.setBegintim(DateUtils.dateTimeNow());
                doExecute(task);
                updateTaskSta(task);
            } catch (Exception ex) {
                log.info("############当前任务{}执行异常", task.getInr(), ex);
                dealexception(task,ex==null?"发生空指针":ex.getMessage());
            }
            taskMapper.updateByPrimaryKey(task);
        }
    }

    abstract protected void doExecute(Task task);

    protected void dealexception(Task task,String errormsg) {
        task.setSta("E");
        task.setTaskinfo(StringUtils.stringAppend(ITaskRegister.ERROR,errormsg));
    }
    public void updateTaskSta(Task task){
        task.setEndtim(DateUtils.dateTimeNow());
        task.setSta("S");
        task.setTaskinfo(ITaskRegister.SUCCESS);
    }
}
