package com.qxgmat.task;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.nuliji.tools.third.OauthData;
import com.qxgmat.data.constants.enums.SettingKey;
import com.qxgmat.data.dao.entity.Setting;
import com.qxgmat.data.dao.entity.User;
import com.qxgmat.data.dao.entity.UserService;
import com.qxgmat.data.relation.entity.UserPrepareRelation;
import com.qxgmat.help.WechatHelp;
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 javax.annotation.Resource;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 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;

    @Autowired
    private WechatHelp wechatHelp;

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


    // 每小时刷新快过期用户的accessToken
    @Scheduled(cron="0 0 * * * *")
    public void refreshWechatToken(){
        logger.info("Start refresh Wechat token");
        int page = 1;
        int size = 100;
        Date date = new Date();
        Page<User> userList;
        do{
            userList = usersService.listByWechatExpire(page, size, date);
            for(User user : userList){
                OauthData data = wechatHelp.refreshNative(user.getWechatRefreshToken());
                usersService.edit(User.builder()
                        .id(user.getId())
                        .wechatAccessToken(data.getAccessToken())
                        .wechatRefreshToken(data.getRefreshToken())
                        .wechatExpireTime(data.getExpiresTime())
                        .build()
                );
            }
        }while(userList.size() >= size);
    }

    // 每小时刷新备考统计信息
    @Scheduled(cron="0 0 * * * *")
    public void refreshPrepare(){
        logger.info("Start refresh Prepare");
        JSONObject value = new JSONObject();
        // 分别统计不同信息
        List<UserPrepareRelation> relations = null;
        // 身份
        relations = usersService.statPrepareStatus();
        JSONArray status = new JSONArray();
        for(UserPrepareRelation relation : relations){
            JSONObject one = new JSONObject();
            one.put("key", relation.getS());
            one.put("value", relation.getNumber());
            status.add(one);
        }
        value.put("status", status);

        // 考分
        relations = usersService.statPrepareGoal();
        JSONArray goal = new JSONArray();
        for(UserPrepareRelation relation : relations){
            JSONObject one = new JSONObject();
            one.put("key", relation.getI());
            one.put("value", relation.getNumber());
            goal.add(one);
        }
        value.put("goal", goal);

        // 考试时间
        relations = usersService.statPrepareExaminationTime();
        JSONArray examinationTime = new JSONArray();
        for(UserPrepareRelation relation : relations){
            JSONObject one = new JSONObject();
            one.put("key", relation.getS());
            one.put("value", relation.getNumber());
            examinationTime.add(one);
        }
        value.put("examinationTime", examinationTime);

        // 出分时间
        relations = usersService.statPrepareScoreTime();
        JSONArray scoreTime = new JSONArray();
        for(UserPrepareRelation relation : relations){
            JSONObject one = new JSONObject();
            one.put("key", relation.getS());
            one.put("value", relation.getNumber());
            scoreTime.add(one);
        }
        value.put("scoreTime", scoreTime);

        Setting setting = Setting.builder().value(value).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();
        }
    }
}
