%%
% 生成基本表格信息
%% 加载路径
fun_path = genpath('functions');
addpath(fun_path)
%% 设施名称
Facility_Name = 'White Bluff';
folderPath = ['F:\', Facility_Name];

% 获取文件夹信息
folders = dir(folderPath);
folders = folders([folders.isdir]);
folders = folders(~ismember({folders.name}, {'.', '..'}));

% 指定目标路径
% targetPath = 'F:\2024.7 美国核查结果';
type = 'electricity';
% 初始化表格
tableData = cell(length(folders), 35);
len = size(tableData, 1);
%% 查询设施基本信息
datafile = 'data/美国碳源反演.xlsx';
sheetName = '排放设施信息';
T = table2cell(readtable(datafile, 'Sheet', sheetName, 'VariableNamingRule', 'preserve'));
mat_data = T(:, 2);
index = strcmp(Facility_Name, mat_data); % 检索当前设施
info = T(index, :);
State = info{1};
Facility_ID = info{3};
Longitude = info{4};
Latitude = info{5};
Altitude = info{6};
Zone = info{7}; % 地区时
%% 加载EPA查询模块
cd('functions/EPA')
obj = py.importlib.import_module('EPA'); % 导入python模块
py.importlib.reload(obj);   % 加载模块
cd('../..')

%% 循环处理文件夹
for i = 1 : len
    filename = folders(i).name;
    %% G | satellite
    underscoreIndices = strfind(filename, '_');
    satellite = filename(1 : underscoreIndices(1) - 1);
    %% H | date
    underscoreIndices = strfind(filename, '_');
    date = filename(underscoreIndices(4)+1 : underscoreIndices(4)+8);
    %% C | foldername
    foldername = [Facility_Name, '_', date];
    %% I | Time of Satellite
    fpath = fullfile(folderPath, filename);
    flist_xml = dir([fpath,'\*xml']);
    flist_xml = fullfile(fpath, flist_xml.name);
    xmlStruct = ReadXmlData(flist_xml);   % 读取xml文件
    ToS = datetime(xmlStruct.StartTime, 'Format', 'yyyy-MM-dd HH:mm:ss'); % 卫星时间
    
    %% J | UTC
    % UTC 美国过境时间为16:00 - 20:00左右
    % UTC 中国过境时间为02:00 - 06:00左右
    switch satellite
        case 'GF5B'
            UTC = ToS - duration(8, 0, 0);
        case 'ZY1E'
            UTC = ToS;
        case 'ZY1F'
            UTC = ToS;
        case 'GF5'
            UTC = ToS - duration(8, 0, 0);
        case 'GF5A'
            UTC = ToS;
    end
    %% M | LST
    switch Zone
        case 'EST'
            LST = UTC - duration(5, 0, 0);
        case 'CST'
            LST = UTC - duration(6, 0, 0);
        case 'MST'
            LST = UTC - duration(7, 0, 0);
        case 'PST'
            LST = UTC - duration(8, 0, 0);
        otherwise
            disp('ERR Zone name!')
    end
    %% O | day LST
    day_LST = datestr(LST, 'mm/dd/yyyy');
    %% P | time
    time = datestr(LST, 'hh:MM');
    %% Q R S | EPA Emission
    Hour = hour(LST);
    DATE = datestr(LST, 'yyyy-mm-dd');
    %% 尝试查询
    cd('functions/EPA');
    try
        Emission = py.EPA.QueryEmission(DATE, uint32(Facility_ID), uint8(Hour));
        t = cell(Emission);
        Q_former = double(py.array.array('d', t{1}));
        Q_latter = double(py.array.array('d', t{2}));
    catch ME
        fprintf('An error occurred: %s\n', ME.message);
        Q_former = 0;
        Q_latter = 0;
    end
    cd('../..');
    mydisp("查询完成");
    %% S | Q_avg
    Minute = minute(LST);
    Q_avg = (Q_former * (60 - Minute) + Q_latter * Minute) / 60 * 0.90718474;
    %% 保存到表格
    tableData{i, 1} = i; % 序号
    tableData{i, 2} = filename; % 文件名
    tableData{i, 3} = foldername;
    tableData{i, 4} = Facility_Name; % 设施名称
    tableData{i, 5} = type; % 设施类型
    tableData{i, 6} = Latitude;
    tableData{i, 7} = Longitude;
    tableData{i, 8} = Altitude;

    tableData{i, 9} = satellite;
    tableData{i, 10} = date; % 8位日期
    tableData{i, 11} = ToS;
    tableData{i, 12} = UTC;
    tableData{i, 13} = State;
    tableData{i, 14} = Zone;
    tableData{i, 15} = LST;
    tableData{i, 16} = Facility_ID;
    tableData{i, 17} = day_LST;
    tableData{i, 18} = time;
    tableData{i, 19} = Q_former;
    tableData{i, 20} = Q_latter;
    tableData{i, 21} = Q_avg;
end
%% 清除
clear obj; % 清除PYTHON变量

%% 创建表格
folderTable = cell2table(tableData, 'VariableNames', ...
    {'id', 'filename', 'foldername', 'facility', 'type', 'Latitude', 'Longitude', 'Altitude', ...
    'satellite', 'date', 'Time of Satellite', 'UTC', 'State', 'Zone', 'Local Standard Time', ...
    'Facility ID', 'day LST', 'time', '前整点Q', '后整点Q', 'avg Q(ton/h)',...
    '反演结果', '反演误差', '不确定度', 'IME_u (t/h)', 'Wind_u (t/h)', 'MF_u (ppm)', 'q', 'diff_dir', 'phi',...
    '风速', '提取', '排放', '背景', '备注'});

% 显示表格
disp(folderTable);

%% 导出表格
outputname = [Facility_Name, '.xlsx'];
writetable(folderTable, outputname);

%% 创建文件夹
% folderNames = tableData(:, 3);
% 
% % 遍历文件夹名称并创建子文件夹
% for i = 1:length(folderNames)
%     currentFolderPath = fullfile(targetPath, folderNames{i});
%     if(~exist(currentFolderPath, 'dir'))
%         mkdir(currentFolderPath);
%         disp(currentFolderPath)
%     end
% end
% 
% disp('子文件夹创建完成。');
