package com.qxgmat.task;

import com.alibaba.fastjson.JSONObject;
import com.qxgmat.data.constants.enums.SettingKey;
import com.qxgmat.data.dao.entity.Setting;
import com.qxgmat.data.dao.entity.UserService;
import com.qxgmat.service.UsersService;
import com.qxgmat.service.inline.SettingService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by gaojie on 2017/11/20.
 */
@Component
public class ScheduledTask {
    private static final Logger logger = LoggerFactory.getLogger(ScheduledTask.class);

    @Autowired
    private AsyncTask asyncTask;

    @Autowired
    private SettingService settingService;

    @Autowired
    private UsersService usersService;

    /**
     * cron表达式：* * * * * *（共6位，使用空格隔开，具体如下）
     * cron表达式：*(秒0-59) *(分钟0-59) *(小时0-23) *(日期1-31) *(月份1-12或是JAN-DEC) *(星期1-7或是SUN-SAT)
     * 注意： 30 * * * * * 表示每分钟的第30秒执行，而（*斜杠30）表示每30秒执行
     *
     * */
    @Scheduled(cron="0 0 * * * *")
    public void refreshToken(){
        // 每小时刷新快过期用户的accessToken

    }

    @Scheduled(cron="0 0 * * * *")
    public void refreshPrepare(){
        // 每小时刷新备考统计信息
        Setting setting = Setting.builder().value(new JSONObject()).build();
        settingService.editByKey(SettingKey.PREPARE_INFO, setting);
    }

    @Scheduled(cron="0 1 0 * * *")
    public void autoExercisePaper() throws ParseException {
        // 每天判断是否自动组卷
        Setting setting = settingService.getByKey(SettingKey.EXERCISE_PAPER_AUTO);
        JSONObject value = setting.getValue();
        String dateString = value.getString("date");
        if (dateString == null) return;
        Date date = DateFormat.getDateTimeInstance().parse(dateString);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String param = sdf.format(date);
        String now = sdf.format(new Date());
        if(param.equals(now)){
            // 当天
            asyncTask.autoExercisePaperError();
        }
    }
}
