<?php
trait base_class_trait
{
	// 取得帳號的可讀取案場清單(若未傳帳號,則為目前使用者)
	public function GetUserStations($userId)
	{
		if ($userId == null) {
			$userId = $this->user_id;
		}
		$sql = "select * from v_roles_users_stations where user_id=:user_id";
		$sth = $this->pdo_sql->prepare($sql);
		$sth->execute(array("user_id" => $userId));
		return $sth->fetchAll(PDO::FETCH_ASSOC);
	}

	// 取得帳號設定的角色(若未傳帳號,則為目前使用者)
	public function GetUserRoles($userId)
	{
		if ($userId == null) {
			$userId = $this->user_id;
		}
		$sql = sprintf("select * from [%s].[dbo].[v_roles_users] where user_id=:user_id", $this->database_alarm);
		$sth = $this->pdo_sql->prepare($sql);
		$sth->execute(array("user_id" => $userId));
		return $sth->fetchAll(PDO::FETCH_ASSOC);
	}

	// 檢查這個帳號是有這個角色
	public function ChkUserRole($roleId, $userRolesList, $userId)
	{
		if ($userId == null) {
			$userId = $this->user_id;
		}
		if ($userRolesList == null) { // 若多次呼叫此函式,可傳入$userRolesList則不用再次取得角色清單,較有效率
			$userRolesList = $this->GetUserRoles($userId);
		}
		if (count($userRolesList) > 0) {
			foreach ($userRolesList as $role) {
				if ($role["role_id"] == $roleId) {
					return true;
				}
			}
		}
		return false;
	}

	// 取得指定案場的INV清單(若不傳入stn則抓全部)
	public function GetStationInv($stn)
	{
		if ($stn == null) {
			$sql = "select * from station_inv_2 order by STN,No";
			$sth = $this->pdo_sql->prepare($sql);
			$sth->execute();
		} else {
			$sql = "select * from station_inv_2 where STN=:stn order by No";
			$sth = $this->pdo_sql->prepare($sql);
			$sth->execute(array("stn" => $stn));
		}
		return $sth->fetchAll(PDO::FETCH_ASSOC);
	}

	// 取得 http://HostIP:Port/系統路徑
	public function GetHostAndSysUrl()
	{
		return HOST_SYS_URL;
		// 若使用者是使用內部IP,也會抓取內部IP,可能導至錯誤
		/* $protocol = strpos(strtolower($_SERVER['SERVER_PROTOCOL']), 'https') === FALSE ? 'http' : 'https';
		$host = $_SERVER['HTTP_HOST'];
		$request = $_SERVER['REQUEST_URI'];
		$request = explode("/", $request);
		return $protocol . "://" . $host . "/" . $request[1]; */
	}

	// Location下拉選單
	public function SelectLocationOptions($params)
	{
		return $this->GetUserStations();
	}
	// Inverter下拉選單
	public function SelectInverterNoOptions($params)
	{
		return $this->GetStationInv($params['stn']);
	}

	/* Leo
	* 建立隨機英數大小寫混和字串
	* $_nlength -> 欲產生長度多少之字串
	* $_nSpecial -> 欲產生多少特殊符號 (不可超過設定長度)
	*/
	public function CreateRandomStr($_nlength, $_nSpecial = 0)
	{
		$keyspace = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
		$str = '';
		$max = mb_strlen($keyspace, '8bit') - 1;
		$_nSpecial = $_nSpecial > $_nlength ? $_nlength - 1 : $_nSpecial;
		if ($_nSpecial > 0) {
			$SpecialCode = '!@#$%^&*';
			$S_max = mb_strlen($SpecialCode, '8bit') - 1;
			for ($i = 0; $i < $_nlength; ++$i) {
				$str .= $keyspace[random_int(0, $max)];
			}
			$str_max = mb_strlen($str, '8bit') - 1;
			for ($i = 0; $i < $_nSpecial; ++$i) {
				$str[random_int(0, $str_max)] = $SpecialCode[random_int(0, $S_max)];
			}
		} else {
			for ($i = 0; $i < $_nlength; ++$i) {
				$str .= $keyspace[random_int(0, $max)];
			}
		}
		return $str;
	}
	/* Leo
	* 建立毫秒時間戳
	*/
	public function CreateTimeStampMillisecond()
	{
		$str = '';
		$n_microtime = microtime(1);
		$a_microtime = explode(".", $n_microtime);
		$s_microtime_sec = str_pad($a_microtime[1], 4, "0", STR_PAD_RIGHT);
		$str = $a_microtime[0] . $s_microtime_sec;

		return $str;
	}

	/**
	 * 模糊搜尋 工單號 (料件型)
	 * @param: keyword
	 * @return: wo [Array]
	 */
	public function SelectFuzzyWoItemType1($params)
	{
		$params['item_type'] = 1;
		return $this->FuzzyWoByItemType($params);
	}

	/**
	 * 模糊搜尋 工單號
	 * @param: keyword
	 * @return: wo [Array]
	 */
	public function FuzzyWoByItemType($params)
	{
		$condi = "";
		$tb = $this->database_alarm;
		if (isset($params['item_type'])) {
			$item_type = $params['item_type'];
			$condi = " AND [id] IN (
				SELECT [work_order_id]
				FROM [$tb].[dbo].[work_order_product] AS WOP
				INNER JOIN [$tb].[dbo].[product] AS P
				ON WOP.[product_id] = P.[id]
				WHERE P.[item_type] = $item_type
			)";
		}
		$sql = sprintf(
			"SELECT DISTINCT
							[wo] AS [label]
						   ,[wo] AS [value]
						FROM [%s].[dbo].[work_order]
						WHERE [wo] LIKE '%%%s%%' $condi ",
			$this->database_alarm,
			$params["keyword"],
			$condi
		);
		$sth = $this->pdo_sql->prepare($sql);
		$sth->execute();
		return $sth->fetchAll(PDO::FETCH_ASSOC);
	}
}
