<?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");


		$sql = "WITH range_row_no AS (
			SELECT MAX
				( _rrn.RowNO ) AS Max_no,
				MIN ( _rrn.RowNO ) AS Min_no,
				ID 
			FROM
				[dbo].[R_WM] AS _rrn 
			WHERE
				_rrn.DATE_TIME BETWEEN '$s_start_time' AND '$s_end_time'
				AND ID IN ($s_id_list) 
			GROUP BY
				_rrn.ID 
			) SELECT
			_rrn.ID ,
			( SELECT Acc FROM R_WM WHERE RowNO = _rrn.Min_no ) AS MIN_Acc,
			(
			SELECT TOP
				1 Acc 
			FROM
				R_WM 
			WHERE
				RowNO = _rrn.Max_no 
			) AS MAX_Acc,
			(
			SELECT TOP
				1 Flow 
			FROM
				R_WM 
			WHERE
				RowNO = _rrn.Min_no 
			) AS MIN_Flow,
			(
			SELECT TOP
				1 Flow 
			FROM
				R_WM 
			WHERE
				RowNO = _rrn.Max_no 
			) AS MAX_Flow 
		FROM
			range_row_no AS _rrn";
		$res = [];
		if ($this->pdo_hty != null) {
			$sth = $this->pdo_hty->prepare($sql);
			$sth->execute([]);
			$res = $sth->fetchAll(PDO::FETCH_ASSOC);
			foreach ($res as $k => &$v) {
				$v["ID"] = (int)$v["ID"];
				$v["MIN_Acc"]=number_format($v["MIN_Acc"],2,".","");
				$v["MAX_Acc"]=number_format($v["MAX_Acc"],2,".","");
				$v["MIN_Flow"]=number_format($v["MIN_Flow"],2,".","");
				$v["MAX_Flow"]=number_format($v["MAX_Flow"],2,".","");
			}
		}
		return $res;
	}	

	// 水係統最新狀態資料
	public function SelectStatus($params)
	{
		$sql = "SELECT RD.* 
				FROM [R_Device] AS RD
				INNER JOIN (
					SELECT [Id]
						,MAX([DATE_TIME]) AS [max_DATE_TIME]
					FROM [R_Device]
					GROUP BY [Id]
				) AS RD_L
				ON RD.[Id] = RD_L.[Id] AND RD.[DATE_TIME] = RD_L.[max_DATE_TIME]
				ORDER BY RD.[Id]";
		$res = [];
		if ($this->pdo_hty != null) {
			$sth = $this->pdo_hty->prepare($sql);
			$sth->execute();
			$res = $sth->fetchAll(PDO::FETCH_ASSOC);
		}
		$id_group = [];
		foreach ($res as $dr) 
		{
			$id_group[$dr['Id']] = $dr;
		}
		return $id_group;
	}
}
