package com.ai.da.common.task;

import com.ai.da.common.utils.RedisUtil;
import com.ai.da.mapper.primary.entity.Account;
import com.ai.da.service.AccountService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Component
@Slf4j
public class AccountTask {

    @Resource
    private AccountService accountService;
    @Resource
    private RedisUtil redisUtil;

    /**
     * 每周日晚上刷新 年付用户、月付用户的积分
     * 替换为
     * 每个月月初只刷新教育子账号的积分
     */
//    @Scheduled(cron = "0 25 14 * * ?")
    @Scheduled(cron = "0 0 0 1 * ?")
    public void refreshCreditsMonthly() {
        log.info("每月1号0点 重置教育版子账号为默认积分");
        accountService.refreshCreditsMonthly();
    }

//    @Scheduled(cron = "0 */5 * * * *") // Run every 5 minutes
    public void getPaidUser() {
        // 获取code-create 表中 指定日期之后 订单状态为wc-processing的订单
        accountService.extendValidityForCC();
    }

    // 每天凌晨0点执行一次
    @Scheduled(cron = "0 0 0 * * ?")
    public void cancelActivityBenefits() {
        // 1、查询当前所有参与了活动且过期的用户
        List<Account> accountList = accountService.getExpiredUserBySystemUser(4);

        // 2、将到期用户置为游客
        for (Account account : accountList) {
            log.info("参与活动的用户{} : {} 于 {} 账号有效期到期，置为游客", account.getId(), account.getUserEmail(), account.getValidEndTime());
            accountService.toVisitor(account);
        }
    }

    // 每天检测正式用户到期情况，每天凌晨0点执行
    @Scheduled(cron = "0 0 0 * * ?")
    public void paidUserToVisitor() {
        // 1、查询当前已过期正式用户或试用用户
        List<Account> accountList = accountService.getExpiredUserBySystemUser(1);
        accountList.addAll(accountService.getExpiredUserBySystemUser(2));
        accountList.addAll(accountService.getExpiredUserBySystemUser(3));

        // 2、将到期用户置为游客
        for (Account account : accountList) {
            log.info("用户{} : {} 于 {}账号有效期到期，置为游客", account.getId(), account.getUserEmail(), account.getValidEndTime());
            accountService.toVisitor(account);
        }
    }

    /**
     * ！！关闭此定时器！！不再从Code-Create上默认创建AiDA游客
     * 将Code-Create上注册的用户添加为AiDA的游客
     */
//    @Scheduled(cron = "0 */5 * * * *") // Run every 5 minutes
    public void registerUserToVisitor() {
        accountService.registerUserToVisitor();
    }

    @Scheduled(cron = "0 0 0 1 * ?")
    // 每月初刷新所有用户用户名剩余修改次数
    public void resetUsernameModifyTimes(){
        log.info("重置所有用户的用户名修改次数");
        redisUtil.batchDeleteKeysWithSamePrefix(RedisUtil.NICKNAME_MODIFY_TIMES);
    }

    //    @Scheduled(cron = "0 35 14 * * ?")
    @Scheduled(cron = "0 5 0 * * ?")
    public void checkEduAdminExpireStatus() {
        accountService.checkEduAdminExpireStatus();
    }
}
