# from openpyxl import load_workbook,Workbook
import csv,os
import pandas as pd

class SaveCsv():
    def __init__(self, file):
        self.file=file

    def read_to_df(self)-> pd.DataFrame:
        df = pd.read_csv(self.file)
        return df
    
    def append_row(self,row_to_append):
        '''
        # 要追加的数据
        row_to_append = ["John", 28, "Engineer"]
        '''
        with open(self.file, "a", newline="") as file:
            writer = csv.writer(file)
            # 写入一行数据
            writer.writerow(row_to_append)
    
class SaveCsvHeader(SaveCsv):
    def __init__(self, file,header:list|None=None):
        '''
        header:[列1,列2,列3]
        '''
        super().__init__(file)

        self.header=header
        if self.header is None:
            self.header=self.read_header()

    def read_header(self):
        with open(self.file, mode='r', newline='', encoding='utf-8') as file:
            reader = csv.reader(file)
            header = next(reader)  # 获取第一行作为表头

        return header


    def initialize(self):
        self.write_header()
    
    def write_header(self):
        # 打开CSV文件并写入数据
        with open(self.file, mode='w', newline='', encoding='utf-8') as file:
            fieldnames = self.header
            writer = csv.DictWriter(file, fieldnames=fieldnames)
            # 写入表头
            writer.writeheader()
    
    def read_to_dictList(self):
        filepath=self.file
        # 打开CSV文件
        with open(filepath, mode='r', newline='', encoding='utf-8') as file:
            reader = csv.DictReader(file)
            dictList=list(reader)
        return dictList
    
    def write_dictList(self,dictList):
        filepath=self.file
        # 将修改后的数据写回文件
        with open(filepath, mode='w', newline='', encoding='utf-8') as file:
            fieldnames = dictList[0].keys()  # 获取表头
            writer = csv.DictWriter(file, fieldnames=fieldnames)
            writer.writeheader()  # 写入表头
            writer.writerows(dictList)  # 写入数据

    def append_data(self,new_rows):
        '''
        new_rows: dictList
        '''
        # 打开CSV文件，以追加模式
        with open(self.file, mode='a', newline='', encoding='utf-8') as file:
            fieldnames = self.header# 表头
            writer = csv.DictWriter(file, fieldnames=fieldnames)
            
            # 追加数据
            for row in new_rows:
                writer.writerow(row)


    def set_cell(self,row, col_name,value):
        dictList=self.read_to_dictList()
        dictList[row][col_name]=value
        self.write_dictList(dictList)

    @staticmethod
    def create_folder(folder_path):
        os.makedirs(folder_path, exist_ok=True)

class SaveCsvsHeader():
    def __init__(self, folder_path:str,sheets:dict,flag_create_folder=False):
        '''
        sheets {"sheet_name":[列1,列2,列3]}
        '''
        self.folder_path = folder_path
        if flag_create_folder:
            self.create_folder(folder_path)
        self.sheets=sheets
        self.setNewSheet()

    def setNewSheet(self):
        for sheet_name in self.sheets:
            self.write_header(sheet_name)
    @staticmethod
    def create_folder(folder_path):
        os.makedirs(folder_path, exist_ok=True)

    def get_filename(self,sheet_name):
        return f"{self.folder_path}/{sheet_name}.csv"
    
    def write_header(self,sheet_name):
        # 打开CSV文件并写入数据
        with open(self.get_filename(sheet_name), mode='w', newline='', encoding='utf-8') as file:
            fieldnames = self.sheets[sheet_name]
            writer = csv.DictWriter(file, fieldnames=fieldnames)
            # 写入表头
            writer.writeheader()

    def read_to_df(self,sheet_name):
        df = pd.read_csv(self.get_filename(sheet_name))
        return df
    
    def read_to_dictList(self,sheet_name):
        filepath=self.get_filename(sheet_name)
        # 打开CSV文件
        with open(filepath, mode='r', newline='', encoding='utf-8') as file:
            reader = csv.DictReader(file)
            dictList=list(reader)
        return dictList
    
    def write_dictList(self,sheet_name,dictList):
        filepath=self.get_filename(sheet_name)
        # 将修改后的数据写回文件
        with open(filepath, mode='w', newline='', encoding='utf-8') as file:
            fieldnames = dictList[0].keys()  # 获取表头
            writer = csv.DictWriter(file, fieldnames=fieldnames)
            writer.writeheader()  # 写入表头
            writer.writerows(dictList)  # 写入数据

    def append_data(self,sheet_name,new_rows):
        '''
        new_rows: dictList
        '''
        # 打开CSV文件，以追加模式
        with open(self.get_filename(sheet_name), mode='a', newline='', encoding='utf-8') as file:
            fieldnames = self.sheets[sheet_name] # 表头
            writer = csv.DictWriter(file, fieldnames=fieldnames)
            
            # 追加数据
            for row in new_rows:
                writer.writerow(row)


    def set_cell(self,sheet_name,row, col_name,value):
        dictList=self.read_to_dictList(sheet_name)
        dictList[row][col_name]=value
        self.write_dictList(sheet_name,dictList)

