package hunan;

import com.game.Util;
import com.taurus.core.entity.ITArray;
import com.taurus.core.entity.ITObject;
import com.taurus.core.entity.TObject;
import com.taurus.core.util.StringUtil;
import taurus.client.Message;
import taurus.client.TaurusClient;
import taurus.util.CardUtil;
import taurus.util.HongZhongSuanFaTest;

import java.util.*;

public class HuNanHongZhong {


    public static int hongZhongCard = 0;

    //湖南红中麻将手牌
    private List<Integer> hongZhongCardInhand = new ArrayList<>();

    //红中麻将出过的牌
    private List<Integer> hongZhongchuguopai = new ArrayList<>();


    // 玩家座位号
    public static int seat = 0;

    public static int playerId = 0;


    // 会话标识
    public static String session = "";
    // 访问令牌
    public static String token = "";
    //红中麻将算法
//    private static HongZhongSuanFa hongZhongSuanFa = new HongZhongSuanFa();

    private static HongZhongSuanFaTest hongZhongSuanFaTest = new HongZhongSuanFaTest();



    // 公共的getter和setter方法
    public List<Integer> getHongZhongCardInhand() {
        return hongZhongCardInhand;
    }

    public List<Integer> getChuGuoCardInhand() {
        return hongZhongchuguopai;
    }


    /**
     * 出牌广播协议 812
     *
     * @param command 协议号
     * @param message 消息对象
     * @return
     */
    public static String drawCard(String command, Message message) {
        if (command.equalsIgnoreCase("812")) {
            ITObject param = message.param;
            if (param == null) {
                return null;
            }
            hongZhongCard = param.getInt("card");
            System.out.println("出牌广播" + hongZhongCard);
            System.out.println("座位号:" + param.getInt("seat") + "的用户出牌:" + param.getInt("card"));
        }
        return null;
    }


    /**
     * 摸牌协议 819
     *
     * @param command 协议号
     * @param message 消息对象
     * @return
     */
    public String getCard(String command, Message message) {
        System.out.println("摸牌协议-----" + command + "message---" + message);
        if (command.equalsIgnoreCase("819")) {
            ITObject param = message.param;
            if (param == null) {
                return null;
            }
//            {seat=2, Ishupai=0, isBaoTing=-1, tingcard=0, isgang=0, card=101, left_count=106}
            System.out.println("轮到用户:" + param.getInt("player") + "的用户摸牌" + ",牌为：" + param.getInt("card"));
            System.out.println("用户id" + playerId);
            System.out.println("座位号" + param.getInt("seat"));
            if (param.getInt("player") != null) {
                int drawnCard = param.getInt("card");

                hongZhongSuanFaTest.drawnCards = drawnCard;
                hongZhongCardInhand.add(drawnCard);
                System.out.println("摸牌后手牌" + hongZhongCardInhand);

                // 创建包含摸牌后的完整手牌
                List<Integer> newHand = new ArrayList<>(hongZhongCardInhand);

                // 调用分离分析方法，将刻子、顺子、红中单独拎出后分析剩余牌
                System.out.println("[HuNanHongZhong] 开始分离分析手牌结构...");
                hongZhongSuanFaTest.separateAndAnalyzeHand(newHand);

                // 直接调用hongZhongSuanFaTest中的analyzeDrawCard方法分析摸牌后是否可听牌
                hongZhongSuanFaTest.analyzeDrawCard(hongZhongCardInhand, drawnCard);


                // 调用新添加的findDiscardToTing方法，分析打出哪张牌可以听牌
                System.out.println("[HuNanHongZhong] 开始分析打出哪张牌可以听牌...");
                Map<Integer, Set<Integer>> discardOptions = hongZhongSuanFaTest.findDiscardToTing(newHand);

                // 如果有可打出后听牌的选项，记录信息
                if (!discardOptions.isEmpty()) {
                    System.out.println("[HuNanHongZhong] 发现" + discardOptions.size() + "个可打出后听牌的选项");
                    // 这些信息将在出牌决策时被考虑
                } else {
                    System.out.println("[HuNanHongZhong] 当前没有可以打出后听牌的牌");
                }
            }
        }
        return null;
    }

    /**
     * 判断是否应该碰牌
     *
     * @param proposedCard 提议碰的牌
     * @return 是否应该碰牌
     */
    public boolean shouldPong(int proposedCard) {
        System.out.println("判断是否应该碰牌: " + proposedCard);

        // 直接调用hongZhongSuanFaTest中的shouldPong方法，它已经包含了所有需要的规则
        return hongZhongSuanFaTest.shouldPong(proposedCard, hongZhongCardInhand);

//        return hongZhongSuanFaTest.shouldPong(proposedCard, Arrays.asList(305,304,303,207,207,204,204,208,208,201,201,412,412));
    }


    /**
     * 初始化手牌协议 811
     *
     * @param command 协议号
     * @param message 消息对象
     * @return
     */
    public String cardInHead(String command, Message message, TaurusClient client) {
        if (command.equalsIgnoreCase("811")) {
            ITObject param = message.param;
            if (param == null) {
                return null;
            }
//            {bank_seat=1, laiziCard=0, laiziCard2=0, laiziCard2Before=0, jing=0, laiziCardBefore=0, card_list=[101, 103, 104, 201, 204, 207, 208, 209, 307, 309, 501, 502, 503]}
            ITArray cardList = param.getTArray("card_list");
            for (int i = 0; i < cardList.size(); i++) {
                hongZhongCardInhand.add(cardList.getInt(i));
            }
            if (hongZhongCardInhand.size() > 13) {
                outCard(client);
                System.out.println("机器人:" + param.getInt("seat") + "为庄家，需要出牌" + ",牌为：" + hongZhongCardInhand.get(0));
            }
            System.out.println("机器人:" + param.getInt("seat") + "初始化手牌" + ",牌为：" + hongZhongCardInhand.toString());

        }
        return null;
    }

    /**
     * 处理杠碰胡操作
     *
     * @param param 消息参数
     * @return
     */
    public String actionCard(ITObject param, TaurusClient client) {
        //获取碰杠胡参数 type  和id 后续算法接入，是否能让碰和杠
        ITArray tipList = param.getTArray("tip_list");
        int id = 0;
        int type = 0;
        int opcard = 0;
        ITObject params = TObject.newInstance();
        if (tipList != null && tipList.size() > 0) {
            TObject firstTip = (TObject) tipList.get(0).getObject();
            id = firstTip.getInt("id");
            type = firstTip.getInt("type");
            opcard = firstTip.getTArray("opcard").getInt(0);
            System.out.println("id ++ " + id);
            System.out.println("type ++ " + type);
        }
        //弃 是根据算法选择是否要弃掉 不进行碰杠胡
        //params.putInt("qi", 0);
        //params.putInt("id", 0);

        //执行碰牌
        if (type == 2) {
            // 根据规则判断是否应该碰牌
            if (shouldPong(opcard)) {
                params.putString("session", session + "," + token);
                params.putInt("qi", 0);
                params.putInt("id", 1);
                Util.removeCard(hongZhongCardInhand, opcard, 2);
                System.out.println("执行碰牌并删除碰的牌");
            } else {
                params.putString("session", session + "," + token);
                params.putInt("qi", 1); // 放弃碰牌
                params.putInt("id", 0);
                System.out.println("根据规则，决定不碰牌: " + opcard);
            }
//            Global.logger.info("删除碰的牌");
            //执行胡牌
        } else if (type == 6) {
            params.putString("session", session + "," + token);
            params.putInt("qi", 0);
            params.putInt("id", 1);
            System.out.println("执行胡牌");
            //执行吃杠
        } else if (type == 3) {
            params.putString("session", session + "," + token);
            params.putInt("qi", 0);
            params.putInt("id", 1);
            Util.removeCard(hongZhongCardInhand, opcard, 3);
            System.out.println("执行吃杠");
            //执行自杠
        } else if (type == 4) {
            params.putString("session", session + "," + token);
            params.putInt("qi", 0);
            params.putInt("id", 1);
            Util.removeCard(hongZhongCardInhand, opcard, 4);
            System.out.println("执行自杠");
            // 碰后补杠
        } else if (type == 5) {
            params.putString("session", session + "," + token);
            params.putInt("qi", 0);
            params.putInt("id", 1);
            Util.removeCard(hongZhongCardInhand, opcard, 1);
            System.out.println("执行碰后补杠");
        }

//        cardInhand.remove(0);
//        cardInhand.remove(1);
        System.out.println("执行id为：" + 0 + "的操作");

        client.send("612", params, response -> {
            System.out.println("操作成功: " + response.returnCode);
        });
        return null;
    }


    public static String changePlayer(String command, Message message) {
        if (command.equalsIgnoreCase("820")) {
            ITObject param = message.param;
            if (param == null) {
                return null;
            }
            System.out.println("出牌权转移到座位号:" + param.getInt("seat") + "的用户");
        }
        return null;
    }


    /**
     * 出牌方法
     */
//    public  String outCard(TaurusClient client, List< Integer> list) {
    public String outCard(TaurusClient client) {
        // 调用分离分析方法，将刻子、顺子、红中单独拎出后分析剩余牌
        System.out.println("[HuNanHongZhong] 出牌前分离分析手牌结构...");
        hongZhongSuanFaTest.separateAndAnalyzeHand(hongZhongCardInhand);

        // 红中麻将出牌
        String hongzhongOutCard = hongZhongSuanFaTest.outCardSuanFa(hongZhongCardInhand, hongZhongCard);
//        String hongzhongOutCard = hongZhongSuanFaTest.outCardSuanFa(list, hongZhongCard);
        ITObject params = TObject.newInstance();
        int cardToOut;
        if (StringUtil.isNotEmpty(hongzhongOutCard)) {
            cardToOut = Integer.parseInt(hongzhongOutCard);
        } else {
            cardToOut = hongZhongCardInhand.get(0);
        }
        params.putInt("card", cardToOut);

        int outCountBefore = hongZhongchuguopai.size(); // 当前历史出牌数量

        // 第n次出牌时，发送前n-1张出牌
        if (outCountBefore >= 1) {
            // 发送前n-1张（所有历史出牌）
            List<Integer> cardsToSend = hongZhongchuguopai.subList(0, outCountBefore);
            params.putTArray("outcard_list", CardUtil.maJiangToTArray(cardsToSend));
        }
        params.putTArray("card_list", CardUtil.maJiangToTArray(hongZhongCardInhand));
        System.out.println("机器人牌============" + params);
        // 将当前出的牌添加到历史出牌列表
        hongZhongchuguopai.add(cardToOut);
        // 从手牌中移除
        hongZhongCardInhand.remove(Integer.valueOf(cardToOut));
        System.out.println("出牌: " + cardToOut);
        System.out.println("目前机器人剩余手牌：" + hongZhongCardInhand.toString());
        params.putString("session", session + "," + token);
        client.send("611", params, response -> {
            System.out.println("出牌成功: " + response.returnCode);
        });
        return null;
    }

    /**
     * 删除出过的牌组
     *
     * @param param
     * @return
     */
    public String shanchuchuguopai(ITObject param) {
        if (param == null) {
            return null;
        }
        Integer card = param.getInt("card"); // 操作牌值
        Integer type = param.getInt("type"); // 操作类型
        Integer from_seat = param.getInt("from_seat"); // 牌来源座位
        System.out.println("删除出过的牌组 card  " + card);
        System.out.println("删除出过的牌组 type  " + type);
        System.out.println("删除出过的牌组 from_seat  " + from_seat);
        System.out.println("机器人 seat  " + seat);

        if (type == 2 || type == 3 || type == 5) { // 碰，杠
            getChuGuoCardInhand().remove(Integer.valueOf(card));
            System.out.println("删除出过的牌组 成功");
        }
        return null;
    }
}
