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.ZhuanZhuanSuanFaTest;

import java.util.*;

public class HuNanZhuanZhuan {

    public static int zhuanZhuanCard = 0;

    //湖南转转麻将手牌
    private List<Integer> zhuanZhuanCardInhand = new ArrayList<Integer>();


    //打出的牌
    private List<Integer> zhuanZhuanchuguopai = new ArrayList<>();


    private static ZhuanZhuanSuanFaTest zhuanZhuanFaTest = new ZhuanZhuanSuanFaTest();



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

    // 会话标识
    public static String session = "";
    // 访问令牌
    public static String token = "";

    public List<Integer> getZhuanZhuanCardInhand() {
        return zhuanZhuanCardInhand;
    }

    public List<Integer> getZhuanZhuanchuguopai() {
        return zhuanZhuanchuguopai;
    }

    /**
     * 初始化手牌协议 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++) {
                zhuanZhuanCardInhand.add(cardList.getInt(i));
            }
            if (zhuanZhuanCardInhand.size() > 13) {
                outCard(client);
                if (!zhuanZhuanCardInhand.isEmpty()) {
                    System.out.println("机器人:" + param.getInt("seat") + "为庄家，需要出牌1111" + ",牌为：" + zhuanZhuanCardInhand.get(0));
                } else {
                    System.out.println("机器人:" + param.getInt("seat") + "为庄家，需要出牌1111，但手牌为空");
                }
            }
            System.out.println("机器人:" + param.getInt("bank_seat") + "初始化手牌" + ",牌为：" + zhuanZhuanCardInhand.toString());

        }
        return null;
    }


   // ... existing code ...
    /**
     * 出牌方法
     *
     */
    public  void outCard(TaurusClient client) {
            //麻将出牌
            String zhuanzhaunOutCard = zhuanZhuanFaTest.outCardSuanFa(zhuanZhuanCardInhand, zhuanZhuanCard);

            ITObject params = TObject.newInstance();
            int cardToOut;
            if (StringUtil.isNotEmpty(zhuanzhaunOutCard)) {
                cardToOut = Integer.parseInt(zhuanzhaunOutCard);
            }else {
                cardToOut = zhuanZhuanCardInhand.get(0);
            }
            params.putString("session", session + "," + token);

            params.putInt("card", cardToOut);
            int outCountBefore = zhuanZhuanchuguopai.size();

            if (outCountBefore >=1){
                List<Integer> cardsToSend = zhuanZhuanchuguopai.subList(0, outCountBefore);
                params.putTArray("outcard_list", CardUtil.maJiangToTArray(cardsToSend));
            }
            params.putTArray("card_list", CardUtil.maJiangToTArray(zhuanZhuanCardInhand));
            zhuanZhuanchuguopai.add(cardToOut);
            System.out.println("机器人出牌: " + cardToOut);
            zhuanZhuanCardInhand.remove(Integer.valueOf(cardToOut));
            System.out.println("目前机器人剩余手牌：" + zhuanZhuanCardInhand.toString());

            client.send("611", params, response -> {
                System.out.println("出牌成功: " + response.returnCode);
            });

    }
// ... existing code ...





    /**
     * 出牌广播协议 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;
            }
            zhuanZhuanCard = param.getInt("card");
            System.out.println("出牌广播" + zhuanZhuanCard);
            System.out.println("座位号:" + param.getInt("seat") + "的用户出牌:" + param.getInt("card"));
        }
        return null;
    }


    /**
     * 摸牌协议 819
     *
     * @param command 协议号
     * @param message 消息对象
     * @return
     */
    public  String getCard(String 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}
            int card = param.getInt("card");
            System.out.println("轮到座位号:" + param.getInt("seat") + "的用户摸牌" + ",牌为：" + card);
            if (param.getInt("player") != null) {
                zhuanZhuanCardInhand.add(card);
                
                // 添加摸牌分析逻辑
                System.out.println("\n===== 摸牌分析开始 =====");
                
                // 创建包含摸牌后的手牌副本
                List<Integer> tempHand = new ArrayList<>(zhuanZhuanCardInhand);
                tempHand.sort(Integer::compareTo);
                
                // 调用算法类进行摸牌分析
                if (zhuanZhuanFaTest != null) {
                    boolean isTing = zhuanZhuanFaTest.analyzeDrawCard(zhuanZhuanCardInhand, card);
                    
                    // 如果摸牌后可以听牌，记录信息
                    if (isTing) {
                        System.out.println("\n摸牌后已进入听牌状态！");
                    }
                    
                    // 分析打出哪张牌可以听牌
                    Map<Integer, Set<Integer>> discardToTingMap = zhuanZhuanFaTest.findDiscardToTing(tempHand);
                    if (discardToTingMap != null && !discardToTingMap.isEmpty()) {
                        System.out.println("可打出后听牌的牌数量: " + discardToTingMap.size());
                    }
                }
                
                System.out.println("===== 摸牌分析结束 =====");
//                cardInhand.add(104);
            }
        }
        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;
    }


    /**
     * 处理杠碰胡操作
     *
     * @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);
            System.out.println("机器人收到牌：" + opcard + "，当前手牌：" + zhuanZhuanCardInhand);
        }
        //弃 是根据算法选择是否要弃掉 不进行碰杠胡
        //params.putInt("qi", 0);
        //params.putInt("id", 0);

        // 如果是碰操作，使用算法判断是否应该碰
        if (type == 2 && zhuanZhuanFaTest != null) {
            // 复制当前手牌进行分析
            List<Integer> tempHands = new ArrayList<>(zhuanZhuanCardInhand);
            // 使用算法判断是否应该碰牌
            boolean shouldPong = zhuanZhuanFaTest.shouldPong(opcard, tempHands);
            if (!shouldPong) {
                // 如果算法判断不应该碰，设置放弃操作
                params.putInt("qi", 1);
                params.putInt("id", 0);
                System.out.println("智能决策：不碰该牌，保持手牌灵活性");
                
                client.send("612", params, response -> {
                    System.out.println("操作成功: " + response.returnCode);
                });
                return null;
            }
        }
        
        // 如果是杠操作，使用算法判断是否应该杠
        if (type == 3 || type == 4 || type == 5) {
            if (zhuanZhuanFaTest != null) {
                List<Integer> tempHands = new ArrayList<>(zhuanZhuanCardInhand);
                boolean shouldGang = zhuanZhuanFaTest.shouldGang(opcard, tempHands, type);
                if (!shouldGang) {
                    params.putInt("qi", 1);
                    params.putInt("id", 0);
                    System.out.println("智能决策：不杠该牌，保持手牌灵活性");
                    
                    client.send("612", params, response -> {
                        System.out.println("操作成功: " + response.returnCode);
                    });
                    return null;
                }
            }
        }

        //执行碰牌
        if (type == 2) {
            params.putString("session", session + "," + token);
            params.putInt("qi", 0);
            params.putInt("id", 1);
            Util.removeCard(zhuanZhuanCardInhand, opcard, 2);
            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("执行胡牌：" + opcard);
            //执行吃杠
        } else if (type == 3) {
            params.putString("session", session + "," + token);
            params.putInt("qi", 0);
            params.putInt("id", 1);
            Util.removeCard(zhuanZhuanCardInhand, opcard, 3);
            System.out.println("执行吃杠：" + opcard);
            //执行自杠
        } else if (type == 4) {
            params.putString("session", session + "," + token);
            params.putInt("qi", 0);
            params.putInt("id", 1);
            Util.removeCard(zhuanZhuanCardInhand, opcard, 4);
            System.out.println("执行自杠：" + opcard);
            // 碰后补杠
        } else if (type == 5) {
            params.putString("session", session + "," + token);
            params.putInt("qi", 0);
            params.putInt("id", 1);
            Util.removeCard(zhuanZhuanCardInhand, opcard, 1);
            System.out.println("执行碰后补杠：" + opcard);
        }

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

        client.send("612", 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) { // 碰，杠
            zhuanZhuanchuguopai.remove(Integer.valueOf(card));
            System.out.println("删除出过的牌组 成功");
        }
        return null;
    }
}
