import pandas as pd
import os
import shutil
from collections import OrderedDict

def copy_events(date_path, events, save_event):
    for event in events:
        try:
            # print('en', str(event))
            if str(event) != 'nan':
                event_path = os.path.join(date_path, str(event))
                save_event_ = os.path.join(save_event, str(event))
                print(f'copy {event_path} to {save_event_}')
                shutil.copytree(event_path, save_event_)
        except Exception as e:
            with open('error_events.txt', 'a') as f:
                f.write(f'{e}: {event}\n')

def replace_str(name):
    string_ = ['\n', '/']
    name_ = name
    for s in string_:
        if s in name:
            name_ = name.replace(s, '')
    return name_


def write_events(events, txt):
    with open(txt, 'a') as f:
        for event in events:
            if str(event) != 'nan':
                f.write(str(event) + '\n')
def anlay_xlsx_filter_events(file_path, name, ch='轨迹数', classFlag=False):

    # 读取 Excel 文件
    df = pd.read_excel(file_path)
    date_path = os.path.dirname(file_path)
    date = os.path.basename(date_path).replace('-', '')         #20250114

    # 获取表头名称
    # headers = df.columns.tolist()
    # print("表头名称：", headers)
    name_ = replace_str(name)
    if ch in name:
        ch_ = ch + '为空'
        # txt_path = os.path.join(date_path, date + '_' + ch_ + '.txt')
        txt_path = os.path.join(date_path, ch_ + '.txt')
        filter_df = df[(df[name].isnull())]

    else:
        # txt_path = os.path.join(date_path, date + '_' + name_ + '.txt')
        txt_path = os.path.join(date_path, name_ + '.txt')
        filter_df = df[(df[name].notna()) & (df['是否购物现场'].str.contains('是'))]
    try:

        if classFlag:
            filter_contents = filter_df[name].tolist()
            filter_contents_unique = list(set(filter_contents))
            for type_ in filter_contents_unique:
                temp_df = filter_df[filter_df[name] == type_]
                events = list(set(temp_df['事件名'].tolist()))
                if len(events) > 0:
                    '''复制事件文件夹到指定路径'''
                    # save_path_ = os.path.join(save_path, name_, type_)
                    # os.makedirs(save_path_, exist_ok=True)
                    # copy_events(date_path, events, save_path_)
                    '''将事件名称写入txt文件'''
                    write_events(events, txt_path)

        else:
            events = list(set(filter_df['事件名']))
            print('events: ', events)
            if len(events) > 0:
                '''复制事件文件夹到指定路径'''
                # save_path_ = os.path.join(save_path, name_)
                # os.makedirs(save_path_, exist_ok=True)
                # copy_events(date_path, events, save_path_)
                '''将事件名称写入txt文件'''
                write_events(events, txt_path)

    except Exception as e:
        with open(name_ + 'write_txt_error.txt', 'a') as f:
            f.write(f'{date_path}: {e}\n')


if __name__ == "__main__":
    # file_path = 'finish_data_test'
    file_path = '/home/yujia/yj/gpu_code/callback_data_test_0417/'
    xlsx_name = '现场回传数据分析表_all.xlsx'
    # events_save = os.path.join(file_path, 'events_class')
    '''
    title_list = ['barcode', '有无商品操作', '赠品', '散称', '私人物品', '大号购物袋', '遮挡/模糊', '单次/多次事件切分不准确', '复杂操作', '是否购物现场', '备注',
                  'algroStartToEnd', 'one2one', 'one2SN', 'one2n', '前摄轨迹数', '后摄轨迹数']
    '''


    title_names = ['赠品', '散称', '前摄轨迹数']        ##需筛选的表头标题名称
    ch = '轨迹数'    ##筛选出excel表格中前摄轨迹数为0的事件名称，这类事件需重新跑pipline填入轨迹数
    saveClass = False    ##是否按照列表内容分类保存，或将列表下非空的内容保存
    for title_name in title_names:
        for name in os.listdir(file_path):      ##人名
            # name_ = 'cxy'
            name_path = os.path.join(file_path, name)
            for date in os.listdir(name_path):      ##日期
                # date_ = '2025-02-04'
                date_path = os.path.join(name_path, date)
                data_xlsx = os.path.join(date_path, xlsx_name)
                anlay_xlsx_filter_events(data_xlsx, title_name, ch, saveClass)

        # break






