import pandas as pd
import cdsapi
import os
import shutil
import math

def Get_Mass(date, Facility, lat, lon):
    # 将Timestamp对象转换为日期和时间的字符串
    date_str = date.strftime("%Y-%m-%d")
    time_str_current = date.strftime("%H:00")
    time_str_next = (date + pd.Timedelta(hours=1)).strftime("%H:00")

    # 解析日期字符串
    date_parts = date_str.split('-')
    year, month, day = date_parts

    # 计算包含位置的上下左右取整格网
    lat_min = math.floor(lat)
    lat_max = lat_min + 1
    lon_min = math.floor(lon)
    lon_max = lon_min + 1

    # 构建文件名
    filename = f'{Facility}_{year}{month}{day}_SL.nc'

    # 初始化 CDS API 客户端
    c = cdsapi.Client()

    # 构建参数并调用 CDS API
    c.retrieve(
        'reanalysis-era5-single-levels',
        {
            'product_type': 'reanalysis',
            'variable': 'vertical_integral_of_mass_of_atmosphere',
            'year': year,
            'month': month,
            'day': day,
            'time': [time_str_current, time_str_next],
            'area': [lat_max, lon_min, lat_min, lon_max],  # 修正顺序
            'format': 'netcdf',
        },
        filename
    )
    return filename

file_path_0 = r"F:\科研数据\2024.2 美国核查结果"

# 读取指定路径下的 Excel 文件
file_path = r'C:\Users\why\Desktop\CO2_匹配滤波器\data\美国碳源反演.xlsx'
sheet_name = '2024.2'

# 读取表格数据
data = pd.read_excel(file_path, sheet_name=sheet_name)

# 遍历表格行
for _, row in data.iterrows():
    # 获取每行的 M、D、E、F 列数据
    date = row['UTC']
    Facility = row['Facility Name']
    lat = row['Latitude']
    lon = row['Longitude']
    foldername = row['foldername']

    search_file_path = os.path.join(file_path_0, foldername)
    Files = os.listdir(search_file_path)
    for k in range(len(Files)):
        # 提取文件夹内所有文件的后缀
        Files[k]=os.path.splitext(Files[k])[1]
    
    # 你想要找的文件的后缀
    Str='SL.nc'
    date_str = date.strftime("%Y-%m-%d")
    # 解析日期字符串
    date_parts = date_str.split('-')
    year, month, day = date_parts
    # 构建文件名
    filename = f'{Facility}_{year}{month}{day}_SL.nc'
    
    if filename in Files:
        print(f"{foldername}已存在nc文件")
    else:
        # 调用之前定义的函数
        filename = Get_Mass(date, Facility, lat, lon)

        # 构建文件路径和目标子目录路径
        target_folder = os.path.join(file_path_0, foldername)

        # 构建目标文件路径
        target_file_path = os.path.join(target_folder, filename)
        source_file_path = os.path.join('./', filename)

        # 判断文件是否存在
        if os.path.exists(source_file_path):
            # 使用shutil.move在不同磁盘之间移动文件
            shutil.move(source_file_path, target_file_path)
            print(f"文件已成功移动到目标子目录：{target_folder}")
        else:
            print(f"文件不存在：{source_file_path}")

