<?php
// 頁面專用WebAPI, 不管任何的頁面, class名稱固定為 [WebAPIForMenuPage], 不可變更
class WebAPIForMenuPage extends base_class
{

	public function SelectLoadPageData($params)
	{


		//指定ID資料
		$s_id_list = (string) $params["id_list"];
		$s_id_list = trim($s_id_list);

		//設定查詢時間
		//資料結束時間 
		$s_end_time = date("Y-m-d 23:59:59");
		//當天起始時間
		$s_start_time = date("Y-m-d 00:00:00");
		//資料回傳陣列
		$res = [
			"info" => [],
			"chart_data" => []
		];

		//先撈取最後一筆當前資料
		$sql_info = "SELECT
							* 
						FROM
							(
							SELECT TOP
								1 ResidualTime,
								Alarm,
								HighAlarm,
								ContractDemand,
								DemandTarget,
								DemandAlarmSV,
								DemandShutdownSV,
								CurrentDemandTarget,
								CurrentDemand,
								InstantDemand,
								PredictedDemand,
								AdjustedDemand 
							FROM
								[dbo].[R_DMC] AS _rd 
							ORDER BY
								DATE_TIME DESC 
							) AS _t1
							CROSS JOIN (
							SELECT TOP
								1 P1,
								P2 
							FROM
								[dbo].[R_Other] 
							WHERE
								ID = 1 
							ORDER BY
								DATE_TIME DESC 
							) AS _t2
							CROSS JOIN (
							SELECT TOP
								1 Vrs,
								Vst,
								Vtr,
								Ir,
								[Is],
								It,
								PF,
								Kw,
								Kva,
								Kvar,
								KWH 
							FROM
								[dbo].[R_PM] 
							WHERE
								ID = 1 
							ORDER BY
							DATE_TIME DESC 
							) AS _t3
							";
		if ($this->pdo_hty != null) {
			$sth = $this->pdo_hty->prepare($sql_info);
			$sth->execute([]);
			$res["info"] = $sth->fetch(PDO::FETCH_ASSOC);
		}
		//撈取趨勢圖用的資料
		$sql_chart = "SELECT
						DATE_TIME,
						ResidualTime,
						Alarm,
						HighAlarm,
						ContractDemand,
						DemandTarget,
						DemandAlarmSV,
						DemandShutdownSV,
						CurrentDemandTarget,
						CurrentDemand,
						InstantDemand,
						PredictedDemand,
						AdjustedDemand 
					FROM
						[dbo].[R_DMC]
					WHERE
						DATE_TIME BETWEEN '$s_start_time' AND '$s_end_time'
						";
		if ($this->pdo_hty != null) {
			$sth = $this->pdo_hty->prepare($sql_chart);
			$sth->execute([]);
			$rows = $sth->fetchAll(PDO::FETCH_ASSOC);	
			foreach($rows as $k => &$v){
				$v["ContractDemand"] = number_format($v["ContractDemand"], 2,".","");
				$v["DemandShutdownSV"] = number_format($v["DemandShutdownSV"], 2,".","");
				$v["DemandTarget"] = number_format($v["DemandTarget"], 2,".","");
				$v["CurrentDemand"] = number_format($v["CurrentDemand"], 2,".","");
				$v["PredictedDemand"] = number_format($v["PredictedDemand"], 2,".","");
				$v["CurrentDemandTarget"] = number_format($v["CurrentDemandTarget"], 2,".","");
			}		
			$res["chart_data"] = $rows;
		}
		

		return $res;
	}
}
