#!/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import print_function
import pandas as pd
import json
import os
import argparse
import sys
import subprocess

# 检查Python版本
if sys.version_info[0] < 3:
    reload(sys)
    sys.setdefaultencoding('utf-8')

# 定义列映射 - 兼容中文和英文 Excel 文件
column_mapping = {
    # 中文列名映射
    u"事件编码": "eventCode",
    u"事件信息": "eventInfo", 
    u"事件类别": "eventCategory",
    u"周期/触发": "period",
    u"事件级别": "event",
    u"事件操作对象": "operator",
    u"事件记录结果信息编码": "functionCode",
    u"事件内容概述": "FunctionDescr",
    u"事件追加信息": "addDescr",
    # 英文列名映射
    u"eventCode": "eventCode",
    u"eventInfo": "eventInfo", 
    u"eventCategory": "eventCategory",
    u"period/trig": "period",
    u"event": "event",
    u"operator": "operator",
    u"functionCode": "functionCode",
    u"FunctionDescr": "FunctionDescr",
    u"addDescr": "addDescr"
}

def read_json(file_path):
    """读取 JSON 文件"""
    with open(file_path, "r") as file:
        data = json.load(file)
    return data

def write_json(data, file_path):
    """写入 JSON 文件"""
    with open(file_path, "w") as file:
        json.dump(data, file, indent=4, ensure_ascii=False)

def process_event(event):
    """处理单个事件信息"""
    print(event)  # 打印事件内容
    for key, value in event.items():
        if value is None:
            event[key] = ""
        if isinstance(value, basestring):
            event[key] = value.strip()
    
    # 处理period字段转换
    if 'period' in event:
        period_value = event['period']
        if period_value == "period" or period_value == "周期":
            event['period'] = 1
        elif period_value == "trig" or period_value == "触发":
            event['period'] = 0
    
    return event

def excel_to_json(input_file, output_file):
    """将Excel转换为JSON格式的事件定义文件"""
    
    # 检查输入文件是否存在
    if not os.path.exists(input_file):
        print(u"文件 {} 不存在".format(input_file))
        return False

    try:
        # 读取Excel文件
        wb = pd.read_excel(input_file)
        
        # 打印列名以进行调试
        print(u"Excel文件列名:")
        wb.columns = wb.iloc[0]
        wb = wb[1:]
        for col in wb.columns:
            print(u"  - {}".format(col))
        
        # 尝试找到正确的列映射
        actual_mapping = {}
        for chinese_col, english_col in column_mapping.items():
            # 尝试精确匹配
            if chinese_col in wb.columns:
                actual_mapping[chinese_col] = english_col
                print(u"映射列: {} -> {}".format(chinese_col, english_col))
            else:
                # 尝试部分匹配
                for actual_col in wb.columns:
                    if isinstance(actual_col, (list, dict)) and chinese_col in actual_col:
                        actual_mapping[actual_col] = english_col
                        print(u"映射列: {} -> {} (通过部分匹配)".format(actual_col, english_col))
                        break
        # 重命名列
        if actual_mapping:
            df = wb.rename(columns=actual_mapping)
        else:
            print(u"警告: 无法映射列名，尝试使用原始列名")
            df = wb.copy()
        
        # 检查是否有eventCode列
        if 'eventCode' not in df.columns:
            print(u"错误: 找不到eventCode列")
            print(u"可用列名:")
            for col in df.columns:
                print(u"  - {}".format(col))
            return False
        
        # 筛选有效的eventCode
        df = df[pd.to_numeric(df['eventCode'], errors='coerce').notnull()]
        df['eventCode'] = df['eventCode'].astype(int)
        
        # 如果有functionCode列，处理方式与eventCode一致
        if 'functionCode' in df.columns:
            df['functionCode'] = df['functionCode']  # 移除astype(str)，确保与eventCode一致
        
        # 转换为 JSON
        estr = df.to_json(orient="records")
        events = json.loads(estr)
        
        # 处理事件信息
        events = [process_event(event) for event in events]
        
        # 组织数据格式
        result = {
            "event_tmplate": events
        }
        
        # 确保输出目录存在
        output_dir = os.path.dirname(output_file)
        if output_dir and not os.path.exists(output_dir):
            os.makedirs(output_dir)
        
        # 写入 JSON 文件
        write_json(result, output_file)
        print(u"事件定义文件已生成: {}".format(output_file))
        print(u"共处理 {} 条事件记录".format(len(events)))
        
        # 检测是否为英文 Excel 文件
        is_english = any(col in df.columns for col in ["eventCode", "eventInfo", "eventCategory"])
        if is_english:
            # 调用 generate_event_h_from_json.py
            generate_script = os.path.join(os.path.dirname(__file__), "generate_event_h_from_json.py")
            output_h_file = os.path.join(os.path.dirname(output_file), "event_codes.h")
            subprocess.call(["python", generate_script, "--input", output_file, "--output", output_h_file])
            print(u"已生成头文件: {}".format(output_h_file))
        
        return True
        
    except Exception as e:
        print(u"处理Excel文件时出错: {}".format(str(e)))
        import traceback
        traceback.print_exc()
        return False

def main():
    parser = argparse.ArgumentParser(description='将Excel转换为JSON格式的事件定义文件')
    parser.add_argument('input_file', help='输入Excel文件路径')
    parser.add_argument('output_file', help='输出JSON文件路径')
    
    args = parser.parse_args()
    
    # 生成JSON文件
    excel_to_json(args.input_file, args.output_file)

if __name__ == "__main__":
    main()