package com.ms.biz.task;

import com.ms.biz.common.TaskBaseService;
import com.ms.biz.service.DoudianMsgService;
import com.ms.dal.entity.DoudianMsgParseQueue;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.Executor;

@Configuration
@Component
@Slf4j
public class DoudianMsgParseTaskService extends TaskBaseService {

    @Autowired
    private DoudianMsgService doudianMsgService;

    /**
     * 同时开启任务处理数量
     */
    public int getCorePoolSiz() {
        return 5;
    }

    /**
     * 任务管理器名称
     */
    public String getTaskExecutorName() {
        return "doudianMsgParseTaskPool";
    }

    @Bean(name = "doudianMsgParseTaskPool")
    @Override
    public Executor getAsyncExecutor() {
        return super.getAsyncExecutor();
    }

    @Resource(name = "doudianMsgParseTaskPool")
    protected Executor taskPool;

    @Override
    protected Executor getTaskPool() {
        return taskPool;
    }

    @Async("doudianMsgParseTaskPool")
    @Override
    public void runTask() {
        super.runTask();
    }

    @Override
    public Object getTask() {
        DoudianMsgParseQueue queue = doudianMsgService.lockDoudianMsgParseQueue();
        return queue;
    }

    /**
     * 处理任务
     *
     * @param params
     * @return
     */
    @Override
    public Object processTask(Object params) {
        if (params == null) {
            return null;
        }
        DoudianMsgParseQueue queue = (DoudianMsgParseQueue) params;
        Long doudianMsgId = queue.getDoudianMsgId();

        boolean isSuccess = false;
        try {
            isSuccess = doudianMsgService.processDoudianMsgParseQueue(doudianMsgId);
        } catch (Exception e) {
            log.error("ParseDoudianMsgTask processTask exception: ", e);
            doudianMsgService.failProcessDoudianMsgParseQueue(doudianMsgId);
        }

        if (isSuccess) {
            return queue.getDoudianMsgParseQueueId();
        } else {
            return null;
        }

    }

    /**
     * 清理任务
     *
     * @param params
     */
    @Override
    public void clearTask(Object params) {
        if (params == null) {
            return;
        }
        Long queueId = (Long)params;
        doudianMsgService.deleteDoudianMsgParseQueue(queueId);
    }
}
