<?php

// 頁面專用WebAPI, 不管任何的頁面, class名稱固定為 [WebAPIForMenuPage], 不可變更
class WebAPIForMenuPage extends base_class
{
	//撈取圖表資料
	public function Selectload_chart_data($params)
	{
		$res = [
			"label_list" => [], //x軸時間label
			"line_data" => [], //各線資料存放用
		];

		//選中的設備子項目
		$a_line_item = (array) $params["line"];


		// 起始時間 當前時間往前推 24 小時
		$s_start_at_obj = new DateTime('-24 hours');
		$s_start_at = $s_start_at_obj->format("Y-m-d H:i:s");
		// 結束時間 當前時間
		$s_end_at_obj = new DateTime();
		$s_end_at =   $s_end_at_obj->format("Y-m-d H:i:s");

		// // 設定每分鐘的間隔
		// $interval = new DateInterval('PT1M'); // PT1M 表示 1 分鐘的間隔

		// // 建立時間區間
		// $period = new DatePeriod($s_start_at_obj, $interval, $s_end_at_obj);

		// foreach ($period as $dt) {
		// 	// 將每分鐘的時間格式化為 'Y-m-d H:i:s' 並加入陣列
		// 	$res["label_list"][] = $dt->format('Y-m-d H:i:00');
		// }


		//當設備子項目陣列不為空 才撈取資料
		$a_sql_union_arr = [];
		if (count($a_line_item) >= 0) {
			// 建立撈取語句
			foreach ($a_line_item as $k => $v) {
				$table = trim($v["table"]);
				$column = trim($v["column"]);
				$a_sql_union_arr[] = sprintf(
					"SELECT
						Time_Stamp,
						%s AS line_data,
						'line_%s' AS target_inx
					FROM
						[%s].[dbo].[%s]
					WHERE 
						Time_Stamp >= '%s' 
						AND Time_Stamp <= '%s' 
						AND DATEPART( minute, Time_Stamp ) = 0 
						AND DATEPART( second, Time_Stamp ) = 0 
					",
					$column,
					$k,
					$this->database_trend,
					$table,
					$s_start_at,
					$s_end_at
				);
				// foreach ($res["label_list"] as $k_2 => $v_2) {
				// 	$res["line_data"][$v][] = $k_2;
				// }
			}
			//組合查詢sql語句 並執行
			$sql = implode(" UNION ALL ", $a_sql_union_arr);
			$sth = $this->pdo_sql->prepare($sql);
			$sth->execute();
			$rows = $sth->fetchAll(PDO::FETCH_ASSOC);
			$temp_line_data = [];
			foreach ($rows as $k => $v) {
				$d_data_time = date("Y-m-d H:i:s", strtotime($v["Time_Stamp"]));
				if (!in_array($d_data_time, $res["label_list"])) {
					$res["label_list"][] = $d_data_time;
				}
				$temp_line_data[explode("_", $v["target_inx"])[1]][$d_data_time] = [
					"Time_Stamp" => $d_data_time,
					"line_data" => (float) number_format($v["line_data"], 2, ",", ""),
				];
			}


			//遞增排序整理時間軸
			sort($res["label_list"]);

			//資料依據時間排序
			foreach ($res["label_list"] as $k => $v) {
				//再依據各線分類
				foreach ($a_line_item  as $k_2 => $v_2) {
					$res["line_data"][$k_2][] = isset($temp_line_data[$k_2][$v]) ? $temp_line_data[$k_2][$v]["line_data"] : null;
					
				}
			}

		}


		return $res;
	}
}
