package com.game.business.websocket.client;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.game.business.config.GameOneConfig;
import com.game.business.domain.AppGame;
import com.game.business.domain.AppGameClassify;
import com.game.business.domain.AppGameLottery;
import com.game.business.service.IAppGameClassifyService;
import com.game.business.service.IAppGameLotteryService;
import com.game.business.service.IAppGameService;
import com.game.business.task.AppGameBettingTask;
import com.game.business.util.Common;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import java.util.Date;

@Component
@ClientEndpoint
public class GameOneClient {

    @Autowired
    private IAppGameLotteryService appGameLotteryService;

    @Autowired
    private IAppGameService appGameService;

    @Autowired
    private IAppGameClassifyService appGameClassifyService;

    @Autowired
    private AppGameBettingTask appGameBettingTask;

    @OnOpen
    public void onOpen(Session session) throws Exception{
        System.out.printf("game one 游戏已连接 server");
        // 发送游戏编码
        session.getBasicRemote().sendText("{\"code\":\"" + Common.GAME_ONE_CODE + "\"}");
    }

    @OnClose
    public void onClose(Session session) throws Exception{
        System.out.printf("game on 游戏已断开 server");
        connect();
    }

    @OnError
    public void onError(Session session, Throwable throwable) throws Exception{
        System.out.printf("game one 连接异常 [" + throwable.getMessage() + "]");
        connect();
    }

    public void connect(){
        synchronized (this){
            try {
                GameOneConfig.webSocketConnent.connect();
            }catch (Exception e){
                System.out.printf("连接 game on [socket] 异常" + e.getMessage());
            }
        }
    }

    @OnMessage
    public void onMessage(Session session, String message){
        try {
            if(StringUtils.isBlank(message)){
                System.out.println("game one 数据为空");
                return;
            }

            System.out.println("game one 接收数据" + message);
            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;
            }

            // 更新倒计时
            if(type == 1){

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

                if(classCode == null){
                    System.out.println("游戏socket推送倒计时，平台ID为空。");
                    return;
                }

                if(gameDataArry == null){
                    System.out.println("游戏socket推送倒计时，data对象为空。");
                    return;
                }

                if(time == null){
                    System.out.println("游戏socket推送倒计时，time为空。");
                    return;
                }

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

                for (int i = 0; i < gameDataArry.size(); i++) {
                    JSONObject jsonObject = gameDataArry.getJSONObject(i);
                    String gameCode = jsonObject.getString("id");
                    if(gameCode == null){
                        System.out.println("游戏socket推送倒计时，游戏id为空。");
                        continue;
                    }

                    AppGame appGame = appGameService.selectAppGameByClassIdAndCode(appGameClassify.getId(), gameCode);
                    if(appGame == null){
                        System.out.println("开奖游戏不存在：" + gameCode);
                    }
                    appGame.setGameTime(time);
                    appGameService.updateAppGame(appGame);
                }
                return;
            }

            if(type != 2 && type != 3){
                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("data");
                }
                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);
            }

            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为空。");
                    return;
                }

                AppGame appGame = appGameService.selectAppGameByClassIdAndCode(appGameClassify.getId(), gameCode);
                if(appGame == null){
                    System.out.println("开奖游戏不存在：" + gameCode);
                }

                String gameDate = gameLotteryObject.getString("gameDate");

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

                if(type == 3){
                    appGame.setGameDate(gameDate);
                    appGameService.updateAppGame(appGame);
                    continue;
                }

                long count = appGameLotteryService.selectCount(appGame.getClassifyId(), appGame.getId(), gameDate);

                if(count > 0){
                    System.out.println("游戏socket推送开奖，当前期已开过将，游戏编码：" + gameCode + "，期号：" + gameDate);
                    continue;
                }

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

                // 保存开奖记录
                AppGameLottery appGameLottery = new AppGameLottery();
                appGameLottery.setGameId(appGame.getId());
                appGameLottery.setGameDate(gameDate);
                appGameLottery.setIsLottery(isLottery);
                appGameLottery.setGameRecordDate(new Date());
                appGameLottery.setGameLotterySucc(gameLotterySucc);
                appGameLotteryService.save(appGameLottery);

                if(isLottery != 1){
                    continue;
                }

                appGameBettingTask.gameBettingTask(appGameClassify.getId(), appGame.getId(), gameDate, gameLotterySucc);
            }
        }catch (Exception e){
            e.printStackTrace();
            System.out.printf("game one 接收数据异常[" + e.getMessage() + "]");
        }
    }
}
