package com.zanxiang.game.back.serve.task;

import com.zanxiang.game.back.serve.service.IGameTencentMiniGameCallbackService;
import com.zanxiang.game.module.base.ServerInfo;
import com.zanxiang.game.module.base.pojo.dto.GameDTO;
import com.zanxiang.game.module.base.pojo.enums.GameCategoryEnum;
import com.zanxiang.game.module.base.rpc.IGameRpc;
import com.zanxiang.module.redis.service.IDistributedLockComponent;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author : lingfeng
 * @time : 2025-03-10
 * @description : 腾讯小游戏玩家定时器
 */
@Slf4j
@Component
public class GameTencentMiniGameTask {

    private static final String CALL_BACK_URL_LOCK_KEY = "game-back:CALLBACK_URL_LOCK";

    @DubboReference(providedBy = ServerInfo.SERVER_DUBBO_NAME)
    private IGameRpc gameRpc;

    @Autowired
    private IDistributedLockComponent distributedLockComponent;

    @Autowired
    private IGameTencentMiniGameCallbackService gameTencentMiniGameCallbackService;

    /**
     * 每10分钟执行, 补充玩家信息中的 callBackUrl, 因为腾讯回调存在延迟的情况
     */
    @Scheduled(cron = "0 0/10 * * * ?")
    public void updateMiniGameUserCallBackUrl() {
        //上锁
        if (!distributedLockComponent.doLock(CALL_BACK_URL_LOCK_KEY, 0L, 5L, TimeUnit.MINUTES)) {
            return;
        }
        GameDTO gameDTO = gameRpc.getAllGameList().getData();
        List<GameDTO.GameBean> gameBeanList = Optional.ofNullable(gameDTO)
                .map(GameDTO::getAllGameList)
                .orElse(null);
        if (CollectionUtils.isEmpty(gameBeanList)) {
            return;
        }
        List<Long> gameIdList = gameBeanList.stream()
                .filter(gameBean -> gameBean.getId() >= 35
                        && Objects.equals(gameBean.getCategory(), GameCategoryEnum.CATEGORY_WX_APPLET.getId()))
                .map(GameDTO.GameBean::getId)
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(gameIdList)) {
            return;
        }
        gameIdList.forEach(gameId -> {
            try {
                gameTencentMiniGameCallbackService.delayUpdateMiniGameUserCallBackUrl(gameId, LocalDateTime.now());
            } catch (Exception e) {
                log.error("定时器-腾讯小游戏注册callBackUrl定时任务执行异常, gameId L {}, e : {}", gameId, e.getMessage());
            }
        });
    }
}
