package com.fujica.abk.utils;

import com.fujica.abk.ResourceTable;
import com.fujica.abk.api.common;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.agp.window.dialog.CommonDialog;
import ohos.app.Context;

import java.util.ArrayList;
import java.util.List;

import static ohos.agp.components.Component.HIDE;
import static ohos.agp.components.Component.VISIBLE;

/**
 * 车牌输入对话框
 * 继承自CommonDialog，实现车牌输入功能
 */
public class LicensePlateInputDialog extends CommonDialog {
    private Context context;
    private Component rootLayout;
    
    // 车牌输入框
    private Text plateProvince;      // 省份
    private Text plateLetter;        // 字母
    private Text plateChar1, plateChar2, plateChar3, plateChar4, plateChar5;  // 5个字符
    private DirectionalLayout plateNewEnergy;  // 新能源选项
    private Text newEnergyText;
    private Text newEnergyPlusText;  // 新能源选项的+号
    
    // 特殊车牌输入
    private TextField specialPlateInput;
    private DirectionalLayout licensePlateInputArea;
    private Text btnSwitchSpecial;
    
    // 键盘相关
    private DirectionalLayout keyboardContainer;
    private DirectionalLayout chineseKeyboardLayout;
    private DirectionalLayout englishKeyboardLayout;
    
    // 键盘按钮列表（用于启用/禁用）
    private List<Button> chineseKeyboardButtons = new ArrayList<>();
    private List<Button> englishKeyboardButtons = new ArrayList<>();
    private List<KeyboardItem> chineseKeyboardItems = new ArrayList<>();
    private List<KeyboardItem> englishKeyboardItems = new ArrayList<>();
    
    // 确认按钮
    private Button btnConfirm;
    
    // 当前输入位置索引 (0-7: 省份、字母、5个字符、新能源)
    private int currentInputIndex = 0;
    
    // 车牌类型：0-常规，1-特殊
    private int plateType = 0;
    
    // 是否新能源
    private boolean isNewEnergy = false;
    
    // 车牌数据
    private String[] plateData = new String[8];  // 8个位置：省份、字母、5个字符、新能源
    
    // 回调接口
    public interface OnConfirmListener {
        void onConfirm(String licensePlate);
    }
    
    private OnConfirmListener confirmListener;
    
    /**
     * 键盘项数据类
     */
    private static class KeyboardItem {
        int id;
        String font;
        
        KeyboardItem(int id, String font) {
            this.id = id;
            this.font = font;
        }
    }
    
    /**
     * 构造函数
     */
    public LicensePlateInputDialog(Context context) {
        super(context);
        this.context = context;
        initKeyboardData();
        initDialog();
    }
    
    /**
     * 初始化对话框
     */
    private void initDialog() {
        // 设置对话框属性
        setAutoClosable(true);
        setCornerRadius(ScreenUtil.vp2px(context, 20));
        
        // 加载布局
        rootLayout = LayoutScatter.getInstance(context)
                .parse(ResourceTable.Layout_layout_license_plate_dialog, null, false);
        setContentCustomComponent(rootLayout);
        
        // 初始化视图
        initViews();
        
        // 设置监听器
        setupListeners();
        
        // 初始化车牌数据
        initPlateData();
        
        // 显示常规车牌输入
        showNormalPlateInput();
        
        // 初始化时聚焦第一个输入框
        currentInputIndex = 0;
        updateInputFocus();
        showChineseKeyboard();
    }
    
    /**
     * 初始化键盘数据
     */
    private void initKeyboardData() {
        // 中文键盘（省份）- 按照截图布局：4行，每行10个
        // 第1行：京、津、冀、鲁、晋、蒙、辽、吉、黑、沪
        String[] row1 = {"京", "津", "冀", "鲁", "晋", "蒙", "辽", "吉", "黑", "沪"};
        int[] row1Ids = {1, 4, 5, 16, 6, 7, 8, 9, 10, 2};
        for (int i = 0; i < row1.length; i++) {
            chineseKeyboardItems.add(new KeyboardItem(row1Ids[i], row1[i]));
        }
        // 第2行：苏、浙、皖、闽、赣、豫、鄂、湘、粤、桂
        String[] row2 = {"苏", "浙", "皖", "闽", "赣", "豫", "鄂", "湘", "粤", "桂"};
        int[] row2Ids = {11, 12, 13, 14, 15, 17, 18, 19, 3, 20};
        for (int i = 0; i < row2.length; i++) {
            chineseKeyboardItems.add(new KeyboardItem(row2Ids[i], row2[i]));
        }
        // 第3行：琼、渝、川、贵、云、藏、陕、甘、青、宁
        String[] row3 = {"琼", "渝", "川", "贵", "云", "藏", "陕", "甘", "青", "宁"};
        int[] row3Ids = {21, 22, 23, 24, 25, 26, 27, 28, 29, 30};
        for (int i = 0; i < row3.length; i++) {
            chineseKeyboardItems.add(new KeyboardItem(row3Ids[i], row3[i]));
        }
        // 第4行：新、虚、M、删除
        String[] row4 = {"新", "虚", "M", ""};
        int[] row4Ids = {31, 32, 34, 33};
        for (int i = 0; i < row4.length; i++) {
            chineseKeyboardItems.add(new KeyboardItem(row4Ids[i], row4[i]));
        }
        
        // 英文键盘（字母和数字）- 按照截图布局
        // 第1行：1、2、3、4、5、6、7、8、9、0
        String[] engRow1 = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "0"};
        int[] engRow1Ids = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        for (int i = 0; i < engRow1.length; i++) {
            englishKeyboardItems.add(new KeyboardItem(engRow1Ids[i], engRow1[i]));
        }
        // 第2行：Q、W、E、R、T、Y、U、O、P、港
        String[] engRow2 = {"Q", "W", "E", "R", "T", "Y", "U", "O", "P", "港"};
        int[] engRow2Ids = {25, 31, 15, 26, 28, 41, 29, 40, 24, 35};
        for (int i = 0; i < engRow2.length; i++) {
            englishKeyboardItems.add(new KeyboardItem(engRow2Ids[i], engRow2[i]));
        }
        // 第3行：A、S、D、F、G、H、J、K、L、澳
        String[] engRow3 = {"A", "S", "D", "F", "G", "H", "J", "K", "L", "澳"};
        int[] engRow3Ids = {11, 27, 14, 16, 17, 18, 19, 20, 21, 36};
        for (int i = 0; i < engRow3.length; i++) {
            englishKeyboardItems.add(new KeyboardItem(engRow3Ids[i], engRow3[i]));
        }
        // 第4行：Z、X、C、V、B、N、M、学、领、删除
        String[] engRow4 = {"Z", "X", "C", "V", "B", "N", "M", "学", "领", ""};
        int[] engRow4Ids = {34, 32, 13, 30, 12, 23, 22, 37, 39, 38};
        for (int i = 0; i < engRow4.length; i++) {
            englishKeyboardItems.add(new KeyboardItem(engRow4Ids[i], engRow4[i]));
        }
    }
    
    /**
     * 初始化视图
     */
    private void initViews() {
        // 标题栏
        Image btnClose = (Image) rootLayout.findComponentById(ResourceTable.Id_btn_close);
        if (btnClose != null) {
            btnClose.setClickedListener(component -> hide());
        }
        
        // 车牌输入框
        plateProvince = (Text) rootLayout.findComponentById(ResourceTable.Id_plate_province);
        plateLetter = (Text) rootLayout.findComponentById(ResourceTable.Id_plate_letter);
        plateChar1 = (Text) rootLayout.findComponentById(ResourceTable.Id_plate_char1);
        plateChar2 = (Text) rootLayout.findComponentById(ResourceTable.Id_plate_char2);
        plateChar3 = (Text) rootLayout.findComponentById(ResourceTable.Id_plate_char3);
        plateChar4 = (Text) rootLayout.findComponentById(ResourceTable.Id_plate_char4);
        plateChar5 = (Text) rootLayout.findComponentById(ResourceTable.Id_plate_char5);
        plateNewEnergy = (DirectionalLayout) rootLayout.findComponentById(ResourceTable.Id_plate_new_energy);
        newEnergyText = (Text) rootLayout.findComponentById(ResourceTable.Id_new_energy_text);
        // 获取+号文本（plateNewEnergy的第一个子组件）
        if (plateNewEnergy != null && plateNewEnergy.getChildCount() > 0) {
            Component firstChild = plateNewEnergy.getComponentAt(0);
            if (firstChild instanceof Text) {
                newEnergyPlusText = (Text) firstChild;
            }
        }
        
        // 特殊车牌
        specialPlateInput = rootLayout.findComponentById(ResourceTable.Id_special_plate_input);
        licensePlateInputArea = rootLayout.findComponentById(ResourceTable.Id_license_plate_input_area);
        btnSwitchSpecial = rootLayout.findComponentById(ResourceTable.Id_btn_switch_special);
        
        // 键盘
        keyboardContainer = rootLayout.findComponentById(ResourceTable.Id_keyboard_container);
        chineseKeyboardLayout = rootLayout.findComponentById(ResourceTable.Id_chinese_keyboard);
        englishKeyboardLayout = rootLayout.findComponentById(ResourceTable.Id_english_keyboard);
        
        // 确认按钮
        btnConfirm = (Button) rootLayout.findComponentById(ResourceTable.Id_btn_confirm);
        
        // 初始化键盘（创建所有按钮）
        initKeyboards();
    }
    
    /**
     * 设置监听器
     */
    private void setupListeners() {
        // 切换特殊车牌
        if (btnSwitchSpecial != null) {
            btnSwitchSpecial.setClickedListener(component -> {
                plateType = (plateType + 1) % 2;
                if (plateType == 0) {
                    showNormalPlateInput();
                    btnSwitchSpecial.setText("切换特殊车牌");
                    // 显示键盘
                    currentInputIndex = 0;
                    updateInputFocus();
                    showChineseKeyboard();
                } else {
                    showSpecialPlateInput();
                    btnSwitchSpecial.setText("切换常规车牌");
                    // 隐藏键盘
                    hideKeyboard();
                }
            });
        }
        
        // 确认按钮
        if (btnConfirm != null) {
            btnConfirm.setClickedListener(component -> {
                String licensePlate = getLicensePlate();
                if (licensePlate != null && !licensePlate.isEmpty()) {
                    common.updateDefaultPlateNo(context, licensePlate);
                    if (confirmListener != null) {
                        confirmListener.onConfirm(licensePlate);
                    }
                    hide();
                }
            });
        }
        
        // 车牌输入框点击事件
        setupPlateInputListeners();
    }
    
    /**
     * 设置车牌输入框点击监听
     */
    private void setupPlateInputListeners() {
        if (plateProvince != null) {
            plateProvince.setClickedListener(component -> {
                currentInputIndex = 0;
                updateInputFocus();
                showChineseKeyboard();
            });
        }

        if (plateLetter != null) {
            plateLetter.setClickedListener(component -> {
                currentInputIndex = 1;
                updateInputFocus();
                showEnglishKeyboard();
            });
        }
        
        if (plateChar1 != null) {
            plateChar1.setClickedListener(component -> {
                currentInputIndex = 2;
                updateInputFocus();
                showEnglishKeyboard();
            });
        }
        
        if (plateChar2 != null) {
            plateChar2.setClickedListener(component -> {
                currentInputIndex = 3;
                updateInputFocus();
                showEnglishKeyboard();
            });
        }
        
        if (plateChar3 != null) {
            plateChar3.setClickedListener(component -> {
                currentInputIndex = 4;
                updateInputFocus();
                showEnglishKeyboard();
            });
        }
        
        if (plateChar4 != null) {
            plateChar4.setClickedListener(component -> {
                currentInputIndex = 5;
                updateInputFocus();
                showEnglishKeyboard();
            });
        }
        
        if (plateChar5 != null) {
            plateChar5.setClickedListener(component -> {
                currentInputIndex = 6;
                updateInputFocus();
                showEnglishKeyboard();
            });
        }
        
        if (plateNewEnergy != null) {
            plateNewEnergy.setClickedListener(component -> {
                currentInputIndex = 7;
                updateInputFocus();
                showEnglishKeyboard();
            });
        }
    }
    
    /**
     * 初始化车牌数据
     */
    private void initPlateData() {
        plateData[0] = "粤";  // 默认省份
        plateData[1] = "B";   // 默认字母
        for (int i = 2; i < 7; i++) {
            plateData[i] = "";
        }
        plateData[7] = "新能源";
        updatePlateDisplay();
    }
    
    /**
     * 更新车牌显示
     */
    private void updatePlateDisplay() {
        if (plateProvince != null) plateProvince.setText(plateData[0] != null ? plateData[0] : "");
        if (plateLetter != null) plateLetter.setText(plateData[1] != null ? plateData[1] : "");
        if (plateChar1 != null) plateChar1.setText(plateData[2] != null ? plateData[2] : "");
        if (plateChar2 != null) plateChar2.setText(plateData[3] != null ? plateData[3] : "");
        if (plateChar3 != null) plateChar3.setText(plateData[4] != null ? plateData[4] : "");
        if (plateChar4 != null) plateChar4.setText(plateData[5] != null ? plateData[5] : "");
        if (plateChar5 != null) plateChar5.setText(plateData[6] != null ? plateData[6] : "");
        
        // 更新新能源显示
        if (newEnergyText != null) {
            if (plateData[7] != null && !plateData[7].isEmpty() && !plateData[7].equals("新能源")) {
                // 如果有输入字符，显示输入的字符，隐藏+号，使用正常颜色和大小
                newEnergyText.setText(plateData[7]);
                newEnergyText.setTextSize(ScreenUtil.fp2px(context, 16));  // 正常大小
                // 如果当前聚焦在第8个位置，文字颜色为白色；否则为黑色
                if (currentInputIndex == 7) {
                    newEnergyText.setTextColor(Color.WHITE);
                } else {
                    newEnergyText.setTextColor(new Color(0xFF000000));  // 黑色
                }
                // 隐藏+号
                if (newEnergyPlusText != null) {
                    newEnergyPlusText.setVisibility(HIDE);
                }
            } else {
                // 没有输入时，显示默认样式
                if (isNewEnergy) {
                    // 如果是新能源状态，显示空
                    newEnergyText.setText("");
                } else {
                    // 默认显示"新能源"
                    newEnergyText.setText("新能源");
                }
                newEnergyText.setTextColor(new Color(0xFF999999));  // 灰色
                newEnergyText.setTextSize(ScreenUtil.fp2px(context, 10));  // 小字体
                // 显示+号
                if (newEnergyPlusText != null) {
                    newEnergyPlusText.setVisibility(VISIBLE);
                }
            }
        }
    }
    
    /**
     * 显示常规车牌输入
     */
    private void showNormalPlateInput() {
        if (licensePlateInputArea != null) {
            licensePlateInputArea.setVisibility(VISIBLE);
        }
        if (specialPlateInput != null) {
            specialPlateInput.setVisibility(HIDE);
        }
    }
    
    /**
     * 显示特殊车牌输入
     */
    private void showSpecialPlateInput() {
        if (licensePlateInputArea != null) {
            licensePlateInputArea.setVisibility(HIDE);
        }
        if (specialPlateInput != null) {
            specialPlateInput.setVisibility(VISIBLE);
        }
        hideKeyboard();
    }
    
    /**
     * 初始化键盘（创建所有按钮）
     */
    private void initKeyboards() {
        // 初始化中文键盘
        initChineseKeyboard();
        // 初始化英文键盘
        initEnglishKeyboard();
    }
    
    /**
     * 初始化中文键盘
     */
    private void initChineseKeyboard() {
        if (chineseKeyboardLayout == null) return;
        chineseKeyboardLayout.removeAllComponents();
        chineseKeyboardButtons.clear();
        
        int itemsPerRow = 10;
        DirectionalLayout currentRow = null;
        int itemCount = 0;
        
        for (KeyboardItem item : chineseKeyboardItems) {
            if (itemCount % itemsPerRow == 0) {
                currentRow = new DirectionalLayout(context);
                currentRow.setOrientation(Component.HORIZONTAL);
                ComponentContainer.LayoutConfig rowConfig = new ComponentContainer.LayoutConfig(
                        ComponentContainer.LayoutConfig.MATCH_PARENT,
                        ComponentContainer.LayoutConfig.MATCH_CONTENT);
                currentRow.setLayoutConfig(rowConfig);
                chineseKeyboardLayout.addComponent(currentRow);
            }
            
            Button btn = createKeyboardButton(item, true);
            chineseKeyboardButtons.add(btn);
            
            if (currentRow != null) {
                currentRow.addComponent(btn);
            }
            
            itemCount++;
        }
    }
    
    /**
     * 初始化英文键盘
     */
    private void initEnglishKeyboard() {
        if (englishKeyboardLayout == null) return;
        englishKeyboardLayout.removeAllComponents();
        englishKeyboardButtons.clear();
        
        int itemsPerRow = 10;
        DirectionalLayout currentRow = null;
        int itemCount = 0;
        
        for (KeyboardItem item : englishKeyboardItems) {
            if (itemCount % itemsPerRow == 0) {
                currentRow = new DirectionalLayout(context);
                currentRow.setOrientation(Component.HORIZONTAL);
                ComponentContainer.LayoutConfig rowConfig = new ComponentContainer.LayoutConfig(
                        ComponentContainer.LayoutConfig.MATCH_PARENT,
                        ComponentContainer.LayoutConfig.MATCH_CONTENT);
                currentRow.setLayoutConfig(rowConfig);
                englishKeyboardLayout.addComponent(currentRow);
            }
            
            Button btn = createKeyboardButton(item, false);
            englishKeyboardButtons.add(btn);
            
            if (currentRow != null) {
                currentRow.addComponent(btn);
            }
            
            itemCount++;
        }
    }
    
    /**
     * 创建键盘按钮
     */
    private Button createKeyboardButton(KeyboardItem item, boolean isChinese) {
        Button btn = new Button(context);
        if (item.font.isEmpty()) {
            // 删除按钮
            btn.setText("删除");
        } else {
            btn.setText(item.font);
        }
        btn.setTextSize(ScreenUtil.fp2px(context, 20));  // 增大字体
        
        // 设置按钮样式
        ShapeElement background = new ShapeElement();
        background.setShape(ShapeElement.RECTANGLE);
        background.setRgbColor(new RgbColor(255, 255, 255));
        background.setCornerRadius(ScreenUtil.vp2px(context, 6));
        btn.setBackground(background);
        btn.setTextColor(new Color(0xFF333333));
        
        // 设置按钮尺寸和布局参数（增大按钮）
        DirectionalLayout.LayoutConfig layoutConfig = new DirectionalLayout.LayoutConfig(
                0,
                ComponentContainer.LayoutConfig.MATCH_CONTENT);
        layoutConfig.width = 0;
        layoutConfig.weight = 1;
        layoutConfig.height = ScreenUtil.vp2px(context, 50);  // 增大高度到50vp
        layoutConfig.setMarginLeft(ScreenUtil.vp2px(context, 4));
        layoutConfig.setMarginRight(ScreenUtil.vp2px(context, 4));
        layoutConfig.setMarginTop(ScreenUtil.vp2px(context, 4));
        layoutConfig.setMarginBottom(ScreenUtil.vp2px(context, 4));
        btn.setLayoutConfig(layoutConfig);
        
        // 设置点击事件
        btn.setClickedListener(component -> onKeyboardItemClick(item));
        
        return btn;
    }
    
    /**
     * 显示中文键盘
     */
    private void showChineseKeyboard() {
        if (keyboardContainer == null || chineseKeyboardLayout == null || englishKeyboardLayout == null) return;
        
        keyboardContainer.setVisibility(VISIBLE);
        chineseKeyboardLayout.setVisibility(VISIBLE);
        englishKeyboardLayout.setVisibility(HIDE);
        
        // 更新按钮状态
        updateKeyboardButtonsState();
    }
    
    /**
     * 显示英文键盘
     */
    private void showEnglishKeyboard() {
        if (keyboardContainer == null || chineseKeyboardLayout == null || englishKeyboardLayout == null) return;
        
        keyboardContainer.setVisibility(VISIBLE);
        chineseKeyboardLayout.setVisibility(HIDE);
        englishKeyboardLayout.setVisibility(VISIBLE);
        
        // 更新按钮状态
        updateKeyboardButtonsState();
    }
    
    /**
     * 更新键盘按钮状态（根据当前输入索引启用/禁用按钮）
     */
    private void updateKeyboardButtonsState() {
        // 更新中文键盘按钮状态
        for (int i = 0; i < chineseKeyboardButtons.size() && i < chineseKeyboardItems.size(); i++) {
            Button btn = chineseKeyboardButtons.get(i);
            KeyboardItem item = chineseKeyboardItems.get(i);
            boolean enabled = isButtonEnabled(item, true);
            btn.setEnabled(enabled);
            
            // 更新按钮样式（禁用时置灰）
            ShapeElement background = new ShapeElement();
            background.setShape(ShapeElement.RECTANGLE);
            background.setCornerRadius(ScreenUtil.vp2px(context, 6));
            if (enabled) {
                background.setRgbColor(new RgbColor(255, 255, 255));
                btn.setTextColor(new Color(0xFF333333));
            } else {
                background.setRgbColor(new RgbColor(192, 192, 192));
                btn.setTextColor(new Color(0xFF666666));
            }
            btn.setBackground(background);
        }
        
        // 更新英文键盘按钮状态
        for (int i = 0; i < englishKeyboardButtons.size() && i < englishKeyboardItems.size(); i++) {
            Button btn = englishKeyboardButtons.get(i);
            KeyboardItem item = englishKeyboardItems.get(i);
            boolean enabled = isButtonEnabled(item, false);
            btn.setEnabled(enabled);
            
            // 更新按钮样式（禁用时置灰）
            ShapeElement background = new ShapeElement();
            background.setShape(ShapeElement.RECTANGLE);
            background.setCornerRadius(ScreenUtil.vp2px(context, 6));
            if (enabled) {
                background.setRgbColor(new RgbColor(255, 255, 255));
                btn.setTextColor(new Color(0xFF333333));
            } else {
                background.setRgbColor(new RgbColor(192, 192, 192));
                btn.setTextColor(new Color(0xFF666666));
            }
            btn.setBackground(background);
        }
    }
    
    /**
     * 判断按钮是否可用
     */
    private boolean isButtonEnabled(KeyboardItem item, boolean isChinese) {
        // 删除按钮始终可用
        if (item.id == 33 || item.id == 38) {
            return true;
        }
        
        // 根据当前输入索引判断
        if (currentInputIndex == 0) {
            // 省份输入：只显示中文键盘
            return isChinese;
        } else if (currentInputIndex == 1) {
            // 字母输入：只显示英文键盘
            if (!isChinese) {
                // 如果首位是M，第二位只能是数字
                if (plateData[0] != null && plateData[0].equals("M")) {
                    return item.id >= 1 && item.id <= 10;
                }
                // 如果首位是虚，第二位只能是数字
                if (plateData[0] != null && plateData[0].equals("虚")) {
                    return item.id >= 1 && item.id <= 10;
                }
                // 禁用数字 0-9（ID: 1-10）
                if (item.id >= 1 && item.id <= 10) {
                    return false;
                }
                // 字母O只能在第二位使用
                if (item.id == 40) {  // O
                    return true;
                }
                // 港澳学领只能在第六位使用
                if (item.id == 35 || item.id == 36 || item.id == 37 || item.id == 39) {
                    return false;
                }
                return true;
            }
            return false;
        } else if (currentInputIndex >= 2 && currentInputIndex <= 6) {
            // 字符输入：只显示英文键盘
            if (!isChinese) {
                // 港澳学领只能在第六位使用
                if (item.id == 35 || item.id == 36 || item.id == 37 || item.id == 39) {
                    return currentInputIndex == 6;
                }
                // 字母O不能在第二位之后使用
                if (item.id == 40) {
                    return false;
                }
                return true;
            }
            return false;
        } else if (currentInputIndex == 7) {
            // 新能源选项：显示英文键盘，禁用规则与第6个位置相同
            if (!isChinese) {
                // 港澳学领只能在第六位使用（第8个位置不能使用）
                if (item.id == 35 || item.id == 36 || item.id == 37 || item.id == 39) {
                    return false;
                }
                // 字母O不能在第二位之后使用
                if (item.id == 40) {
                    return false;
                }
                return true;
            }
            return false;
        }
        
        return true;
    }
    
    /**
     * 键盘项点击事件
     */
    private void onKeyboardItemClick(KeyboardItem item) {
        if (!isButtonEnabled(item, currentInputIndex == 0)) {
            return;  // 按钮被禁用，不处理
        }
        
        if (item.id == 33 || item.id == 38) {
            // 删除按钮
            handleDelete();
        } else {
            // 输入字符
            handleInput(item.font);
        }
        updatePlateDisplay();
        updateInputFocus();
        // 更新键盘按钮状态
        updateKeyboardButtonsState();
    }
    
    /**
     * 处理输入
     */
    private void handleInput(String value) {
        if (currentInputIndex < 0 || currentInputIndex >= 8) return;
        
        if (currentInputIndex == 7) {
            // 第8个位置：允许输入字符
            plateData[currentInputIndex] = value;
            // 输入后失去聚焦并隐藏键盘
            currentInputIndex = -1;  // 设置为无效值，表示失去聚焦
            hideKeyboard();
        } else {
            plateData[currentInputIndex] = value;
            // 自动移动到下一个输入框
            if (currentInputIndex < 6) {
                currentInputIndex++;
                // 根据位置决定显示哪个键盘
                if (currentInputIndex == 0) {
                    showChineseKeyboard();
                } else if (currentInputIndex == 7) {
                    // 第8个位置，显示英文键盘
                    showEnglishKeyboard();
                } else {
                    showEnglishKeyboard();
                }
            } else if (currentInputIndex == 6) {
                // 第7个字符输入后，隐藏键盘，不聚焦到第8个位置
                currentInputIndex = -1;  // 设置为无效值，表示失去聚焦
                hideKeyboard();
            }
        }
    }
    
    /**
     * 处理删除
     */
    private void handleDelete() {
        if (currentInputIndex == 0) {
            // 删除省份
            plateData[0] = "";
        } else if (currentInputIndex > 0 && currentInputIndex < 7) {
            // 删除当前字符，并移动到前一个输入框
            plateData[currentInputIndex] = "";
            currentInputIndex--;
            // 根据位置决定显示哪个键盘
            if (currentInputIndex == 0) {
                showChineseKeyboard();
            } else if (currentInputIndex > 0) {
                showEnglishKeyboard();
            }
        } else if (currentInputIndex == 7) {
            // 第8个位置：删除字符，如果为空则移动到前一个位置
            if (plateData[7] != null && !plateData[7].isEmpty()) {
                plateData[7] = "";
            } else {
                // 如果已经为空，移动到前一个位置
                currentInputIndex = 6;
                showEnglishKeyboard();
            }
        }
    }
    
    /**
     * 切换新能源
     */
    private void toggleNewEnergy() {
        isNewEnergy = !isNewEnergy;
        if (isNewEnergy) {
            plateData[7] = "";
        } else {
            plateData[7] = "新能源";
        }
        hideKeyboard();
    }
    
    /**
     * 更新输入框焦点样式
     */
    private void updateInputFocus() {
        // 清除所有焦点样式
        clearInputFocus();
        
        // 设置当前输入框焦点样式
        if (currentInputIndex == 7) {
            // 第8个位置：plateNewEnergy (DirectionalLayout)
            if (plateNewEnergy != null) {
                ShapeElement background = new ShapeElement();
                background.setShape(ShapeElement.RECTANGLE);
                background.setRgbColor(new RgbColor(0xFA, 0x63, 0x32));
                background.setCornerRadius(ScreenUtil.vp2px(context, 5));
                plateNewEnergy.setBackground(background);
                // 聚焦后，无论有没有值，字体都是白色
                if (newEnergyText != null) {
                    newEnergyText.setTextColor(Color.WHITE);
                }
            }
        } else {
            // 其他位置：Text 组件
            Text currentInput = getInputByIndex(currentInputIndex);
            if (currentInput != null) {
                ShapeElement background = new ShapeElement();
                background.setShape(ShapeElement.RECTANGLE);
                background.setRgbColor(new RgbColor(0xFA, 0x63, 0x32));
                background.setCornerRadius(ScreenUtil.vp2px(context, 5));
                currentInput.setBackground(background);
                currentInput.setTextColor(Color.WHITE);
            }
        }
    }
    
    /**
     * 清除所有输入框焦点样式
     */
    private void clearInputFocus() {
        Text[] inputs = {plateProvince, plateLetter, plateChar1, plateChar2, 
                        plateChar3, plateChar4, plateChar5};
        for (Text input : inputs) {
            if (input != null) {
                ShapeElement background = new ShapeElement();
                background.setShape(ShapeElement.RECTANGLE);
                background.setRgbColor(new RgbColor(0xE2, 0xE2, 0xE2));
                background.setCornerRadius(ScreenUtil.vp2px(context, 5));
                input.setBackground(background);
                input.setTextColor(new Color(0xFF333333));
            }
        }
        // 清除第8个位置的焦点样式
        if (plateNewEnergy != null) {
            ShapeElement background = new ShapeElement();
            background.setShape(ShapeElement.RECTANGLE);
            background.setRgbColor(new RgbColor(0xE2, 0xE2, 0xE2));
            background.setCornerRadius(ScreenUtil.vp2px(context, 5));
            plateNewEnergy.setBackground(background);
        }
    }
    
    /**
     * 根据索引获取输入框
     */
    private Text getInputByIndex(int index) {
        switch (index) {
            case 0: return plateProvince;
            case 1: return plateLetter;
            case 2: return plateChar1;
            case 3: return plateChar2;
            case 4: return plateChar3;
            case 5: return plateChar4;
            case 6: return plateChar5;
            default: return null;
        }
    }
    
    /**
     * 隐藏键盘
     */
    private void hideKeyboard() {
        if (keyboardContainer != null) {
            keyboardContainer.setVisibility(HIDE);
        }
        if (chineseKeyboardLayout != null) {
            chineseKeyboardLayout.setVisibility(HIDE);
        }
        if (englishKeyboardLayout != null) {
            englishKeyboardLayout.setVisibility(HIDE);
        }
    }
    
    /**
     * 获取车牌号
     */
    private String getLicensePlate() {
        if (plateType == 1) {
            // 特殊车牌
            if (specialPlateInput != null) {
                return specialPlateInput.getText();
            }
            return "";
        } else {
            // 常规车牌
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < 7; i++) {
                if (plateData[i] != null && !plateData[i].isEmpty()) {
                    sb.append(plateData[i]);
                }
            }
            return sb.toString();
        }
    }
    
    /**
     * 设置确认监听器
     */
    public void setOnConfirmListener(OnConfirmListener listener) {
        this.confirmListener = listener;
    }
}

