#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""条码映射编辑模块"""

from tkinter import messagebox

from app.core.excel.converter import UnitConverter
from app.core.utils.dialog_utils import show_barcode_mapping_dialog

from app.ui.logging_ui import add_to_log


def edit_barcode_mappings(log_widget):
    """编辑条码映射配置"""
    try:
        add_to_log(log_widget, "正在加载条码映射配置...\n", "info")

        unit_converter = UnitConverter()

        current_mappings = unit_converter.special_barcodes

        def save_mappings(new_mappings):
            success = unit_converter.update_barcode_mappings(new_mappings)
            if success:
                add_to_log(log_widget, f"成功保存条码映射配置，共{len(new_mappings)}项\n", "success")
            else:
                add_to_log(log_widget, "保存条码映射配置失败\n", "error")

        show_barcode_mapping_dialog(None, save_mappings, current_mappings)

    except Exception as e:
        add_to_log(log_widget, f"编辑条码映射时出错: {str(e)}\n", "error")
        messagebox.showerror("错误", f"编辑条码映射时出错: {str(e)}")
