package com.ssj.service.task;

import com.ssj.framework.core.security.manager.TokenManager;
import com.ssj.framework.core.util.SystemResourceLocator;
import com.ssj.service.kmt.exercisesys.service.KmtExerciseSysService;
import com.ssj.taskthread.Task;
import com.ssj.taskthread.ThreadPool;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 异步刷新练习册加工状态和题目状态统计
 *
 * @author yrf
 * @date 2020/5/28 15:44
 */
public class SyncRefreshExerciseBookStatusTask extends Task {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private Integer triggerType;
    private List<String> selectedExerciseBookIdList;

    public SyncRefreshExerciseBookStatusTask(List<String> selectedExerciseBookIdList, Integer triggerType) {
        super();
        this.triggerType = triggerType;
        this.selectedExerciseBookIdList = selectedExerciseBookIdList;
    }

    @Override
    public void run() {
        KmtExerciseSysService kmtExerciseSysService = null;
        TokenManager tokenManager = null;
        String threadName = "";
        boolean success;
        int addLockTimeOut = 0;

        try {
            // 延迟三秒，防止数据的修改还未生效
            TimeUnit.SECONDS.sleep(3);
            threadName = Thread.currentThread().getName();

            logger.info("异步刷新练习册加工状态开始，selectedExerciseBookIdList={}", selectedExerciseBookIdList);

            kmtExerciseSysService = SystemResourceLocator.getBean(KmtExerciseSysService.class);
            tokenManager = SystemResourceLocator.getBean(TokenManager.class);
            int count = 0;
            while (addLockTimeOut < 60000) {
                success = tokenManager.addLock("book_status_lock", threadName, 60);
                if (success) {
                    logger.info("异步刷新练习册加工状态加锁成功");
                    count = kmtExerciseSysService.refreshBookStatus(selectedExerciseBookIdList);
                    break;
                }

                TimeUnit.MILLISECONDS.sleep(200);
                addLockTimeOut += 200;
            }

            logger.info("异步刷新练习册加工状态完成，更新{}条数据", count);
        } catch (Exception e) {
            logger.error("selectedExerciseBookIdList={}", selectedExerciseBookIdList);
            logger.error("异步刷新练习册加工状态异常", e);
        } finally {
            if (tokenManager != null) {
                tokenManager.unLock("book_status_lock", threadName);
            }
        }

        try {

            logger.info("异步刷新练习册题目状态统计开始，selectedExerciseBookIdList={}", selectedExerciseBookIdList);
            addLockTimeOut = 0;
            if (kmtExerciseSysService == null) {
                kmtExerciseSysService = SystemResourceLocator.getBean(KmtExerciseSysService.class);
            }
            if (tokenManager == null) {
                tokenManager = SystemResourceLocator.getBean(TokenManager.class);
            }
            if (StringUtils.isBlank(threadName)) {
                threadName = Thread.currentThread().getName();
            }
            int count = 0;
            while (addLockTimeOut < 60000) {
                success = tokenManager.addLock("book_count_lock", threadName, 60);
                if (success) {
                    logger.info("异步刷新练习册题目状态统计加锁成功");
                    count = kmtExerciseSysService.refreshExerciseBookCount(selectedExerciseBookIdList);
                    break;
                }

                TimeUnit.MILLISECONDS.sleep(200);
                addLockTimeOut += 200;
            }

            logger.info("异步刷新练习册题目状态统计完成，更新{}条数据", count);
        } catch (Exception e) {
            logger.error("selectedExerciseBookIdList={}", selectedExerciseBookIdList);
            logger.error("异步刷新练习册题目状态统计异常", e);
        } finally {
            if (tokenManager != null) {
                tokenManager.unLock("book_count_lock", threadName);
            }
        }

        if (triggerType != null) {
            ThreadPool.getInstance().addTask(new SyncRefreshExerciseBookDistributionCountTask(selectedExerciseBookIdList, triggerType));
        }
    }

}
