% Date: 2023-12-17
% Author: HuayiWang
function Wind = WebWindDataMul(Facility, choice)
%% 获取基本信息
lat = Facility.lat;
lon = Facility.lon;
Date = datestr(Facility.UTC_time, 'yyyy-mm-dd');
Hour = hour(Facility.UTC_time);
Minute = minute(Facility.UTC_time);
%% 定义API链接
api_url_head = {'https://archive-api.open-meteo.com/v1/archive?','https://api.open-meteo.com/v1/forecast?'};
if(choice == 1 || choice == 2)
    api_url_head = api_url_head{1};
else
    api_url_head = api_url_head{2};
end
lat_mat = floor(lat):0.25:floor(lat)+1;
lon_mat = floor(lon):0.25:floor(lon)+1;
[LON, LAT] = meshgrid(lon_mat,lat_mat);
b_lon = num2str(LON(:)');
c_lon = regexprep(b_lon,'\s*',',');
b_lat = num2str(LAT(:)');
c_lat = regexprep(b_lat,'\s*',',');
geo_info = ['latitude=', c_lat, '&longitude=', c_lon];
time_info = ['&start_date=', Date, '&end_date=', Date];
data_info = '&hourly=wind_speed_10m,wind_direction_10m&wind_speed_unit=ms&timezone=GMT';
model_name = {'era5_seamless', 'ecmwf_ifs', 'best_match'};
model_info = ['&models=', model_name{choice}];
api_url = [api_url_head, geo_info, time_info, data_info, model_info];

%% 使用webread获取API返回的JSON数据
max_attempts = 5;  % 设置最大尝试次数
current_attempt = 1;

while current_attempt <= max_attempts
    try % 成功获取数据
        struct_data = webread(api_url);
        %         mydisp('风速数据成功获取！');
        break;  % 跳出循环，因为已成功获取数据
    catch
        % 如果发生错误，捕获异常并显示错误消息
        disp(['尝试 ', num2str(current_attempt), ' 失败，等待重试...']);
        current_attempt = current_attempt + 1;
        pause(3);  % 添加3秒的延迟
    end
end

%% 解析STRUCT数据
for i = 1:25
    Wind_speed = struct_data{i,1}.hourly.wind_speed_10m;
    Wind_direction= struct_data{i,1}.hourly.wind_direction_10m;
    %
    index = round(Hour + (Minute / 60)) + 1;
    Wind.speed(i) = Wind_speed(index);
    Wind.direction(i) = Wind_direction(index);
    Wind.u10_(i) = Wind.speed(i) * sind(Wind.direction(i));
    Wind.v10_(i) = Wind.speed(i) * cosd(Wind.direction(i));
    Wind.lat(i) = struct_data{i,1}.latitude;
    Wind.lon(i) = struct_data{i,1}.longitude;
end
X = LON;
Y = LAT;
V = reshape(Wind.v10_, [5, 5]);
U = reshape(Wind.u10_, [5, 5]);
Xq = Facility.lon;
Yq = Facility.lat;
Vq = interp2(X,Y,V,Xq,Yq,'linear');
Uq = interp2(X,Y,U,Xq,Yq,'linear');
Wind.speed = sqrt(Uq^2+Vq^2);
Wind.direction = atan2d(Uq,Vq);
Wind.direction = mod(Wind.direction + 360, 360);

% Ueff：有效风速 effective wind speed
% p1 = 0.5199;
% p2 = 1.173;
% Wind.Ueff = p1 * Wind.speed + p2; % 单位：m/s

% Cusworth,2023
q1 = 1.1;
q2 = 0.6;
Wind.Ueff = q1 * log(Wind.speed) + q2; % 单位：m/s

end
