package com.game.business.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.game.business.domain.*;
import com.game.business.dto.AppItemCountDTO;
import com.game.business.service.*;
import com.game.business.util.Common;
import com.game.business.util.im.TencentCloudImUtil;
import com.game.business.vo.AppGameItemBettingVO;
import com.game.common.constant.CacheConstants;
import com.game.common.constant.finance.FinTranType1;
import com.game.common.constant.finance.FinTranType2;
import com.game.common.constant.finance.FinTranType3;
import com.game.common.core.domain.HttpRet;
import com.game.common.core.redis.RedisCache;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

@Component
public class AppGameBettingTask {

    @Autowired
    private IAppGameLotteryHistoryService appGameLotteryHistoryService;

    @Autowired
    private IAppGameService appGameService;

    @Autowired
    private IAppGameClassifyService appGameClassifyService;

    @Autowired
    private RedisCache redisCache;

    @Async("asyncExecutor")
    public void gameDataTask(String message, String gameCodeFinal) throws Exception {

        JSONArray dataArry = JSONArray.parseArray(message);

        Integer type = null;

        for (int i = 0; i < dataArry.size(); i++) {
            JSONObject jsonObject = dataArry.getJSONObject(i);
            if(jsonObject.containsKey("type")){
                type = jsonObject.getInteger("type");
                break;
            }
        }

        if(type == null){
//            System.out.println("游戏socket推送类型为空。");
            return;
        }


        JSONArray gameArry = null;
        String classCode = null;
        for (int i = 0; i < dataArry.size(); i++) {
            JSONObject jsonObject = dataArry.getJSONObject(i);
            if(jsonObject.containsKey("gameTypeSortArrayVOS")){
                gameArry = jsonObject.getJSONArray("gameTypeSortArrayVOS");
            }
            if(jsonObject.containsKey("id")){
                classCode = jsonObject.getString("id");
            }
        }

        if(gameArry == null){
//            System.out.println("游戏socket推送期号或开奖，gameTypeSortArrayVOS对象为空。");
            return;
        }

        if(classCode == null){
//            System.out.println("游戏socket推送期号或开奖，平台ID为空。");
            return;
        }

        AppGameClassify appGameClassify = appGameClassifyService.getByCode(classCode);
        if(appGameClassify == null){
//            System.out.println("开奖游戏平台不存在：" + classCode);
            return;
        }

        List<AppGame> appGameList = appGameService.selectAppGameByClassId(appGameClassify.getId());
        if(appGameList == null || appGameList.isEmpty()){
//            System.out.println("开奖游戏平台没有游戏：" + classCode);
            return;
        }
        Map<String, List<AppGame>> codeGameMap = appGameList.stream().collect(Collectors.groupingBy(AppGame::getCode));

        for (int i = 0; i < gameArry.size(); i++) {
            JSONObject gameLotteryObject = gameArry.getJSONObject(i);
            String gameCode = gameLotteryObject.getString("id");

            if(gameCode == null){
//                System.out.println("游戏socket推送期号或开奖，游戏ID为空。");
                continue;
            }
            if(!gameCodeFinal.equals(gameCode)){
                continue;
            }

            if(!codeGameMap.containsKey(gameCode)){
//                System.out.println("开奖游戏不存在：" + gameCode);
                continue;
            }
            AppGame appGame = codeGameMap.get(gameCode).get(0);

            String gameDate = gameLotteryObject.getString("gameDate");
            if(gameDate == null){
//                System.out.println("游戏socket推送期号或开奖，期号为空。");
                continue;
            }

            if(type == 3){

                String redisKey = CacheConstants.GAME_LOTTERY_TASK_CREATE_NEW2.concat(appGame.getId() + ":" + gameCode);
                if(!redisCache.redisTemplate.opsForValue().setIfAbsent(redisKey, 1)){
                    continue;
                }

                try {

                    AppGameLotteryHistory appGameLottery = appGameLotteryHistoryService.selectLottery(appGame.getClassifyId(), appGame.getId(), gameDate);

                    if(appGameLottery == null){

                        appGameLottery = new AppGameLotteryHistory();
                        appGameLottery.setGameId(appGame.getId());
                        appGameLottery.setClassId(appGame.getClassifyId());
                        appGameLottery.setGameDate(gameDate);
                        appGameLottery.setIsLottery(0);
                        appGameLottery.setGameRecordDate(new Date());
                        appGameLotteryHistoryService.save(appGameLottery);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    redisCache.redisTemplate.delete(redisKey);
                }
                continue;
            }

            Integer isLottery = gameLotteryObject.getInteger("isLottery");
            String gameLotterySucc = gameLotteryObject.getString("gameLotterySucc");

            if(isLottery != 1){
                continue;
            }

            if(gameLotterySucc == null || gameLotterySucc.trim().isEmpty()){
//                System.out.println("游戏socket推送倒计时，time为空。");
                continue;
            }

            String redisKey = CacheConstants.GAME_LOTTERY_TASK_NEW2.concat(appGame.getId() + ":" + gameDate);
            if(!redisCache.redisTemplate.opsForValue().setIfAbsent(redisKey, 1)){
                continue;
            }

            try {

                AppGameLotteryHistory appGameLottery = appGameLotteryHistoryService.selectLottery(appGame.getClassifyId(), appGame.getId(), gameDate);

//                if(gameCode.equals("6")){
//                    gameLotterySucc = appGameLotteryAutoTask.autoTask(appGame, gameDate);
//                }

                if(appGameLottery == null){
                    // 保存开奖记录
                    appGameLottery = new AppGameLotteryHistory();
                    appGameLottery.setGameId(appGame.getId());
                    appGameLottery.setClassId(appGame.getClassifyId());
                    appGameLottery.setGameDate(gameDate);
                    appGameLottery.setIsLottery(isLottery);
                    appGameLottery.setGameRecordDate(new Date());
                    appGameLottery.setGameLotterySucc(gameLotterySucc);
                    appGameLotteryHistoryService.save(appGameLottery);
                }else{
                    if(appGameLottery.getIsLottery() == 1){
//                      redisCache.redisTemplate.delete(redisKey);
//                      System.out.println("游戏socket推送开奖，当前期已开过将，游戏编码：" + gameCode + "，期号：" + gameDate);
                        continue;
                    }

                    AppGameLotteryHistory updateAppGameLottery = new AppGameLotteryHistory();
                    updateAppGameLottery.setId(appGameLottery.getId());
                    updateAppGameLottery.setIsLottery(isLottery);
                    updateAppGameLottery.setGameRecordDate(new Date());
                    updateAppGameLottery.setGameLotterySucc(gameLotterySucc);
                    appGameLotteryHistoryService.updateById(updateAppGameLottery);
                }
//                lotteryTask(appGame, appGameClassify, gameLotterySucc, gameDate);
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                redisCache.redisTemplate.delete(redisKey);
            }
        }
    }
}
