<main id="js-page-content" role="main" class="page-content">
	<div class="row">

		<div class="col-sm-12 col-xl-12">
			<h1 class="p-2 mb-0">運維管理</h1>
			<div class="row bg-dark p-2">
				<div class="col-auto">
					<div class="btn-group">
						<button type="button" onclick="setType(2)" class="btn btn-secondary waves-effect waves-themed">維修</button>
						<button type="button" onclick="setType(1)" class="btn btn-secondary waves-effect waves-themed">保義記錄</button>
						<button type="button" onclick="setType(null)" class="btn btn-secondary waves-effect waves-themed">廠商資料</button>
					</div>
				</div>
				<div id="setDate" class="col-auto">
					<div class="btn-group">
						<button onclick="setDate('tdy')" type="button" class="btn btn-secondary waves-effect waves-themed">今天</button>
						<button onclick="setDate('ytd')" type="button" class="btn btn-secondary waves-effect waves-themed">昨天</button>
					</div>
				</div>
				<div class="col-auto">
					<div class="form-group">
						<input class="form-control" id="startdate" data-val="" type="date" name="date" value="">
					</div>
				</div>
				<div class="col-auto">
					<div class="form-group">
						<input class="form-control" id="enddate" type="date" data-val="" name="date" value="">
					</div>
				</div>
				<div class="col-auto" style="display: none">
					<div class="form-group">
						<input type="text" id="serial_number" class="form-control" placeholder="表單號">
					</div>
				</div>
				<div class="col-auto" style="display: none">
					<a href="#" for="serial_number" onclick="snSearch()" class="btn btn-info">單號查詢</a>
				</div>
				<hr>

			</div>
			<div class="row bg-dark p-2 align-items-center">
				<div class="col-auto">
					<a href="#" id="selAllSys" onclick="selAllSysVal(this)" class="btn btn-info">全選類別</a>
				</div>
				<div class="col-auto">
					<div id="mainList" class="frame-wrap">
					</div>
				</div>
			</div>
			<div class="row bg-dark p-2 mb-5 align-items-center">
				<div class="col-auto" style="padding-left: 133px">
					<div id="subList" class="frame-wrap">
					</div>
				</div>
			</div>

			<div class="">
				<div class="frame-wrap">
					<div class="mb-3">
						<a href="#" id="newForm" class="btn btn-success" data-toggle="modal" data-target="#opeFirmModal">新增</a>
						<a href="#" onclick="exportExcel()" class="btn btn-info waves-effect waves-themed">
							<span class="fal fa-file-excel mr-1"></span>
							匯出
						</a>
					</div>
					<table id="opeFirmTable" class="table table-bordered table-striped text-center m-0 w-100">
					</table>
					<table id="opeRecTable" class="table table-bordered table-striped text-center m-0 w-100">
					</table>
				</div>
			</div>
		</div>
	</div>
</main>

<!-- Modal center 廠商資料 -->
<div class="modal fade" id="opeFirmModal" tabindex="-1" role="dialog" aria-hidden="true">
	<div class="modal-dialog modal-dialog-centered" role="document">
		<div class="modal-content">
			<div class="modal-header">
				<h4 id="opeFirmTitle" class="modal-title">
					
				</h4>
				<button type="button" class="close" data-dismiss="modal" aria-label="Close">
					<span aria-hidden="true"><i class="fal fa-times"></i></span>
				</button>
			</div>
			<form id="opeFirmForm">
				<div class="modal-body">
					<div class="row">
						<div class="col-md-6">
							<div class="form-group">
								<label class="form-label" for="inpFirmSelSysMain">系統大類</label>
								<select class="form-control" id="inpFirmSelSysMain" name="inpFirmSelSysMain">
								</select>
							</div>
						</div>
						<div class="col-md-6">
							<div class="form-group">
								<label class="form-label" for="inpFirmSelSysSub">系統小類</label>
								<select class="form-control" id="inpFirmSelSysSub" name="inpFirmSelSysSub">
									<option value=''>未選擇</option>
								</select>
							</div>
						</div>
						<div class="col-md-6">
							<div class="form-group">
								<label class="form-label" for="inpName">姓名</label>
								<input type="text" id="inpName" name="inpName" class="form-control">
							</div>
						</div>
						<div class="col-md-6">
							<div class="form-group">
								<label class="form-label" for="inpConPer">聯絡人</label>
								<input type="text" id="inpConPer" name="inpConPer" class="form-control">
							</div>
						</div>
						<div class="col-md-6">
							<div class="form-group">
								<label class="form-label" for="inpPhone">電話</label>
								<input type="text" id="inpPhone" name="inpPhone" class="form-control">
							</div>
						</div>
						<div class="col-md-6">
							<div class="form-group">
								<label class="form-label" for="inpEmail">Email</label>
								<input type="email" id="inpEmail" name="inpEmail" class="form-control">
							</div>
						</div>
						<div class="col-md-6">
							<div class="form-group">
								<label class="form-label" for="inpTaxIdNum">統一編號</label>
								<input type="text" id="inpTaxIdNum" name="inpTaxIdNum" maxlength="8" class="form-control">
							</div>
						</div>
						<div class="col-md-6">
							<div class="form-group">
								<label class="form-label" for="inpRemark">備注</label>
								<input type="text" id="inpRemark" name="inpRemark" class="form-control">
							</div>
						</div>
					</div>
				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-secondary" id="OpeFirmCanBtn" data-dismiss="modal">關閉</button>
					<button type="button" class="btn btn-primary" id="OpeFirmSendBtn" e-prevent>儲存</button>
				</div>
			</form>
		</div>
	</div>
</div>

<!-- Modal center 保養/維修 -->
<div class="modal fade" id="opeRecModal" tabindex="-1" role="dialog" aria-hidden="true">
	<div class="modal-dialog modal-dialog-centered" role="document">
		<div class="modal-content">
			<div class="modal-header">
				<h4 id="opeRecTitle" class="modal-title">
					
				</h4>
				<button type="button" class="close" data-dismiss="modal" aria-label="Close">
					<span aria-hidden="true"><i class="fal fa-times"></i></span>
				</button>
			</div>
			<form id="opeRecForm">
				<div class="modal-body">
					<div class="row">
						<div class="col-md-6">
							<div class="form-group">
								<label class="form-label" for="inpErrCode">異常編號</label>
								<select class="form-control" id="inpErrCode" name="inpErrCode">
									<option value=''>未選擇</option>
								</select>
							</div>
						</div>
						<div class="col-md-6">
							<div class="form-group">
								<label class="form-label" for="inpStaTime">預計開始時間</label>
								<input type="date" id="inpStaTime" name="inpStaTime" class="form-control">
							</div>
						</div>
						<div class="col-md-6">
							<div class="form-group">
								<label class="form-label" for="inpWorTyp">項目</label>
								<select class="form-control custom-select-ri" id="inpWorTyp" name="inpWorTyp" disabled>
									<option value=1 selected>保養</option>
									<option value=2>維修</option>
								</select>
							</div>
						</div>
						<div class="col-md-6">
							<div class="form-group">
								<label class="form-label" for="inpFixDo">維修項目</label>
								<input type="text" id="inpFixDo" name="inpFixDo" class="form-control">
							</div>
						</div>
						<div class="col-md-6">
							<div class="form-group">
								<label class="form-label" for="inpFixDoCode">維修項目代碼(設備編號)</label>
								<select class="form-control" id="inpFixDoCode" name="inpFixDoCode">
									<option value=''>未選擇</option>
								</select>
							</div>
						</div>
						<div class="col-md-6">
							<div class="form-group">
								<label class="form-label" for="inpFixFirm">負責廠商</label>
								<select class="form-control" id="inpFixFirm" name="inpFixFirm">
									<option value=''>未選擇</option>
								</select>
							</div>
						</div>
						<div class="col-md-6">
							<div class="form-group">
								<label class="form-label" for="inpStatus">狀態</label>
								<div class="form-control" id="inpStatus">
									<div class="row container">
										<div class="">
											<input class="custom-radio-input" type="radio" name="inpSta" id="inpSta_0" value="0" checked>
											<label class="form-label" for="inpSta_0">未完成</label>
										</div>

										<div class="px-4">
											<input class="custom-radio-input" type="radio" name="inpSta" id="inpSta_1" value="1">
											<label class="form-label" for="inpSta_1">完成</label>
										</div>
									</div>
								</div>
							</div>
						</div>
						<div class="col-md-6">
							<div class="form-group">
								<label class="form-label" for="inpWorPerId">工作人員編號</label>
								<select class="form-control" id="inpWorPerId" name="inpWorPerId">
									<option value=''>未選擇</option>
								</select>
							</div>
						</div>
						<div class="col-md-12">
							<div class="form-group">
								<label class="form-label" for="inpNotice">注意事項</label>
								<textarea class="form-control" type="text" id="inpNotice" name="inpNotice" rows="7"></textarea>
							</div>
						</div>
						<div class="col-md-12">
							<div class="form-group">
								<label class="form-label" for="inpDescription">結果描述</label>
								<textarea class="form-control" type="text" id="inpDescription" name="inpDescription" rows="7"></textarea>
							</div>
						</div>
						<div class="col-md-6">
							<div id='forImage' class="col-sm-12 forimage mt-2 p-0">

							</div>
							<div class="form-group">
								<label class="form-label">上傳檔案</label>
								<label for="myImage" class="file-upload" style="cursor : pointer ">點擊上傳檔案</label>
								<input id="myImage" class="form-control" type="file" multiple hidden />
							</div>
						</div>
					</div>
				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-secondary" id="OpeRecCanBtn" data-dismiss="modal">關閉</button>
					<button type="button" class="btn btn-primary" id="OpeRecSendBtn" e-prevent>儲存</button>
				</div>
			</form>
		</div>
	</div>
</div>

<!-- Modal center 刪除 -->
<div class="modal fade" id="delModal" tabindex="-1" role="dialog" aria-hidden="true">
	<div class="modal-dialog modal-dialog-centered" role="document">
		<div class="modal-content">
			<div class="modal-header">
				<h4 class="modal-title">
					確定刪除這一筆嗎?
				</h4>
				<button type="button" class="close" data-dismiss="modal" aria-label="Close">
					<span aria-hidden="true"><i class="fal fa-times"></i></span>
				</button>
			</div>
			<div class="modal-footer">
				<button type="button" class="btn btn-secondary" id="confirmDelCanBtn" data-dismiss="modal">關閉</button>
				<button type="button" class="btn btn-primary" id="confirmDelBtn" e-prevent>儲存</button>
			</div>
		</div>
	</div>
</div>

<script>
	$(function () {
		pageAct.mainStatus = false;
		$(loadEle).Loading("close");
		pageAct.sub_system_tag = null;
		pageAct.main_system_tag = null;
		pageAct.selSysSub = [];
		pageAct.selSysMain = [];

		sysList();

		$('input[type=checkbox][data-type=main]').parent().on('change', function () {
			pageAct.main_system_tag = $('input[type=checkbox]').map(function (i, v) {
				if ($(v).data('type') == 'main') {
					if ($(v).is(':checked')) {
						$(`[data-main=` + $(v).prop('id') + `]`).attr('hidden', false);
						return $(v).prop('id')
					}
					else
						$(`[data-main=` + $(v).prop('id') + `]`).attr('hidden', true);
				}
			}).toArray();

			if ($('input[type=checkbox][data-type=main]:checked').length <= 0) {
				pageAct.main_system_tag = null
				pageAct.sub_system_tag = null;
			}

			refTable();
		});

		$('#subList, #mainList').on('change', $('input[type=checkbox][data-type=sub]').parent(), function () {
			pageAct.sub_system_tag = $('input[type=checkbox]:checked').map(function (i, v) { if ($(v).data('type') == 'sub') return $(v).prop('id') }).toArray();

			if ($('input[type=checkbox][data-type=sub]:checked').length <= 0) {
				pageAct.sub_system_tag = null;
			}

			if ($('input[type=checkbox][data-type=sub]:checked').length == $('input[type=checkbox][data-type=sub]').length) {
				$('#selAllSys').html('取消全選');
			}
			else {
				$('#selAllSys').html('全選類別');
			}

			refTable();
		});

		$('[onclick^=setType]').on('click', function () {
			btnSelCss(this);
		});

		$(`[onclick^=setDate]`).on('click', function () {
			if ($(this).hasClass('btn-info')) {
				$(this).removeClass('btn-info');
				$(this).addClass('btn-secondary');
				setDate();
			}
			else
				btnSelCss(this);
		});

		$('#startdate, #enddate').on('change', function () {
			let startdate = new Date($('#startdate').val());
			let enddate = new Date($('#enddate').val());
			setDate(null, startdate, enddate);
		});

		$(`[onclick="setType(null)"]`).click();

		initDate();
		event();
		$('div.image-full-show').css("display", "none");
	});

	function loadOpeFirmTable() {
		$('#opeFirmTable_wrapper').css('display', 'block');
		$('#opeRecTable_wrapper').css('display', 'none');
		$('#serial_number').parent().parent().css('display', 'none');
		$('[for=serial_number]').parent().css('display', 'none');
		$('#setDate').css('display', 'none');
		$('#startdate').parent().parent().css('display', 'none');
		$('#enddate').parent().parent().css('display', 'none');

		serial_number = $('#serial_number').val() || null;
		let ajaxObj = {
			url: baseApiUrl + "/operation/OpeFirList",
			method: "POST",
			data: { work_type: null, start_created_at: pageAct.startdate, end_created_at: pageAct.enddate, serial_number: pageAct.serial_number, main_system_tag: pageAct.main_system_tag, sub_system_tag: pageAct.sub_system_tag }
		};
		let tag = "#opeFirmTable";

		let column_defs = [
			{ "targets": [0], "width": "4%", "sortable": true },
			{ "targets": [1], "width": "5%", "sortable": true },
			{ "targets": [2], "width": "5%", "sortable": true },
			{ "targets": [3], "width": "5%", "sortable": true },
			{ "targets": [4], "width": "5%", "sortable": true },
			{ "targets": [5], "width": "5%", "sortable": true },
			{ "targets": [6], "width": "5%", "sortable": true }
		];

		let columns = [
			{
				"title": "廠商類別",
				"data": "system_key",
			},
			{
				"title": "廠商",
				"data": "name",
			},
			{
				"title": "聯絡人",
				"data": "contact_person",
			},
			{
				"title": "電話",
				"data": "phone",
			},
			{
				"title": "email",
				"data": "email",
			},
			{
				"title": "建立日期",
				"data": "created_at"
			},
			{
				"title": "功能",
				"data": "id",
				"render": function (data) {
					let btnDiv = creDiv(["row", "m-0", "justify-content-center"], { "style": "gap:10px" }, null, null, { id: data });
					btnDiv.append(creBtnHtml("修改", "opeFirmEdiBtn", null, ["btn", "btn-info"], { "toggle": "modal", "target": "#opeFirmModal" }));
					btnDiv.append(creBtnHtml("刪除", "opeFirmDelBtn", null, ["btn", "btn-danger"], { "toggle": "modal", "target": "#delModal" }));
					return btnDiv.outerHtml();
				}
			},
		];

		opeFirmTable = new YourTeam.JqDataTables.getTableByAjax(ajaxObj, tag, null, columns, column_defs);
	}

	function loadOpeRecTable() {
		$('#opeFirmTable_wrapper').css('display', 'none');
		$('#opeRecTable_wrapper').css('display', 'block');
		$('#serial_number').parent().parent().css('display', 'block');
		$('[for=serial_number]').parent().css('display', 'block');
		$('#setDate').css('display', 'block');
		$('#startdate').parent().parent().css('display', 'block');
		$('#enddate').parent().parent().css('display', 'block');

		let ajaxObj = {
			url: baseApiUrl + "/operation/OpeRecList",
			method: "POST",
			data: { work_type: pageAct.work_type, start_created_at: pageAct.startdate, end_created_at: pageAct.enddate, serial_number: pageAct.serial_number, main_system_tag: pageAct.main_system_tag, sub_system_tag: pageAct.sub_system_tag }
		}

		let tag = "#opeRecTable";

		let column_defs = [
			{ "targets": [0], "width": "2%", "sortable": true },
			{ "targets": [1], "width": "6%", "sortable": true },
			{ "targets": [2], "width": "7%", "sortable": true },
			{ "targets": [3], "width": "6%", "sortable": true },
			{ "targets": [4], "width": "5%", "sortable": true },
			{ "targets": [5], "width": "3%", "sortable": true },
			{ "targets": [6], "width": "5%", "sortable": true },
			{ "targets": [7], "width": "6%", "sortable": true },
			{ "targets": [8], "width": "15%", "sortable": false },
			{ "targets": [9], "width": "6%", "sortable": false },
			{ "targets": [10], "width": "8%", "sortable": false },
			{ "targets": [11], "width": "8%", "sortable": false },
		];

		let columns = [
			{
				"title": "項目",
				"data": "work_type_name",
			},
			{
				"title": "位置",
				"data": "location",
			},
			{
				"title": "異常代號",
				"data": "error_code",
			},
			{
				"title": "表單號",
				"data": "formId",
			},
			{
				"title": "設備名稱",
				"data": "device_name",
			},
			{
				"title": "狀態",
				"data": "status_name",
			},
			{
				"title": "處理人員",
				"data": "user_full_name",
			},
			{
				"title": "預計施工時間",
				"data": "start_time",
				"render": function (data) {
					return displayDate(data, "datetime");
				}
			},
			{
				"title": "檔案上傳",
				"data": "lorf",
				"render": function (data) {
					strHtml = ``;
					$.each(data, function (i, v) {
						if (i == 0)
							strHtml += `<div class="file-item" data-id=${v.id}>`
						if (i < 3) {
							let extName = v.ori_file_name.split('.')[1];
							strHtml += `<a href="${baseApiUrl}/upload/operation/${v.save_file_name}.${extName}" download="${v.ori_file_name}" target="_blank">
											<img style="margin-left: 30px" data-filename="${v.ori_file_name}" data-savename="${v.save_file_name}" height="70px" width="70px" src="${baseApiUrl}/upload/operation/${v.save_file_name}.${extName}">
										</a>`
						}
					});
					strHtml += `</div>`;

					return strHtml;
				}
			},
			{
				"title": "完成時間",
				"data": "finish_time",
				"render": function (data) {
					return displayDate(data, "datetime");
				}
			},
			{
				"title": "建立時間",
				"data": "created_at",
			},
			{
				"title": "功能",
				"data": "id",
				"render": function (data) {
					let btnDiv = creDiv(["row", "m-0", "justify-content-center"], { "style": "gap:10px" }, null, null, { id: data });
					btnDiv.append(creBtnHtml("修改", "opeRecEdiBtn", null, ["btn", "btn-info"], { "toggle": "modal", "target": "#opeRecModal" }));
					btnDiv.append(creBtnHtml("刪除", "opeRecDelBtn", null, ["btn", "btn-danger"], { "toggle": "modal", "target": "#delModal" }));
					return btnDiv.outerHtml();
				}
			},
		];

		opeRecTable = new YourTeam.JqDataTables.getTableByAjax(ajaxObj, tag, null, columns, column_defs);
	}

	function setType(wt) {
		pageAct.work_type = wt;
		
		if (wt == null) {
			$('#newForm').attr('data-target', '#opeFirmModal');
			loadOpeFirmTable();
		}
		else {
			$('#inpWorTyp').val(wt);
			$('#newForm').attr('data-target', '#opeRecModal');
			loadOpeRecTable();
		}
	}

	function setDate(dateType = null, startdate = null, enddate = null) {
		clearPageAct();
		pageAct.startdate = startdate;
		pageAct.enddate = enddate;

		if ($('#startdate').val() > $('#enddate').val()) {
			$('#startdate').val($('#startdate').data('val'));
			$('#enddate').val($('#enddate').data('val'));
			toast_error('不可選擇大於結束時間');
		}
		else {
			let today = displayDate(new Date(new Date().setDate(new Date().getDate())), 'date').replaceAll('/', '-');
			let ytd = displayDate(new Date(new Date().setDate(new Date().getDate() - 1)), 'date').replaceAll('/', '-')

			if (dateType == 'tdy') {
				pageAct.startdate = new Date(displayDate(new Date(new Date().setDate(new Date().getDate())), 'date'));
				$('#startdate').val(today);
				$('#startdate').data('val', today);
				$('#enddate').val(today);
				$('#enddate').data('val', today);
			}
			else if (dateType == 'ytd') {
				pageAct.startdate = new Date(displayDate(new Date(new Date().setDate(new Date().getDate() - 1)), 'date'));
				$('#startdate').val(ytd);
				$('#startdate').data('val', ytd);
				$('#enddate').val(ytd);
				$('#enddate').data('val', ytd);
			}
			else {
				$(`[onclick^=setDate]`).removeClass('btn-info');
				$(`[onclick^=setDate]`).addClass('btn-secondary');
				if ($('#startdate').val() == $('#enddate').val()) {
					if ($('#startdate').val() == today)
						$(`[onclick="setDate('tdy')"]`).click();
					else if ($('#startdate').val() == ytd)
						$(`[onclick="setDate('ytd')"]`).click();
				}
				$('#startdate').data('val', $('#startdate').val());
				$('#enddate').data('val', $('#enddate').val());
			}

			refTable();
		}
	}

	function initDate() {
		//$('#startdate').val(displayDate(new Date(new Date().setDate(new Date().getDate())), 'date').replaceAll('/', '-'));
		//$('#enddate').val(displayDate(new Date(new Date().setDate(new Date().getDate())), 'date').replaceAll('/', '-'));
		$(`[onclick="setDate('tdy')"]`).click();
	}

	function clearPageAct() {
		pageAct.startdate = null;
		pageAct.enddate = null;
		pageAct.serial_number = null;
	}

	function clearOpeRecPageAct() {
		pageAct.selAreaTag = null;
		pageAct.selBuiTag = null;
		pageAct.selFloTag = null;
	}

	function snSearch() {
		clearPageAct();
		pageAct.serial_number = $('#serial_number').val() || null;
		refTable();
	}

	function sysList() {
		let url = baseApiUrl + "/api/GetMainSub";
		let sendData = {
			building_tag: pageAct.buiTag
		}
		objSendData.Data = sendData;
		function success(res) {
			let mainStrHtml = ``;
			let subStrHtml = ``;
			let display = pageAct.mainStatus ? "hidden" : "";

			$.each(res.data.history_Main_Systems, function (i, v) {
				if (pageAct.mainStatus) {
					mainStrHtml += `<div class="custom-control custom-checkbox custom-control-inline">
										<input type="checkbox" class="custom-control-input" data-type="main" id="${v.main_system_tag}">
										<label class="custom-control-label" for="${v.main_system_tag}">${v.full_name}</label>
									</div>`;
				}
				pageAct.selSysMain.push(v);
				$.each(v.history_Sub_systems, function (i2, v2) {
					subStrHtml += `<div class="custom-control custom-checkbox custom-control-inline" data-main="${v.main_system_tag}" ${display}>
										<input type="checkbox" class="custom-control-input" data-type="sub" id="${v2.sub_system_tag}">
										<label class="custom-control-label" for="${v2.sub_system_tag}">${v2.full_name}</label>
									</div>`;

					pageAct.selSysSub.push(v2);
				});
			});
			
			if (pageAct.mainStatus) {
				$('#mainList').html(mainStrHtml);
				$('#subList').html(subStrHtml);
			}
			else {
				$('#mainList').html(subStrHtml);
			}	
			
			if (pageAct.sub_system_tag != null) {
				$.each(pageAct.sub_system_tag, function (i, v) {
					$('#' + v).click();
				});
			}
		}
		ytAjax = new YourTeam.Ajax(url, objSendData, success, null, "POST").send();
	}

	function refTable() {
		if (pageAct.work_type == null)
			loadOpeFirmTable();
		else
			loadOpeRecTable();
	}

	function exportExcel() {
		let url = baseApiUrl + "/operation/OpeExportExcel";

		objSendData.Data = {
			work_type: pageAct.work_type,
			startdate: pageAct.startdate == undefined ? null : pageAct.startdate,
			enddate: pageAct.enddate == undefined ? null : pageAct.enddate,
		};

		ytAjax = new YourTeam.Ajax(url, objSendData, function (rel) {
			if (rel.code == "0000")
				location.href = baseApiUrl + "/api/df?path=" + rel.data.split('/')[0] + "&fileName=" + rel.data.split('/')[1] + "&token=" + localStorage.getItem("JWT-Authorization");
		}, null, "POST").send();
	}

	function selSysMain() {
		$("#inpFirmSelSysMain").html();
		$("#inpFirmSelSysSub").html();
		let mainStrHtml = ``;
		let subStrHtml = ``;
		$.each(pageAct.selSysMain, (index, roleObj) => {
			let selected = index == 0 ? "selected" : "";
			mainStrHtml += `<option value='${roleObj.main_system_tag}' ${selected}>${roleObj.full_name}</option>`;

			$.each(roleObj.history_Sub_systems, (index2, roleObj2) => {
				subStrHtml += `<option value='${roleObj2.sub_system_tag}' data-main='${roleObj.main_system_tag}' ${selected} hidden>${roleObj2.full_name}</option>`;
			});
		});

		$("#inpFirmSelSysMain").html(mainStrHtml);
		$("#inpFirmSelSysSub").html(subStrHtml);
		$(`[data-main=` + $("#inpFirmSelSysMain").find('option:selected').val() + `]`).attr('hidden', false);
	}

	function selDevice() {
		let url = baseApiUrl + "/operation/DevList";
		let lsst = [];
		pageAct.selSysSub.map(function (v, i) { lsst.push(v.sub_system_tag.toString()); });
		sendData = {
			device_area_tag: pageAct.AreaTag,
			device_building_tag: pageAct.buiTag,
			list_sub_system_tag: lsst,
		};
		objSendData.Data = sendData;
		ytAjax = new YourTeam.Ajax(url, objSendData, function (res) {
			if (!res || res.code != "0000" || !res.data) {

			} else {
				strHtml = ``;
				$("#inpFixDoCode").html();
				$.each(res.data, (index, roleObj) => {
					strHtml += `<option value='${roleObj.device_number}' data-floor=${roleObj.device_floor_tag} data-main=${roleObj.device_system_tag} data-sub=${roleObj.device_name_tag}>${roleObj.device_name}</option>`;

					if (index == 0)
						pageAct.sysSub = roleObj.device_name_tag
				})
				$("#inpFixDoCode").html(strHtml);
			}
		}, null, "POST").send();
	}

	function selUser() {
		let url = baseApiUrl + "/User/UserManagerList";
		ytAjax = new YourTeam.Ajax(url, objSendData, function (res) {
			if (!res || res.code != "0000" || !res.data) {

			} else {
				$("#inpWorPerId").html();
				strHtml = ``;
				strHtml += `<option value=''>未選擇</option>`;
				$.each(res.data, (index, roleObj) => {
					strHtml += `<option value='${roleObj.userinfo_guid}'>${roleObj.full_name}</option>`;
				})
				$("#inpWorPerId").html(strHtml);
			}
		}, null, "POST").send();
	}

	function selOpeFir() {
		let url = baseApiUrl + "/operation/OpeFirSel";
		objSendData.Data = { sub_system_tag: [pageAct.sysSub] };
		ytAjax = new YourTeam.Ajax(url, objSendData, function (res) {
			if (!res || res.code != "0000" || !res.data) {

			} else {
				$("#inpFixFirm").html();
				strHtml = ``;
				strHtml += `<option value=''>未選擇</option>`;
				$.each(res.data, (index, roleObj) => {
					strHtml += `<option value='${roleObj.id}'>${roleObj.name}</option>`;
				})
				$("#inpFixFirm").html(strHtml);
			}
		}, null, "POST").send();
	}

	function selAllSysVal(elem) {
		//loading process
		if ($(elem).html() == '全選類別') {
			$('#mainList input').map(function (i, v) {
				if (!$(v).is(':checked')) {
					$(v).click();
				}
			});
			$('#subList input').map(function (i, v) {
				if (!$(v).is(':checked')) {
					$(v).click();
				}
			});
			$(elem).html('取消全選');
		}
		else {
			$('#mainList input').map(function (i, v) {
				if ($(v).is(':checked')) 
					$(v).click();
			});
			$('#subList input').map(function (i, v) {
				if ($(v).is(':checked'))
					$(v).click();
			});
			$(elem).html('全選類別');
		}

		refTable();
		//end loading
	}

	function event() {
		onEvent('click', '#newForm', function () {

			if (pageAct.work_type == null) {
				pageAct.opeFirmAct = 'add';
				$('#opeFirmTitle').html('新增廠商資料');
				$('#opeFirmModal input').map(function (i, v) { $(v).val('') });
			}
			else {
				clearOpeRecPageAct();
				pageAct.opeRecId = null;
				pageAct.imageFile = [];
				$('#opeRecTitle').html(pageAct.work_type == 1 ? "新增保養" : "新增維修");
				$('#opeRecModal input').map(function (i, v) { $(v).val('') });
				let today = displayDate(new Date(Date.now()), 'date').replaceAll('/', '-');
				$('#opeRecModal input[id*=Time]').map(function (i, v) { $(v).val(today) });
				selUser();
				selDevice();
				selOpeFir();
				$('#forImage').html('');
			}

			selSysMain();
		});

		onEvent('click', '#opeFirmEdiBtn', function () {
			$('#opeFirmTitle').html('編輯廠商資料');
			let url = baseApiUrl + "/operation/OpeFirRead";
			pageAct.opeFirmId = $(this).parent().data('id')
			objSendData.Data = { id: pageAct.opeFirmId };
			ytAjax = new YourTeam.Ajax(url, objSendData, function (res) {
				if (!res || res.code != "0000" || !res.data) {

				} else {
					pageAct.opeFirmAct = 'edit';
					$('#opeFirmForm select[id=inpFirmSelSysMain]').val(res.data.device_system_category_layer2).change();
					$('#opeFirmForm select[id=inpFirmSelSysSub]').val(res.data.device_system_category_layer3).change();
					$('#opeFirmForm input[id=inpName]').val(res.data.name);
					$('#opeFirmForm input[id=inpConPer]').val(res.data.contact_person);
					$('#opeFirmForm input[id=inpPhone]').val(res.data.phone);
					$('#opeFirmForm input[id=inpEmail]').val(res.data.email);
					$('#opeFirmForm input[id=inpTaxIdNum]').val(res.data.tax_id_number);
					$('#opeFirmForm input[id=inpRemark]').val(res.data.remark);
				}
			}, null, "POST").send()
		});

		onEvent('click', '#OpeFirmSendBtn', function () {
			let form = $("#opeFirmForm");

			$(form).validate({
				rules: {
					inpFirmSelSysMain: { required: true },
					inpFirmSelSysSub: { required: true },
					inpName: { required: true, maxlength: 50 }
				}
			});
			if ($(form).valid()) {
				let url = baseApiUrl + "/operation/" + (pageAct.opeFirmAct == "add" ? 'SaveOpeFirm' : 'EdtOneOpeFirm');
				let sendData = {
					device_system_category_layer2: $('#inpFirmSelSysMain').val(),
					device_system_category_layer3: $('#inpFirmSelSysSub').val(),
					name: $("#inpName").val() || null,
					contact_person: $("#inpConPer").val() || null,
					phone: $("#inpPhone").val() || null,
					email: $("#inpEmail").val() || null,
					tax_id_number: $("#inpTaxIdNum").val() || null,
					remark: $("#inpRemark").val() || null
				};

				if (pageAct.opeFirmAct == "edit")
					sendData.id = pageAct.opeFirmId;

				objSendData.Data = sendData;

				ytAjax = new YourTeam.Ajax(url, objSendData, function (res) {
					if (!res || res.code != "0000" || !res.data) {

					} else {
						//toast_ok(common.AddSuc);
						//$("#opeFirmModal").modal("hide");
						$("#OpeFirmCanBtn").click();
						refTable();
					}
				}, null, "POST").send();
			}
		});

		onEvent('click', '#opeFirmDelBtn', function () {
			pageAct.opeRecId = null;
			pageAct.opeFirmId = $(this).parent().data('id');
		});

		onEvent('click', '#confirmDelBtn', function () {
			objSendData.Data = { id: pageAct.opeFirmId ?? pageAct.opeRecId };
			let url = baseApiUrl + "/operation/" + (pageAct.work_type == null ? "DelOpeFirm" : "DelOpeRecord");

			ytAjax = new YourTeam.Ajax(url, objSendData, function (res) {
				if (!res || res.code != "0000" || !res.data) {

				} else {
					//toast_ok(common.AddSuc);
					//$("#delModal").modal("hide");
					$("#confirmDelCanBtn").click();
					refTable();
				}
			}, null, "DELETE").send();
		});

		onEvent('click', '#opeRecDelBtn', function () {
			pageAct.opeRecId = $(this).parent().data('id');
			pageAct.opeFirmId = null;
		});

		onEvent('click', '#OpeRecSendBtn', function () {
			let form = $("#opeRecForm");
			let gmtTime = 28800000;
			$(form).validate({
				rules: {
					inpWorTyp: { required: true},
					inpFixDo: { required: true },
					inpFixDoCode: { required: true },
					inpFixFirm: { required: true },
					inpStatus: { required: true },
					inpWorPerId: { required: true },
				}
			});

			if ($(form).valid()) {
				let url = baseApiUrl + "/operation/SavOpeRecord";

				let fd = new FormData();
				$.each(pageAct.imageFile, function (i, v) {
					fd.append("lorf[" + i + "].id", v.id);
					fd.append("lorf[" + i + "].file", v.file);
					fd.append("lorf[" + i + "].save_file_name", v.save_file_name);
					fd.append("lorf[" + i + "].ori_file_name", v.ori_file_name);
				});
				fd.append("location", $('#inpArea option:selected').text() + $('#inpBuilding option:selected').text() + $('#inpFloor option:selected').text());
				fd.append("location_code", $('#inpArea').val().toString() + $('#inpBuilding').val().toString() + $('#inpFloor').val().toString());
				fd.append("device_system_category_layer2", $('#inpRecSelSysMain').val());
				fd.append("device_system_category_layer3", $('#inpRecSelSysSub').val());
				fd.append("work_type", parseInt($('#inpWorTyp').val()));
				fd.append("fix_do", $('#inpFixDo').val());
				fd.append("fix_do_code", $('#inpFixDoCode').val());
				fd.append("fix_firm", parseInt($('#inpFixFirm').val()));
				fd.append("status", parseInt($('#inpStatus').val()));
				fd.append("work_person_id", $('#inpWorPerId').val());
				fd.append("start_time", ($('#inpStaTime').val() || null) == null ? null : new Date($('#inpStaTime').val()).toISOString());
				fd.append("end_time", ($('#inpEndTime').val() || null) == null ? $('#inpEndTime').val() : new Date($('#inpEndTime').val()).toISOString());
				fd.append("work_time", ($('#inpWorTime').val() || null) == null ? $('#inpWorTime').val() : new Date($('#inpWorTime').val()).toISOString());
				fd.append("finish_time", ($('#inpFinTime').val() || null) == null ? null : new Date($('#inpFinTime').val()).toISOString());
				fd.append("notice", $('#inpNotice').val() || null);
				fd.append("description", $('#inpDescription').val() || null);
				
				//let sendData = {
				//	location: $('#inpArea option:selected').text() + $('#inpBuilding option:selected').text() + $('#inpFloor option:selected').text(),
				//	location_code: $('#inpArea').val().toString() + $('#inpBuilding').val().toString() + $('#inpFloor').val().toString(),
				//	device_system_category_layer2: $('#inpRecSelSysMain').val(),
				//	device_system_category_layer3: $('#inpRecSelSysSub').val(),
				//	work_type: parseInt($('#inpWorTyp').val()),
				//	fix_do: $('#inpFixDo').val(),
				//	fix_do_code: $('#inpFixDoCode').val(),
				//	fix_firm: parseInt($('#inpFixFirm').val()),
				//	status: parseInt($('#inpStatus').val()),
				//	work_person_id: $('#inpWorPerId').val(),
				//	start_time: $('#inpStaTime').val() == null ? null : new Date(new Date($('#inpStaTime').val()).getTime() + gmtTime),
				//	end_time: $('#inpEndTime').val() == null ? $('#inpEndTime').val() : new Date(new Date($('#inpEndTime').val()).getTime() + gmtTime),
				//	work_time: $('#inpWorTime').val() == null ? $('#inpWorTime').val() : new Date(new Date($('#inpWorTime').val()).getTime() + gmtTime),
				//	finish_time: $('#inpFinTime').val() == null ? null : new Date(new Date($('#inpFinTime').val()).getTime() + gmtTime),
				//	notice: $('#inpNotice').val() || null,
				//	description: $('#inpDescription').val() || null,
				//	lorf: pageAct.imageFile,
				//};
				if (pageAct.opeRecId != null)
					fd.append("id", pageAct.opeRecId);
				
				objSendData.Data = sendData;
				$.ajax({
					url: url,
					type: "POST",
					data: fd,
					async: false,
					cache: false,
					contentType: false,
					processData: false,
					beforeSend: function (xhr) { xhr.setRequestHeader('Authorization', "Bearer " + localStorage.getItem("JWT-Authorization")) },
					success: function (res) {
						if (!res || res.code != "0000" || !res.data) {

						} else {
							//toast_ok(common.AddSuc);
							//$("#opeFirmModal").modal("hide");
							$("#OpeRecCanBtn").click();
							refTable();
						}
					}
				});

				//ytAjax = new YourTeam.Ajax(url, objSendData, function (res) {
				//	if (!res || res.code != "0000" || !res.data) {

				//	} else {
				//		//toast_ok(common.AddSuc);
				//		//$("#opeFirmModal").modal("hide");
				//		$("#OpeRecCanBtn").click();
				//		refTable();
				//	}
				//}, null, "POST").send();
			}
		});

		onEvent('click', '#opeRecEdiBtn', function () {
			clearOpeRecPageAct();
			selUser();
			pageAct.imageFile = [];
			$('#opeRecTitle').html(pageAct.work_type == 1 ? "編輯保養" : "編輯維修");
			let url = baseApiUrl + "/operation/OpeRecRead";
			pageAct.opeRecId = $(this).parent().data('id');
			objSendData.Data = { id: pageAct.opeRecId };
			ytAjax = new YourTeam.Ajax(url, objSendData, function (res) {
				if (!res || res.code != "0000" || !res.data) {

				} else {
					$('#inpWorTyp').val(res.data.work_type);
					$('#inpFixDo').val(res.data.fix_do);
					$('#inpFixDoCode').val(res.data.fix_do_code);
					$('#inpFixFirm').val(res.data.fix_firm);
					$('#inpStatus').val(res.data.status);
					$('#inpWorPerId').val(res.data.work_person_id);
					//$('#inpStaTime').val(displayDate(res.data.start_time, 'datetime').replace(' ', 'T').replaceAll('/', '-'));
					//$('#inpEndTime').val(displayDate(res.data.end_time, 'datetime').replace(' ', 'T').replaceAll('/', '-'));
					//$('#inpWorTime').val(displayDate(res.data.work_time, 'datetime').replace(' ', 'T').replaceAll('/', '-'));
					//$('#inpFinTime').val(displayDate(res.data.finish_time, 'datetime').replace(' ', 'T').replaceAll('/', '-'));
					$('#inpNotice').text(res.data.notice);
					$('#inpDescription').text(res.data.description);
					let strHtml = ``;
					$.each(res.data.lorf, function (i, v) {
						let extName = v.ori_file_name.split('.')[1];
						let divMargin = (i == 0) ? `style='margin-top: 2px'` : ``;
						strHtml += `<div class="file-item" data-id=${v.id} ${divMargin}>
										<a href="${baseApiUrl}/upload/operation/${v.save_file_name}.${extName}" download="${v.ori_file_name}" target="_blank">
											<img data-filename=${v.ori_file_name} data-savename=${v.save_file_name} height="70px" width="150px" src="${baseApiUrl}/upload/operation/${v.save_file_name}.${extName}">
											<button class="btn-info" name="btnDelImg"><i class="fa fa-times"></i></button>
										</a>
									</div>`;
					});
					$('#forImage').html(strHtml);
				}
			}, null, "POST").send()
		});

		onEvent("change", "#myImage", function (e) {
			var imageuploadFormOS = 0;
			let fileHelper = new YourTeam.Utility.File();
			//若有文字顯示,清除文字顯示
			if ($('#forImage p').length > 0) {
				$("#forImage").html(""); // 清除預覽
			}
			//console.log(this.files)
			imageuploadFormOS = this.files.length;
			//最多只能上傳幾張
			let maxlength = $("#forImage").data("maxlength");
			if (maxlength) {
				if (imageuploadFormOS + $('#forImage img').length > maxlength) {
					ShowModal("error", "uplImgOverLen", "無法上傳", "最多只能上傳" + maxlength + "張,您已經超出上傳數量。");
					$("#myImage").val("");
					return false;
				}
			}
			if (/\.(jpe?g|png|gif)$/i.test(this.file.name))
			fileHelper.readAndPreviewImages(this.files, 'forImage', 150, 70, '<div class="file-item">', '<button class="btn-info" name="btnDelImg" ><i class="fa fa-times"></i></button></div>');
			$.each(this.files, function (i, v) {
				let fd = new FormData();
				let file = v;
				fd.append('file', v);
				pageAct.imageFile.push({ "ori_file_name": v.name, "save_file_name": file.guid, "file": fd.get("file") });
			});
		}); //變更圖片

		onEvent("click", "[name=btnDelImg]", function () {
			elem = $(this).parent();
			if (elem.attr('data-id'))
				pageAct.imageFile.push({ "id": elem.data('id'), "ori_file_name": elem.find('img').data('filename'), "save_file_name": elem.find('img').data('savename') });
			else {
				pageAct.imageFile =
					$.grep(pageAct.imageFile, function (image) {
						return image.save_file_name != elem.find('img').data('savename');
					});
			}

			elem.remove();
		});

		onEvent("change", "#inpFirmSelSysMain", function () {
			let mainTag = $("#inpFirmSelSysMain").find('option:selected').val();
			$(`[data-main=${mainTag}]`).attr('hidden', false);
			$('#inpFirmSelSysSub').find(`option[data-main!=${mainTag}]`).attr('hidden', true);
			$(`#inpFirmSelSysSub option`).removeAttr('selected');
			$($(`#inpFirmSelSysSub option[data-main=${mainTag}]`)[0]).attr('selected', 'selected')
		});

		onEvent("change", "#inpFixDoCode", function () {
			elemSel = $(this).find('option:selected');
			pageAct.sysSub = elemSel.data('sub');
			pageAct.sysMain = elemSel.data('main');
			pageAct.floor = elemSel.data('floor');
			pageAct.number = elemSel.val();
			selOpeFir();
			errCodeList();
		});

	}

	function errCodeList() {
		let _pathArr = pageAct.number.split("_"); //TPE_B1_ELEV_EL_R2F_NA_ELEV1_N1
		let _devicePath = _pathArr[0] + "_" + _pathArr[1] + "_" + _pathArr[2] + "_" + _pathArr[3] + "_" + _pathArr[4] + "_" + _pathArr[5];
		getOneDeviceAlarmTop10ByBaja(_devicePath, callbackForErr);
	}

	function callbackForErr(res) {
		console.log(res);
	}
</script>