import pymysql
import os

target_path = 'F:/dl/ERA5'


def get_file_name_dict():
    file_name_dict = {}
    db = pymysql.connect(host='47.113.231.200', port=28089,
                         user='root', passwd='passok123A', db='jd_data', charset='utf8mb4')
    cursor = db.cursor()
    sql_select = "SELECT data_year, data_month, data_variable, download_url FROM jd_data.era5_detail;"
    cursor.execute(sql_select)
    result = cursor.fetchall()
    cursor.close()
    db.close()
    for line in result:
        raw_name = line[3].split('/')[-1]
        target_name = f'{line[0]}-{line[1]}-{line[2]}.nc'
        file_name_dict[raw_name] = target_name
    return file_name_dict


def rename_file(name_dict):
    counter = 0
    for dir_name in os.listdir(target_path):
        for file_name in os.listdir(os.path.join(target_path, dir_name)):
            counter += 1
            if file_name in name_dict:
                new_name = name_dict[file_name]
                print("[No. {}] 文件{}对应的表记录为：{}".format(counter, file_name, new_name))
                # os.rename("/".join([target_path, file_name]), "/".join([target_path, new_name]) + ".zip")
            else:
                print("[No. {}] 未找到文件{}对应的表记录".format(counter, file_name))


if __name__ == "__main__":
    target_name_dict = get_file_name_dict()
    rename_file(target_name_dict)
