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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

/**
 * 异步刷新练习册分配导出数据
 *
 * @author yrf
 * @date 2020/6/2 14:42
 */
public class SyncRefreshExerciseBookDistributionCountTask extends Task {

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

    private List<String> selectedExerciseBookIdList;
    private int triggerType;

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

    @Override
    public void run() {
        TokenManager tokenManager = null;
        String threadName = "";
        try {
            // 延迟三秒，防止数据的修改还未生效
            TimeUnit.SECONDS.sleep(3);

            logger.info("异步刷新练习册分配导出数据开始，selectedExerciseBookIdList={}", selectedExerciseBookIdList);

            int addLockTimeOut = 0;
            KmtExerciseSysService kmtExerciseSysService = SystemResourceLocator.getBean(KmtExerciseSysService.class);
            tokenManager = SystemResourceLocator.getBean(TokenManager.class);
            boolean success;
            threadName = Thread.currentThread().getName();
            int count = 0;
            while (addLockTimeOut < 60000) {
                success = tokenManager.addLock("exercise_book_distribution_count_lock", threadName, 60);
                if (success) {
                    logger.info("异步刷新练习册分配导出数据加锁成功");
                    count = kmtExerciseSysService.refreshExerciseBookDistributionCount(selectedExerciseBookIdList, triggerType);
                    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("exercise_book_distribution_count_lock", threadName);
            }
        }
    }

}
