package taurus.util;

import com.game.Util;
import com.taurus.core.entity.ITArray;
import com.taurus.core.entity.TArray;
import hunan.HandAnalysis;
import hunan.HuNanChangSha;

import java.util.*;




public class TinHuChi {
    public static boolean isMoreThanLast = false;
    public static  int lastTingCount = 0;


    public static int[][] countTiles(List<Integer> cardInHand) {
        int[][] counts = new int[5][10]; // 类型×值

        for (Integer card : cardInHand) {
            if (card == 0) {
                continue;
            }
            counts[card / 100 - 1][card % 100]++;
        }
        return counts;
    }

    public static boolean isJiangPai(int card){
        if (card%100==2||card%100==5||card%100==8){
            return true;
        }
        return false;
    }

    public static int checkduijiang(List<Integer> cardInHand) {
        Map<Integer, Integer> countMap = new HashMap<>();
        for (Integer item : cardInHand) {
            countMap.put(item, countMap.getOrDefault(item, 0) + 1);
        }
        int jiangnum = 0;
        for (int key : countMap.keySet()) {
            if (isJiangPai(key)&&countMap.get(key)>=2){
                jiangnum++;
            }
        }
        return jiangnum;
    }

    /**
     * 测试方法
     */
    public static void main(String[] args) {
//        System.out.println("=== 测试开始 ===\n");
//
//        // 测试1：你的例子
        List<Integer> hand1 = new ArrayList<>();

       // hand1.add(209);
        hand1.add(208);
        hand1.add(204);
     //   hand1.add(204);

        hand1.add(203);
        hand1.add(203);
       // hand1.add(202);

        hand1.add(201);
        hand1.add(108);
        hand1.add(105);


        hand1.add(104);
        hand1.add(104);
        hand1.add(103);
       // hand1.add(102);


        int addcard =203;

        Map<String, Object> map = new HashMap<>();
        //碰之后的map
        Map<String, Object> map2 = new HashMap<>();

        //先判断碰之前还需要几手牌，以及孤章
//                            int jiangnum = checkduijiang(changShaCardInhand);
        List<Integer> tmpChangSch = new ArrayList<>();
        tmpChangSch.addAll(hand1);
        tmpChangSch.add(addcard);
        ChangshaWinSplitCard.checkNormalHu(tmpChangSch, map);
         System.out.println("checkNormalHu 孤章数量  " + ((List<Integer>) map.get("cardResiue")).size());
                 System.out.println("checkNormalHu 手数  " + map.get("remainingMelds"));


        //碰之后
        List<Integer> pengtemphand = new ArrayList<>();
        pengtemphand.addAll(tmpChangSch);
        Util.removeCard(pengtemphand, addcard, 3);

        ChangshaWinSplitCard.checkNormalHu(pengtemphand, map2);
        //判断两个map是否找到更优
        System.out.println("碰之前 map1: 手数" + Integer.parseInt(map.get("remainingMelds").toString()));
        System.out.println("碰之后 map2 手数:" + Integer.parseInt(map2.get("remainingMelds").toString()));
        //碰之后的手数小于碰之前的手数，可以碰
        if (Integer.parseInt(map2.get("remainingMelds").toString()) < Integer.parseInt(map.get("remainingMelds").toString())) {
            System.out.println("===============碰之后的手数小于碰之前的手数，可以碰 决定碰牌================== ++++ ");
        } else if (Integer.parseInt(map2.get("remainingMelds").toString()) == Integer.parseInt(map.get("remainingMelds").toString())) { //碰完后和碰之前手数相等，需要判断孤章数量
            //碰之后的数量
            int size2 = ((List<Integer>) map2.get("cardResiue")).size();
            System.out.println("碰之后的孤章数量    " + size2);

            int size1 = ((List<Integer>) map.get("cardResiue")).size();
            System.out.println("碰之前的孤章数量    " + size1);
            if (size2 < size1) {
                System.out.println("===============碰之后的孤章数量 小于 碰之前的孤章数量可以碰 ================== ++++ ");
            }
            //碰之后的手数大于碰之前的手数，或者碰之后的孤章数量大于碰之前的孤章数量不能碰
        } else if (Integer.parseInt(map2.get("remainingMelds").toString()) > Integer.parseInt(map.get("remainingMelds").toString()) || ((List<Integer>) map2.get("cardResiue")).size() > ((List<Integer>) map.get("cardResiue")).size()) {
            System.out.println("碰之后的手数大于碰之前的手数，或者碰之后的孤章数量大于碰之前的孤章数量不能碰");
        }
    }









//        List<Integer> temphand = new ArrayList<>();
//        temphand.addAll(hand1);
//        temphand.add(104);
//        Util.removeCard(temphand, 104, 3);
//        List<Integer> checktingpai1 = TinHuChi.checktingpai(temphand);
//        System.out.println("checktingpai1" + checktingpai1);

        //hand1.add(101);

//        Map<String, Object> map = new HashMap<>();
//        Map<String, Object> map2 = new HashMap<>();
//
//        List<List<Integer>> lists = checkChi(hand1, addcard);
//        //吃之前的逻辑
//        int jiangnum = checkduijiang(hand1);
//        hand1.add(addcard);
//        System.out.println(hand1);
//         ChangshaWinSplitCard.checkNormalHu(hand1, map);
//
//         System.out.println("checkNormalHu" + map.get("cardResiue"));
//
//        System.out.println("checktingpai1" + lists);
//        int index = 0;
//        int flag  = 0;
//        for (List<Integer> list : lists) {
//            List<Integer> temphand = hand1;
//            //temphand.add(addcard);
//            Util.removeCard(temphand,list.get(0),1);
//            Util.removeCard(temphand,list.get(1),1);
//            Util.removeCard(temphand,list.get(2),1);
//            System.out.println("temphand" + temphand);
//            ChangshaWinSplitCard.checkNormalHu(temphand, map2);
//            //判断两个map是否找到更优
//            System.out.println("map1:"+Integer.parseInt(map.get("remainingMelds").toString()));
//            System.out.println("map2:"+Integer.parseInt(map2.get("remainingMelds").toString()));
//
//
//            if (Integer.parseInt(map2.get("remainingMelds").toString()) < Integer.parseInt(map.get("remainingMelds").toString()) ){
//                flag=index+1;
//            }else if (Integer.parseInt(map2.get("remainingMelds").toString()) == Integer.parseInt(map.get("remainingMelds").toString())){
//               int size2 = ((List<Integer>) map2.get("cardResiue")).size();
//               System.out.println("size2" + size2);
//               int size1 = ((List<Integer>) map.get("cardResiue")).size();
//                System.out.println("size1" + size1);
//               if (size2 < size1){
//                   flag=index+1;
//               }
//
//               //如果手里没有将，则可以吃
//                if (jiangnum>0) {
//                    int  chihoujiangnum = checkduijiang(temphand);
//                    if (chihoujiangnum>0){
//                        //吃之后还有将
//                        flag=index+1;
//                    }
//                }else{
//                    System.out.println("没队将");
//                    //孤章1张 差一手 不是将 而且card不是将
//                    if (Integer.parseInt(map.get("remainingMelds").toString())==1&&size1==1&&!isJiangPai(((List<Integer>) map.get("cardResiue")).get(0))&&!isJiangPai(addcard)){
//                        //吃
//                        break;
//                    }
//                    flag=index+1;
//                   // break;
//                }
//
//
//
//            }
//
//            index ++ ;
//            System.out.println("checkNormalHu2" + map2);
//        }
//        System.out.println("flag" + flag);






        /*List<Integer> shifoutingpai = shifoutingpai(hand1);
        System.out.println("shifoutingpai" +  shifoutingpai);
//
//        List<Integer> checktingpai = checktingpai(hand1);
//        System.out.println("checktingpai" +  checktingpai);
//
//
        List<List<Integer>> lists = checkChi(hand1, addcard);
        int index = 0;
        int flag  = 0;
        for (List<Integer> list : lists) {
            List<Integer> temphand = hand1;
            temphand.add(addcard);
            Util.removeCard(temphand,list.get(0),1);
            Util.removeCard(temphand,list.get(1),1);
            Util.removeCard(temphand,list.get(2),1);
            List<Integer> checktingpai1 = checktingpai(temphand);
            if (checktingpai1.size() > 0) {
                flag =index +1;
            }
            index ++ ;
            System.out.println("checktingpai1" + checktingpai1);
        }
        System.out.println("flag" + flag);
        System.out.println(lists);
        */


    public static List<Integer> shifoutingpai(List<Integer> cardhand) {
        List<Integer> tpcards = new ArrayList<>();
        List<Integer> tmphc = cardhand;
        for (int i = 0; i < cardhand.size(); i++) {

            int tmpcard = tmphc.get(i);
//            tmphc.remove(i);
            for (int j = 101; j <= 109; j++) {
                WinCard win = new WinCard(tmphc, j);
                if (win.tryWin()) {
                    if (!tpcards.contains(j)) {
                        tpcards.add(j);
                    }
                }
            }
            for (int j = 201; j <= 209; j++) {
                WinCard win = new WinCard(tmphc, j);
                if (win.tryWin()) {
                    if (!tpcards.contains(j)) {
                        tpcards.add(j);
                    }
                }
            }
//            tmphc.add(tmpcard);
        }
        return tpcards;
    }

    public static List<Integer> checktingpai(List<Integer> cardhand) {
        List<Integer> tpcards = new ArrayList<>();
        List<Integer> tmphc = cardhand;
        for (int i = 0; i < cardhand.size(); i++) {

            int tmpcard = tmphc.get(0);
            tmphc.remove(0);
            for (int j = 101; j <= 109; j++) {
                WinCard win = new WinCard(tmphc, j);
                if (win.tryWin()) {
                    if (!tpcards.contains(tmpcard)) {
                        tpcards.add(tmpcard);
                    }
                }
            }
            for (int j = 201; j <= 209; j++) {
                WinCard win = new WinCard(tmphc, j);
                if (win.tryWin()) {
                    if (!tpcards.contains(tmpcard)) {
                        tpcards.add(tmpcard);
                    }
                }
            }
            tmphc.add(tmpcard);
        }
        return tpcards;
    }

    public static List<List<Integer>> checkChi(List<Integer> hand, int card) {
        List<List<Integer>> result = new ArrayList<>();
        if (Util.checkCard(card-1, hand ) &&Util.checkCard(card - 2,  hand)) {
            List<Integer> opcard = new ArrayList<>();
            opcard.add(card-1);
            opcard.add(card - 2);
            opcard.add(card);
            result.add(opcard);
        }

        if (Util.checkCard(card + 1, hand) && Util.checkCard(card - 1, hand)) {
            List<Integer> opcard = new ArrayList<>();
            opcard.add(card + 1);
            opcard.add(card - 1);
            opcard.add(card);
            result.add(opcard);
        }

        if (Util.checkCard(card + 1, hand) && Util.checkCard(card + 2, hand)) {
            List<Integer> opcard = new ArrayList<>();
            opcard.add(card + 1);
            opcard.add(card + 2);
            opcard.add(card);
            result.add(opcard);
        }

        return result;
    }

    public static boolean canChi(List<Integer> handCards, int card) {
        int type = card / 100;
        int value = card % 100;

        if (type >= 4) return false; // 字牌不能吃

        System.out.println("\n要吃的牌: " + value + getTypeName(type));
        System.out.println("当前手牌数量: " + handCards.size() + "张");

        List<int[]> chiOptions = new ArrayList<>(); // 存储所有能吃的方式

        // 检查三种吃法并记录
        if (value >= 3) {
            int prev2 = type * 100 + (value - 2);
            int prev1 = type * 100 + (value - 1);
            if (handCards.contains(prev2) && handCards.contains(prev1)) {
                chiOptions.add(new int[]{prev2, prev1});
                System.out.println("  可以组成" + (value - 2) + (value - 1) + value + "顺子");
            }
        }

        if (value >= 2 && value <= 8) {
            int prev = type * 100 + (value - 1);
            int next = type * 100 + (value + 1);
            if (handCards.contains(prev) && handCards.contains(next)) {
                chiOptions.add(new int[]{prev, next});
                System.out.println("  可以组成" + (value - 1) + value + (value + 1) + "顺子");
            }
        }

        if (value <= 7) {
            int next1 = type * 100 + (value + 1);
            int next2 = type * 100 + (value + 2);
            if (handCards.contains(next1) && handCards.contains(next2)) {
                chiOptions.add(new int[]{next1, next2});
                System.out.println("  可以组成" + value + (value + 1) + (value + 2) + "顺子");
            }
        }

        if (chiOptions.isEmpty()) {
            System.out.println("  没有能吃的方式");
            return false; // 没有能吃的方式
        }

        System.out.println("发现" + chiOptions.size() + "种吃法");

        // 记录所有能听牌的吃法及其听牌详情
        List<TingChiOption> tingOptions = new ArrayList<>();

        for (int[] chiPair : chiOptions) {
            System.out.println("\n尝试吃法: 用" + (chiPair[0] % 100) + getTypeName(type) +
                    "和" + (chiPair[1] % 100) + getTypeName(type) +
                    "吃" + value + getTypeName(type));

            // 检查这种吃法能听多少张牌以及听什么牌
            TingResult tingResult = getTingResultAfterChi(handCards, card, chiPair[0], chiPair[1]);
            if (tingResult != null && tingResult.tingCount > 0) {
                tingOptions.add(new TingChiOption(chiPair, tingResult.tingCount, tingResult.tingCards, tingResult.discardCard));
                System.out.println("  → 打" + (tingResult.discardCard % 100) + getTypeName(tingResult.discardCard / 100) +
                        "可听" + tingResult.tingCount + "张牌: " + formatCards(tingResult.tingCards));
            } else {
                System.out.println("  → 不能听牌");
            }
        }

        // 如果有能听牌的吃法
        if (!tingOptions.isEmpty()) {
            // 选择听牌数量最多的吃法
            tingOptions.sort((a, b) -> {
                // 优先按听牌数量排序
                if (b.tingCount != a.tingCount) {
                    return b.tingCount - a.tingCount;
                }
                // 如果听牌数量相同，可以考虑其他因素，比如听牌质量
                return 0;
            });

            TingChiOption bestOption = tingOptions.get(0);

            System.out.println("\n=== 选择最佳吃法 ===");
            System.out.println("用" + (bestOption.chiPair[0] % 100) + getTypeName(type) +
                    "和" + (bestOption.chiPair[1] % 100) + getTypeName(type) +
                    "吃" + value + getTypeName(type));
            System.out.println("打" + (bestOption.bestDiscard % 100) + getTypeName(bestOption.bestDiscard / 100));
            System.out.println("听" + bestOption.tingCount + "张牌: " + formatCards(bestOption.tingCards));

            // 分析听牌类型
            analyzeTingType(bestOption.tingCards);

            return true;
        }

        return false; // 所有吃法都不能形成好牌型
    }



    // 新增：获取吃牌后的听牌数量
    public static int getTingCountAfterChi(List<Integer> handCards, int chiCard,
                                           int remove1, int remove2) {
        // 模拟吃牌
        List<Integer> afterChi = new ArrayList<>(handCards);
        afterChi.remove(Integer.valueOf(remove1));
        afterChi.remove(Integer.valueOf(remove2));
        Collections.sort(afterChi);

        boolean needs258 = !checkSuitCount(afterChi);
        int targetSizeAfterDiscard = afterChi.size() - 1;

        int maxTingCount = 0;
        Set<Integer> uniqueCards = new HashSet<>(afterChi);

        for (int discardCard : uniqueCards) {
            List<Integer> afterDiscard = new ArrayList<>(afterChi);
            afterDiscard.remove(Integer.valueOf(discardCard));
            Collections.sort(afterDiscard);

            if (afterDiscard.size() == targetSizeAfterDiscard) {
                int tingCount = countTingCards(afterDiscard, needs258);
                maxTingCount = Math.max(maxTingCount, tingCount);
            }
        }

        return maxTingCount;
    }

    // 新增：统计听牌数量
    public static int countTingCards(List<Integer> hand, boolean needs258) {
        if (hand.size() % 3 != 1) return 0; // 听牌时手牌应该是3n+1张

        Set<Integer> tingCards = new HashSet<>();
        Set<Integer> allCards = getAllCards();

        for (int testCard : allCards) {
            List<Integer> tempHand = new ArrayList<>(hand);
            tempHand.add(testCard);
            if (canHu(tempHand, needs258)) {
                tingCards.add(testCard);
            }
        }

        return tingCards.size();
    }

    // 修改后的 TingChiOption 类
    static class TingChiOption {
        int[] chiPair;
        int tingCount;
        Set<Integer> tingCards;
        int bestDiscard;

        TingChiOption(int[] chiPair, int tingCount, Set<Integer> tingCards, int bestDiscard) {
            this.chiPair = chiPair;
            this.tingCount = tingCount;
            this.tingCards = tingCards;
            this.bestDiscard = bestDiscard;
        }
    }


    // 新增：获取吃牌后的听牌结果
    public static TingResult getTingResultAfterChi(List<Integer> handCards, int chiCard,
                                                   int remove1, int remove2) {
        // 模拟吃牌
        List<Integer> afterChi = new ArrayList<>(handCards);
        afterChi.remove(Integer.valueOf(remove1));
        afterChi.remove(Integer.valueOf(remove2));
        Collections.sort(afterChi);

        boolean needs258 = !checkSuitCount(afterChi);
        int targetSizeAfterDiscard = afterChi.size() - 1;

        TingResult bestResult = null;
        Set<Integer> uniqueCards = new HashSet<>(afterChi);

        for (int discardCard : uniqueCards) {
            List<Integer> afterDiscard = new ArrayList<>(afterChi);
            afterDiscard.remove(Integer.valueOf(discardCard));
            Collections.sort(afterDiscard);

            if (afterDiscard.size() == targetSizeAfterDiscard) {
                Set<Integer> tingCards = getTingCards(afterDiscard, needs258);
                int tingCount = tingCards.size();

                if (tingCount > 0) {
                    if (bestResult == null || tingCount > bestResult.tingCount) {
                        bestResult = new TingResult(tingCount, tingCards, discardCard);
                    }
                }
            }
        }

        return bestResult;
    }

    // 新增：获取具体的听牌集合
    public static Set<Integer> getTingCards(List<Integer> hand, boolean needs258) {
        if (hand.size() % 3 != 1) return new HashSet<>(); // 听牌时手牌应该是3n+1张

        Set<Integer> tingCards = new HashSet<>();
        Set<Integer> allCards = getAllCards();

        for (int testCard : allCards) {
            List<Integer> tempHand = new ArrayList<>(hand);
            tempHand.add(testCard);
            if (canHu(tempHand, needs258)) {
                tingCards.add(testCard);
            }
        }

        return tingCards;
    }

    // 新增：格式化牌显示
    public static String formatCards(Set<Integer> cards) {
        List<String> cardStrs = new ArrayList<>();
        for (int card : cards) {
            int type = card / 100;
            int value = card % 100;
            cardStrs.add(value + getTypeName(type));
        }
        return String.join(", ", cardStrs);
    }

    // 新增：记录听牌结果的类
    static class TingResult {
        int tingCount;
        Set<Integer> tingCards;
        int discardCard; // 打哪张牌能达到这个听牌

        TingResult(int tingCount, Set<Integer> tingCards, int discardCard) {
            this.tingCount = tingCount;
            this.tingCards = tingCards;
            this.discardCard = discardCard;
        }
    }
    /**
     * 检查吃牌并打出一张后是否能听牌 - 优化版
     */
    public static boolean canTingAfterChiAndDiscard(List<Integer> handCards, int chiCard,
                                                    int remove1, int remove2) {
        // 1. 模拟吃牌：移除两张牌，吃的牌不加入手牌
        List<Integer> afterChi = new ArrayList<>(handCards);
        afterChi.remove(Integer.valueOf(remove1));
        afterChi.remove(Integer.valueOf(remove2));
        Collections.sort(afterChi);

        System.out.println("  吃后手牌(" + afterChi.size() + "张): " + convertToReadable(afterChi));

        // 2. 检查是否需要258将（花色是否>=10张）
        System.out.println(chiCard);
        System.out.println(afterChi);
        boolean needs258 = !checkSuitCount(afterChi);
        if (needs258) {
            System.out.println("  花色牌数不足10张，需要258做将");
        }

        // 3. 根据手牌数量确定目标手牌数
        int originalSize = handCards.size();
        int targetSizeAfterDiscard;

        if (originalSize == 13) {
            // 标准情况：13张手牌 -> 吃后11张 -> 打后10张
            targetSizeAfterDiscard = 10;
        } else if (originalSize == 14) {
            // 你的例子：14张手牌 -> 吃后12张 -> 打后11张
            targetSizeAfterDiscard = 11;
        } else {
            // 其他情况，根据吃后手牌数减1
            targetSizeAfterDiscard = afterChi.size() - 1;
            System.out.println("  非标准手牌数，目标手牌数: " + targetSizeAfterDiscard);
        }

        // 4. 尝试打每一张不同的牌
        Set<Integer> uniqueCards = new HashSet<>(afterChi);
        boolean foundTing = false;
        for (int discardCard : uniqueCards) {
            List<Integer> afterDiscard = new ArrayList<>(afterChi);
            afterDiscard.remove(Integer.valueOf(discardCard));
            Collections.sort(afterDiscard);

            int discardType = discardCard / 100;
            int discardValue = discardCard % 100;

            System.out.println("---打牌-----" + discardValue);

            System.out.print("\n    打" + discardValue + getTypeName(discardType) +
                    " → 剩余" + afterDiscard.size() + "张: " +
                    convertToReadable(afterDiscard));

            // 5. 检查打牌后是否能听牌
            boolean canTing = checkCanTing(afterDiscard, needs258, targetSizeAfterDiscard);
            if (canTing) {
                HuNanChangSha.isTinChi = true;
                ChangShaSuanFaTest.isChi=true;
                System.out.println(" ✓ 听牌！");
                foundTing = true;

                // 分析听牌详情
                analyzeTingDetails(afterDiscard, needs258);
            } else {
//                // 如果不能听牌，检查是否是好牌型
//                System.out.print(" [手牌分析中...]");
//
//                if (isGoodHandForTing(afterDiscard, needs258, targetSizeAfterDiscard)) {
//                    System.out.println(" ✓ 好牌型（接近听牌）");
//                    foundTing = true;
//                } else {
                System.out.println(" ✗ 不听");
//                }
            }
        }
        return foundTing;
    }

    /**
     * 检查手牌是否能听牌
     */
    public static boolean checkCanTing(List<Integer> hand, boolean needs258, int targetSize) {
        if (hand.size() != targetSize) {
            return false;
        }

        // 获取所有可能的牌
        Set<Integer> allCards = getAllCards();

        for (int testCard : allCards) {
            List<Integer> tempHand = new ArrayList<>(hand);
            tempHand.add(testCard);
            Collections.sort(tempHand);

            // 检查是否能胡牌
            if (canHu(tempHand, needs258)) {
                return true;
            }
        }

        return false;
    }

    /**
     * 检查手牌是否能胡牌（考虑258将要求）
     */
    public static boolean canHu(List<Integer> handCards, boolean needs258) {
        // 手牌排序
        List<Integer> sorted = new ArrayList<>(handCards);
        Collections.sort(sorted);

        // 胡牌时手牌数必须是3n+2
        if (sorted.size() % 3 != 2) {
            return false;
        }

        // 检查七对子（特殊胡牌）
        if (checkQiDuiZi(sorted)) {
            // 七对子不需要258将
            return true;
        }

        // 如果需要258将，检查普通胡牌（必须有258将）
        if (needs258) {
            return checkNormalHuWith258(sorted);
        } else {
            // 不需要258将，检查普通胡牌
            return checkNormalHu(sorted);
        }
    }

    /**
     * 分析听牌详情
     */
    public static void analyzeTingDetails(List<Integer> hand, boolean needs258) {

        Set<Integer> tingCards = new HashSet<>();
        Set<Integer> allCards = getAllCards();

        for (int testCard : allCards) {
            List<Integer> tempHand = new ArrayList<>(hand);
            tempHand.add(testCard);

            if (canHu(tempHand, needs258)) {
                tingCards.add(testCard);
            }
        }

        if (!tingCards.isEmpty()) {
            System.out.print("      听" + tingCards.size() + "张牌: ");
            List<String> tingCardStrs = new ArrayList<>();

            // 比较当前数量和上次数量
            if (tingCards.size() > lastTingCount) {
                isMoreThanLast = true;
//                System.out.print("(比上次多" + (tingCards.size() - lastTingCount) + "张) ");
            } else if (tingCards.size() < lastTingCount) {
//                System.out.print("(比上次少" + (lastTingCount - tingCards.size()) + "张) ");
            } else {
//                System.out.print("(与上次相同) ");
            }

            for (int card : tingCards) {
                int type = card / 100;
                int value = card % 100;
                tingCardStrs.add(value + getTypeName(type));

            }
            System.out.println(String.join(", ", tingCardStrs));

            // 更新上次听牌数量
            lastTingCount = tingCards.size();

            // 分析听牌类型
            analyzeTingType(tingCards);
        } else {
            System.out.println("      无听牌");
            // 比较当前数量和上次数量
            if (0 > lastTingCount) {
                isMoreThanLast = true;
            }
            // 更新上次听牌数量
            lastTingCount = 0;
        }

    }


    // 修改 analyzeTingType 方法以接收 Set<Integer>
    public static void analyzeTingType(Set<Integer> tingCards) {
        if (tingCards.size() == 1) {
            System.out.println("听牌类型: 单吊");
        } else if (tingCards.size() == 2) {
            List<Integer> tingList = new ArrayList<>(tingCards);
            int type1 = tingList.get(0) / 100;
            int type2 = tingList.get(1) / 100;
            if (type1 == type2) {
                System.out.println("听牌类型: 对倒");
            } else {
                System.out.println("听牌类型: 双面听");
            }
        } else if (tingCards.size() >= 3) {
            System.out.println("听牌类型: 多面听（" + tingCards.size() + "张）");
        }
    }

    /**
     * 检查手牌花色牌数是否>=10张
     */
    public static boolean checkSuitCount(List<Integer> hand) {
        // 统计万、筒、条各自的数量
        Map<Integer, Integer> suitCount = new HashMap<>();
        for (int card : hand) {
            int type = card / 100;
            if (type < 4) { // 只统计万筒条
                suitCount.put(type, suitCount.getOrDefault(type, 0) + 1);
            }
        }

        // 检查是否有某种花色>=10张
        for (int count : suitCount.values()) {
            if (count >= 10) {
                return true; // 有花色>=10张，不需要258将
            }
        }

        return false; // 没有花色>=10张，需要258将
    }

    /**
     * 检查七对子
     */
    public static boolean checkQiDuiZi(List<Integer> handCards) {
        if (handCards.size() != 14) return false;

        Map<Integer, Integer> countMap = new HashMap<>();
        for (int card : handCards) {
            countMap.put(card, countMap.getOrDefault(card, 0) + 1);
        }

        // 检查是否都是对子
        for (int count : countMap.values()) {
            if (count != 2) {
                return false;
            }
        }

        return true;
    }

    /**
     * 检查普通胡牌（必须有258将）
     */
    public static boolean checkNormalHuWith258(List<Integer> handCards) {
        // 尝试每种258作为将牌
        for (int card : handCards) {
            int value = card % 100;
            // 检查是否是258
            if (value == 2 || value == 5 || value == 8) {
                // 检查是否有至少2张相同的牌做将
                int count = Collections.frequency(handCards, card);
                if (count >= 2) {
                    // 移除将牌
                    List<Integer> remaining = new ArrayList<>(handCards);
                    for (int i = 0; i < 2; i++) {
                        remaining.remove(Integer.valueOf(card));
                    }

                    // 检查剩余牌是否能组成顺子/刻子
                    if (canGroup(remaining)) {
                        return true;
                    }
                }
            }
        }

        return false;
    }

    /**
     * 检查普通胡牌（不需要258将）
     */
    public static boolean checkNormalHu(List<Integer> handCards) {
        return checkNormalHuRecursive(new ArrayList<>(handCards), false);
    }

    public static boolean checkNormalHuRecursive(List<Integer> handCards, boolean hasJiang) {
        if (handCards.isEmpty()) {
            return true; // 所有牌都分组成功
        }

        Collections.sort(handCards);

        // 统计第一张牌的数量
        int firstCard = handCards.get(0);
        int count = Collections.frequency(handCards, firstCard);

        // 尝试作为刻子（三张相同）
        if (count >= 3) {
            List<Integer> remaining = new ArrayList<>(handCards);
            for (int i = 0; i < 3; i++) {
                remaining.remove(Integer.valueOf(firstCard));
            }
            if (checkNormalHuRecursive(remaining, hasJiang)) {
                return true;
            }
        }

        // 尝试作为顺子（三张连续）
        int type = firstCard / 100;
        int value = firstCard % 100;

        if (type < 4 && value <= 7) { // 字牌和8、9不能组成顺子
            int second = type * 100 + (value + 1);
            int third = type * 100 + (value + 2);

            if (handCards.contains(second) && handCards.contains(third)) {
                List<Integer> remaining = new ArrayList<>(handCards);
                remaining.remove(Integer.valueOf(firstCard));
                remaining.remove(Integer.valueOf(second));
                remaining.remove(Integer.valueOf(third));
                if (checkNormalHuRecursive(remaining, hasJiang)) {
                    return true;
                }
            }
        }

        // 尝试作为将（对子）- 只能有一个将
        if (!hasJiang && count >= 2) {
            List<Integer> remaining = new ArrayList<>(handCards);
            remaining.remove(Integer.valueOf(firstCard));
            remaining.remove(Integer.valueOf(firstCard));
            if (checkNormalHuRecursive(remaining, true)) {
                return true;
            }
        }

        return false;
    }

    /**
     * 检查牌是否能组成顺子或刻子
     */
    public static boolean canGroup(List<Integer> cards) {
        if (cards.isEmpty()) {
            return true; // 所有牌都分组成功
        }

        List<Integer> sorted = new ArrayList<>(cards);
        Collections.sort(sorted);

        int firstCard = sorted.get(0);
        int count = Collections.frequency(sorted, firstCard);

        // 尝试作为刻子（三张相同）
        if (count >= 3) {
            List<Integer> remaining = new ArrayList<>(sorted);
            for (int i = 0; i < 3; i++) {
                remaining.remove(Integer.valueOf(firstCard));
            }
            if (canGroup(remaining)) {
                return true;
            }
        }

        // 尝试作为顺子（三张连续）
        int type = firstCard / 100;
        int value = firstCard % 100;

        if (type < 4 && value <= 7) { // 字牌和8、9不能组成顺子
            int second = type * 100 + (value + 1);
            int third = type * 100 + (value + 2);

            if (sorted.contains(second) && sorted.contains(third)) {
                List<Integer> remaining = new ArrayList<>(sorted);
                remaining.remove(Integer.valueOf(firstCard));
                remaining.remove(Integer.valueOf(second));
                remaining.remove(Integer.valueOf(third));
                if (canGroup(remaining)) {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * 获取所有麻将牌
     */
    public static Set<Integer> getAllCards() {
        Set<Integer> allCards = new HashSet<>();
        // 万条筒 1-9
        for (int type = 1; type <= 3; type++) {
            for (int value = 1; value <= 9; value++) {
                allCards.add(type * 100 + value);
            }
        }
        return allCards;
    }

    /**
     * 转换为可读格式
     */
    public static String convertToReadable(List<Integer> cards) {
        StringBuilder sb = new StringBuilder();
        for (int card : cards) {
            int type = card / 100;
            int value = card % 100;
            sb.append(value).append(getTypeName(type)).append(" ");
        }
        return sb.toString();
    }

    /**
     * 获取牌型名称
     */
    public static String getTypeName(int type) {
        switch (type) {
            case 1:
                return "万";
            case 2:
                return "筒";
            case 3:
                return "条";
            default:
                return "字";
        }
    }


    public static boolean isMoreThanLast() {
        return isMoreThanLast;
    }
}
