<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_2" 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" data-backdrop="static" data-keyboard="false">
	<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_2" tabindex="-1" role="dialog" aria-hidden="true" data-backdrop="static" data-keyboard="false">
	<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_2">
				<div class="modal-body">
					<div class="row">
						<div class="col-md-6">
							<div class="form-group">
								<label class="form-label" for="inpNumber_2">表單編號</label>
								<input type="text" id="inpNumber_2" name="" class="form-control" disabled>
							</div>
						</div>
						<div class="col-md-6">
							<div class="form-group">
								<label class="form-label" for="inpErrCode_2">異常編號</label>
								<select class="form-control" id="inpErrCode_2" name="inpErrCode_2">
									<option value=''>未選擇</option>
								</select>
							</div>
						</div>
						<div class="col-md-6">
							<div class="form-group">
								<label class="form-label" for="inpStaTime_2">預計開始時間</label>
								<input type="date" id="inpStaTime_2" name="inpStaTime_2" class="form-control">
							</div>
						</div>
						<div class="col-md-6">
							<div class="form-group">
								<label class="form-label" for="inpWorTyp_2">項目</label>
								<select class="form-control custom-select-ri" id="inpWorTyp_2" name="inpWorTyp_2" 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_2">維修項目</label>
								<input type="text" id="inpFixDo_2" name="inpFixDo_2" class="form-control">
							</div>
						</div>
						<div class="col-md-6">
							<div class="form-group">
								<label class="form-label" for="inpFixDoCode_2">維修項目代碼(設備編號)</label>
								<select class="form-control" id="inpFixDoCode_2" name="inpFixDoCode_2">
									<option value=''>未選擇</option>
								</select>
							</div>
						</div>
						<div class="col-md-6">
							<div class="form-group">
								<label class="form-label" for="inpFixFirm_2">負責廠商</label>
								<select class="form-control" id="inpFixFirm_2" name="inpFixFirm_2">
									<option value=''>未選擇</option>
								</select>
							</div>
						</div>
						<div class="col-md-6">
							<div class="form-group">
								<label class="form-label" for="inpStatus_2">狀態</label>
								<div class="form-control" id="inpStatus_2">
									<div class="row container">
										<div class="">
											<input class="custom-radio-input" type="radio" name="inpSta_2" id="inpSta_2_0" value="0" data-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_2" id="inpSta_2_1" value="1" data-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_2">工作人員編號</label>
								<select class="form-control" id="inpWorPerId_2" name="inpWorPerId_2">
									<option value=''>未選擇</option>
								</select>
							</div>
						</div>
						<div class="col-md-12">
							<div class="form-group">
								<label class="form-label" for="inpNotice_2">注意事項</label>
								<textarea class="form-control" type="text" id="inpNotice_2" name="inpNotice_2" rows="7"></textarea>
							</div>
						</div>
						<div class="col-md-12">
							<div class="form-group">
								<label class="form-label" for="inpDescription_2">結果描述</label>
								<textarea class="form-control" type="text" id="inpDescription_2" name="inpDescription_2" rows="7"></textarea>
							</div>
						</div>
						<div class="col-md-12">
							<label class="form-label">上傳檔案</label>
							<div id='ope_forImage_2' class="col-sm-12 forimage mt-2 p-0">
							</div>
							<div id='ope_forFile_2' class="col-sm-12 forfile mt-2 p-0">
							</div>

							<div class="form-group dropzone" id="ope_dropZone_2">
								<div class="dz-message">
									<div class="drag-icon-cph">
										<i class="material-icons">backup</i>
									</div>
									<h3>選擇一個文件或拖放到這裡</h3>
									<p class="mb-0 col-grey">
										PDF檔案不超過 10MB
									</p>
								</div>
								<div class="fallback">
									<input name="file" type="file" multiple />
								</div>
							</div>
						</div>
					</div>
				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-secondary" id="OpeRecCanBtn_2" data-dismiss="modal">關閉</button>
					<button type="button" class="btn btn-primary" id="OpeRecSendBtn_2" e-prevent>儲存</button>
				</div>
			</form>
		</div>
	</div>
</div>

<!-- Modal center 保養 -->
<div class="modal fade" id="opeRecModal" tabindex="-1" role="dialog" aria-hidden="true" data-backdrop="static" data-keyboard="false">
	<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="inpNumber">表單編號</label>
								<input type="text" id="inpNumber" name="" class="form-control" disabled>
							</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" data-value="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" data-value="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-12">
							<label class="form-label">上傳檔案</label>
							<div id='ope_forImage' class="col-sm-12 forimage mt-2 p-0">
							</div>
							<div id='ope_forFile' class="col-sm-12 forfile mt-2 p-0">
							</div>

							<div class="form-group dropzone" id="ope_dropZone">
								<div class="dz-message">
									<div class="drag-icon-cph">
										<i class="material-icons">backup</i>
									</div>
									<h3>選擇一個文件或拖放到這裡</h3>
									<p class="mb-0 col-grey">
										PDF檔案不超過 10MB
									</p>
								</div>
								<div class="fallback">
									<input name="file" type="file" multiple />
								</div>
							</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" data-backdrop="static" data-keyboard="false">
	<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 () {
		initDropzone();
		pageAct.sub_system_tag = null;
		pageAct.main_system_tag = null;
		pageAct.selSysSub = [];
		pageAct.selSysMain = [];
		pageAct.imageFile = [];

		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');
		$('#opeRecTable_2_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');

		$('#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" + (pageAct.work_type == "2" ? "_2" : "");
		let column_defs = [];
		let columns = [];
		if (pageAct.work_type == "2") {
			$('#opeRecTable_wrapper').css('display', 'none');
			$('#opeRecTable_2_wrapper').css('display', 'block');

			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 },
			];

			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) {
						ope_imgHtml = null;
						$.each(data, function (i, v) {
							let extName = v.ori_file_name.split('.')[1];
							if (i == 0)
								ope_imgHtml = creDiv(["file-item"], null, null, null, { id: v.id });
							if (i < 3) {
								if (/\.(jpe?g|png|gif)$/i.test(v.ori_file_name)) {
									ope_colA = creEle("a", null, null, null, null, null, { href: baseApiUrl + "/upload/operation/" + v.save_file_name + "." + extName, download: v.ori_file_name, target: "_blank", style: "cursor: pointer" });
									ope_colImg = creImg("img", null, null, null, null, { filename: v.ori_file_name, savename: v.save_file_name }, { style: "margin-left: 30px", height: "70px", width: "50px", src: baseApiUrl + "/upload/operation/" + v.save_file_name + "." + extName });
									ope_colA.append(ope_colImg);
									ope_imgHtml.append(ope_colA);
								}
								else if (/\.(xls?x|doc?x|ptt?x|pdf|zip|rar|7zip|txt|odt|xml|rtf|ods|odp|pps?x)$/i.test(v.ori_file_name)) {
									icons = null
									if (extName == "xlsx" || extName == xls)
										icons = "fas fa-file-excel";
									else if (extName == "pdf" || extName == "ods")
										icons = "fas fa-file-pdf";
									else if (extName == "doc" || extName == "docx")
										icons = "fas fa-file-word";
									else
										icons = "fas fa-file-alt";

									ope_colI = creEle("i", null, null, null, [icons + " fa-3x m-1"]);
									ope_colA = creEle("a", null, null, null, null, { filename: v.ori_file_name, savename: v.save_file_name }, { href: baseApiUrl + "/upload/operation/" + v.save_file_name + "." + extName, download: v.ori_file_name, style: "margin-left: 30px" });
									ope_colA.append(ope_colI);
									ope_imgHtml.append(ope_colA);
								}
							}
						});

						return ope_imgHtml ? ope_imgHtml.outerHtml() : null;
					}
				},
				{
					"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_2" }));
						btnDiv.append(creBtnHtml("刪除", "opeRecDelBtn", null, ["btn", "btn-danger"], { "toggle": "modal", "target": "#delModal" }));
						return btnDiv.outerHtml();
					}
				},
			];
		}
		else if (pageAct.work_type == "1") {
			$('#opeRecTable_wrapper').css('display', 'block');
			$('#opeRecTable_2_wrapper').css('display', 'none');

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

			columns = [
				{
					"title": "項目",
					"data": "work_type_name",
				},
				{
					"title": "位置",
					"data": "location",
				},
				{
					"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) {
						ope_imgHtml = null;
						$.each(data, function (i, v) {
							let extName = v.ori_file_name.split('.')[1];
							if (i == 0)
								ope_imgHtml = creDiv(["file-item"], null, null, null, { id: v.id });
							if (i < 3) {
								if (/\.(jpe?g|png|gif)$/i.test(v.ori_file_name)) {
									ope_colA = creEle("a", null, null, null, null, null, { href: baseApiUrl + "/upload/operation/" + v.save_file_name + "." + extName, download: v.ori_file_name, target: "_blank", style: "cursor: pointer" });
									ope_colImg = creImg("img", null, null, null, null, { filename: v.ori_file_name, savename: v.save_file_name }, { style: "margin-left: 30px", height: "70px", width: "50px", src: baseApiUrl + "/upload/operation/" + v.save_file_name + "." + extName });
									ope_colA.append(ope_colImg);
									ope_imgHtml.append(ope_colA);
								}
								else if (/\.(xls?x|doc?x|ptt?x|pdf|zip|rar|7zip|txt|odt|xml|rtf|ods|odp|pps?x)$/i.test(v.ori_file_name)) {
									icons = null
									if (extName == "xlsx" || extName == xls)
										icons = "fas fa-file-excel";
									else if (extName == "pdf" || extName == "ods")
										icons = "fas fa-file-pdf";
									else if (extName == "doc" || extName == "docx")
										icons = "fas fa-file-word";
									else
										icons = "fas fa-file-alt";

									ope_colI = creEle("i", null, null, null, [icons + " fa-3x m-1"]);
									ope_colA = creEle("a", null, null, null, null, { filename: v.ori_file_name, savename: v.save_file_name }, { href: baseApiUrl + "/upload/operation/" + v.save_file_name + "." + extName, download: v.ori_file_name, style: "margin-left: 30px" });
									ope_colA.append(ope_colI);
									ope_imgHtml.append(ope_colA);
								}
							}
						});

						return ope_imgHtml ? ope_imgHtml.outerHtml() : null;
					}
				},
				{
					"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 {
			$(pageAct.work_type == '1' ? '#inpWorTyp' : '#inpWorTyp_2').val(wt);
			$('#newForm').attr('data-target', pageAct.work_type == "1" ? '#opeRecModal' : '#opeRecModal_2');
			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=" + cookies.get("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 = ``;
				$(pageAct.work_type == '1' ? "#inpFixDoCode" : "#inpFixDoCode_2").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.sysMain = roleObj.device_system_tag;
						pageAct.sysSub = roleObj.device_name_tag;
						pageAct.floor = roleObj.device_floor_tag;
						pageAct.number = roleObj.device_number;
					}
				})
				$(pageAct.work_type == '1' ? "#inpFixDoCode" : "#inpFixDoCode_2").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 {
				$(pageAct.work_type == '1' ? "#inpWorPerId" : "#inpWorPerId_2").html();
				strHtml = ``;
				strHtml += `<option value=''>未選擇</option>`;
				$.each(res.data, (index, roleObj) => {
					strHtml += `<option value='${roleObj.userinfo_guid}'>${roleObj.full_name}</option>`;
				})
				$(pageAct.work_type == '1' ? "#inpWorPerId" : "#inpWorPerId_2").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 {
				$(pageAct.work_type == '1' ? "#inpFixFirm" : "#inpFixFirm_2").html();
				strHtml = ``;
				strHtml += `<option value=''>未選擇</option>`;
				$.each(res.data, (index, roleObj) => {
					strHtml += `<option value='${roleObj.id}'>${roleObj.name}</option>`;
				})
				$(pageAct.work_type == '1' ? "#inpFixFirm" : "#inpFixFirm_2").html(strHtml);
			}
		}, null, "POST").send();
	}

	function selAllSysVal(elem) {
		$(loadEle).Loading("start");
		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();
		$(loadEle).Loading("close");
	}

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

			if (pageAct.work_type == null) {
				pageAct.opeFirmAct = 'add';
				$('#opeFirmTitle').html('新增廠商資料');
				$('#opeFirmModal input').map(function (i, v) { $(v).val('') });
				$('#opeFirmModal [id*=-error]').hide();
			}
			else {
				clearOpeRecPageAct();
				$('#' + (pageAct.work_type == '1' ? 'opeRecForm' : 'opeRecForm_2') + ' [id*=-error]').hide();
				pageAct.opeRecId = null;
				pageAct.imageFile = [];
				$(pageAct.work_type == '1' ? '#opeRecTitle' : '#opeRecTitle_2').html(pageAct.work_type == 1 ? "新增保養" : "新增維修");
				$(pageAct.work_type == '1' ? '#opeRecModal input' : '#opeRecModal_2 input').map(function (i, v) { $(v).val('') });
				let today = displayDate(new Date(Date.now()), 'date').replaceAll('/', '-');
				$(pageAct.work_type == '1' ? '#opeRecModal input[id*=Time]' : '#opeRecModal_2 input[id*=Time]').map(function (i, v) { $(v).val(today) });
				$(pageAct.work_type == '1' ? '#ope_forImage' : '#ope_forImage_2').html('');
				$(pageAct.work_type == '1' ? '#ope_forFile' : '#ope_forFile_2').html('');
				$(pageAct.work_type == '1' ? '#inpDescription' : '#inpDescription_2').val('');
				$(pageAct.work_type == '1' ? '#inpNotice' : '#inpNotice_2').val('');
				$(pageAct.work_type == '1' ? '#inpFixDo' : '#inpFixDo_2').val('');
				selUser();
				selDevice();
				selOpeFir();
				errCodeList();
				getFormId();
				getUser();
			}

			selSysMain();
		});

		onEvent('click', '#opeFirmEdiBtn', function () {
			selSysMain();
			$('#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.DelSuc);
					//$("#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, #OpeRecSendBtn_2', function () {
			let form = $(pageAct.work_type == '1' ? "#opeRecForm" : "#opeRecForm_2");
			if (pageAct.work_type == '1') {
				$(form).validate({
					rules: {
						inpWorTyp: { required: true },
						inpFixDo: { required: true },
						inpFixDoCode: { required: true },
						inpFixFirm: { required: true },
						inpStatus: { required: true },
						inpWorPerId: { required: true },
					}
				});
			}
			else {
				$(form).validate({
					rules: {
						inpWorTyp_2: { required: true },
						inpFixDo_2: { required: true },
						inpFixDoCode_2: { required: true },
						inpFixFirm_2: { required: true },
						inpStatus_2: { required: true },
						inpWorPerId_2: { 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("error_code", $(pageAct.work_type == "1" ? '#inpErrCode' : '#inpErrCode_2').val());
				fd.append("location", "台北" + $('#buiActDrop').text() + pageAct.floor);
				fd.append("location_code", pageAct.AreaTag + pageAct.buiTag + pageAct.floor);
				fd.append("device_system_category_layer2", pageAct.sysMain);
				fd.append("device_system_category_layer3", pageAct.sysSub);
				fd.append("work_type", parseInt($(pageAct.work_type == "1" ? '#inpWorTyp' : '#inpWorTyp_2').val()));
				fd.append("fix_do", $(pageAct.work_type == "1" ? '#inpFixDo' : '#inpFixDo_2').val());
				fd.append("fix_do_code", $(pageAct.work_type == "1" ? '#inpFixDoCode' : '#inpFixDoCode_2').val());
				fd.append("fix_firm", parseInt($(pageAct.work_type == "1" ? '#inpFixFirm' : '#inpFixFirm_2').val()));
				fd.append("status", parseInt($('#' + (pageAct.work_type == '1' ? 'inpStatus' : 'inpStatus_2') + ' [name=' + (pageAct.work_type == '1' ? 'inpSta' : 'inpSta_2') + ']:checked').data('value')));
				fd.append("work_person_id", $(pageAct.work_type == "1" ? '#inpWorPerId' : '#inpWorPerId_2').val());
				fd.append("start_time", ($(pageAct.work_type == "1" ? '#inpStaTime' : '#inpStaTime_2').val() || null) == null ? null : new Date($(pageAct.work_type == "1" ? '#inpStaTime' : '#inpStaTime_2').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", (parseInt($('#' + (pageAct.work_type == '1' ? 'inpStatus' : 'inpStatus_2') + ' [name=' + (pageAct.work_type == '1' ? 'inpSta' : 'inpSta_2') + ']:checked').data('value'))) == 1 ? new Date(Date.now()).toISOString() : null);
				fd.append("notice", $(pageAct.work_type == "1" ? '#inpNotice' : '#inpNotice_2').val() || null);
				fd.append("description", $(pageAct.work_type == "1" ? '#inpDescription' : '#inpDescription_2').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 " + cookies.get("JWT-Authorization")) },
					success: function (res) {
						if (!res || res.code != "0000" || !res.data) {

						} else {
							toast_ok(common.AddSuc);
							//$("#opeFirmModal").modal("hide");
							$(pageAct.work_type == '1' ? "#OpeRecCanBtn" : "#OpeRecCanBtn_2").click();
							refTable();
						}
					}
				});
			}
		});

		onEvent('click', '#opeRecEdiBtn', function () {
			clearOpeRecPageAct();
			selUser();
			selDevice();

			$('#ope_forImage').html('');
			$('#ope_forFile').html('');
			$('#ope_forImage_2').html('');
			$('#ope_forFile_2').html('');

			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 {
					pageAct.sysSub = res.data.device_system_category_layer3;
					pageAct.number = res.data.fix_do_code;
					selOpeFir();
					errCodeList();
					$(pageAct.work_type == "1" ? '#inpNumber' : '#inpNumber_2').val(res.data.formId);
					$(pageAct.work_type == "1" ? '#inpWorTyp' : '#inpWorTyp_2').val(res.data.work_type);
					$(pageAct.work_type == "1" ? '#inpFixDo' : '#inpFixDo_2').val(res.data.fix_do);
					$(pageAct.work_type == "1" ? '#inpFixDoCode' : '#inpFixDoCode_2').val(res.data.fix_do_code);
					$(pageAct.work_type == "1" ? '#inpFixFirm' : '#inpFixFirm_2').val(res.data.fix_firm);
					$('#' + (pageAct.work_type == '1' ? 'inpStatus' : 'inpStatus_2') + ' [name=' + (pageAct.work_type == '1' ? 'inpSta' : 'inpSta_2') + '][data-value=' + res.data.status + ']').click();
					$(pageAct.work_type == "1" ? '#inpWorPerId' : '#inpWorPerId_2').val(res.data.work_person_id);
					$(pageAct.work_type == "1" ? '#inpStaTime' : '#inpStaTime_2').val(displayDate(res.data.start_time, 'date').replaceAll('/', '-'));
					$(pageAct.work_type == "1" ? '#inpNotice' : '#inpNotice_2').val(res.data.notice);
					$(pageAct.work_type == "1" ? '#inpDescription' : '#inpDescription_2').val(res.data.description);

					ope_imgHtml = null;
					$.each(res.data.lorf, function (i, v) {

						let extName = v.ori_file_name.split('.')[1];

						if (/\.(jpe?g|png|gif)$/i.test(v.ori_file_name)) {

							ope_colI = creEle("i", null, null, null, ["fa fa-times"]);
							ope_colBtn = creBtn(null, null, "btnDelImg", ["btn-dark m-1"]);
							ope_colImg = creImg("img", null, null, null, null, { filename: v.ori_file_name, savename: v.save_file_name }, { style: "margin-left: 30px; margin-top: 10px", height: "70px", width: "70px", src: baseApiUrl + "/upload/operation/" + v.save_file_name + "." + extName });
							ope_colA = creEle("a", null, null, null, null, null, { href: baseApiUrl + "/upload/operation/" + v.save_file_name + "." + extName, download: v.ori_file_name, target: "_blank" });
							ope_imgHtml = creEle("span", null, null, null, ["file-item m-1"], { id: v.id }, null);

							ope_colA.append(ope_colImg);
							ope_imgHtml.append(ope_colA);
							ope_colBtn.append(ope_colI);
							ope_imgHtml.append(ope_colBtn);
							$(pageAct.work_type == "1" ? '#ope_forImage' : '#ope_forImage_2').append(ope_imgHtml ? ope_imgHtml.outerHtml() : null);
						}
						else if (/\.(xls?x|doc?x|ptt?x|pdf|zip|rar|7zip|txt|odt|xml|rtf|ods|odp|pps?x)$/i.test(v.ori_file_name)) {
							icons = null
							if (extName == "xlsx" || extName == xls)
								icons = "fas fa-file-excel";
							else if (extName == "pdf" || extName == "ods")
								icons = "fas fa-file-pdf";
							else if (extName == "doc" || extName == "docx")
								icons = "fas fa-file-word";
							else
								icons = "fas fa-file-alt";

							ope_colI = creEle("i", null, null, null, ["fa fa-times"]);
							ope_colBtn = creBtn(null, null, "btnDelImg", ["btn-dark m-1"]);
							ope_colBtn.append(ope_colI);

							ope_colI = creEle("i", null, null, null, [icons + " fa-3x m-1"]);
							ope_colA = creEle("a", v.ori_file_name, null, null, null, null, { href: baseApiUrl + "/upload/operation/" + v.save_file_name + "." + extName, download: v.ori_file_name, target: "_blank" });
							ope_imgHtml = creEle("div", null, null, null, ["file-item"], { id: v.id }, null);

							ope_imgHtml.append(ope_colI);
							ope_imgHtml.append(ope_colA);
							ope_imgHtml.append(ope_colBtn);
							$(pageAct.work_type == "1" ? '#ope_forFile' : '#ope_forFile_2').append(ope_imgHtml ? ope_imgHtml.outerHtml() : null);
						}
					});
				}
			}, null, "POST").send()
		});

		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');
					});

				pageAct.imageFile =
					$.grep(pageAct.imageFile, function (file) {
						return file.save_file_name != elem.find('a').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, #inpFixDoCode_2", 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() {
		$(loadEle).Loading("start");
		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) {
		res = JSON.parse(res);
		strHtml = ``;

		$.each(res.data, function (i, v) {
			msg = v.msgText != null ? ($.trim(v.msgText.toString()).length > 0 ? v.msgText.split(':')[0] : '') : '';
			strHtml += `<option value=${v.uuid}>${v.uuid}</option>`;
		});

		if (res.count > 0)
			$(pageAct.work_type == '1' ? '#inpErrCode' : '#inpErrCode_2').html(strHtml);

		$(loadEle).Loading("close");
	}

	//上傳檔案 dropzone
	function initDropzone() {
		$("#ope_dropZone").dropzone({
			url: baseApiUrl + '/api/Upload',
			previewsContainer: false,
			addRemoveLinks: false,
			dictRemoveFile: `<span class="material-icons mi-delete">delete</span>`,
			dictInvalidFileType: `上傳格式錯誤`,
			dictCancelUploadConfirmation: `確定要取消上傳此檔案嗎?`,
			dictCancelUpload: `<span class="material-icons mi-cancel">cancel</span>`,
			maxFilesize: 10,
			filesizeBase: 1024,
			maxFiles: 50,
			acceptedFiles: ".pdf, .docx, .doc, .xls, .xlsm, .xlsx, .ppt, .pptx, .gif, .png, .jpg, .jpeg",
			headers: { "Authorization": 'Bearer ' + cookies.get("JWT-Authorization") },
			accept: function (file, done) {
				let fileHelper = new YourTeam.Utility.File();
				tmpGuidArr = [];

				if (/\.(jpe?g|png|gif)$/i.test(file.name)) {
					fileHelper.readAndPreviewImages(file, 'ope_forImage', 70, 70, '<span class="file-item m-1">', '<button class="btn-dark m-1" name="btnDelImg"><i class="fa fa-times"></i></button></span>');

					pageAct.imageFile.map(function (v, i) { if (v['file']) tmpGuidArr.push(v.file.guid); });
					if (jQuery.inArray(file.guid, tmpGuidArr) == -1) { //not in array
						let fd = new FormData();
						let f = file;
						fd.append('file', f);
						pageAct.imageFile.push({ "ori_file_name": f.name, "save_file_name": f.guid, "file": fd.get("file") });
					}
				}
				else if (/\.(xls?x|doc?x|ptt?x|pdf|zip|rar|7zip|txt|odt|xml|rtf|ods|odp|pps?x)$/i.test(file.name)) {
					fileHelper.readAndPreviewFiles(file, 'ope_forFile', 70, 70, "<div class='file-item'><i class='fas fa-file-alt fa-2x m-1'></i>", "<button class='btn-dark m-1' name='btnDelImg'><i class='fa fa-times'></i></button></div>");

					pageAct.imageFile.map(function (v, i) { if (v['file']) tmpGuidArr.push(v.file.guid); });
					if (jQuery.inArray(file.guid, tmpGuidArr) == -1) { //not in array
						let fd = new FormData();
						let f = file;
						fd.append('file', f);
						pageAct.imageFile.push({ "ori_file_name": f.name, "save_file_name": f.guid, "file": fd.get("file") });
					}
				}
			}
		});

		$("#ope_dropZone_2").dropzone({
			url: baseApiUrl + '/api/Upload',
			previewsContainer: false,
			addRemoveLinks: false,
			dictRemoveFile: `<span class="material-icons mi-delete">delete</span>`,
			dictInvalidFileType: `上傳格式錯誤`,
			dictCancelUploadConfirmation: `確定要取消上傳此檔案嗎?`,
			dictCancelUpload: `<span class="material-icons mi-cancel">cancel</span>`,
			maxFilesize: 10,
			filesizeBase: 1024,
			maxFiles: 50,
			acceptedFiles: ".pdf, .docx, .doc, .xls, .xlsm, .xlsx, .ppt, .pptx, .gif, .png, .jpg, .jpeg",
			headers: { "Authorization": 'Bearer ' + cookies.get("JWT-Authorization") },
			accept: function (file, done) {
				let fileHelper = new YourTeam.Utility.File();
				tmpGuidArr = [];

				if (/\.(jpe?g|png|gif)$/i.test(file.name)) {
					fileHelper.readAndPreviewImages(file, 'ope_forImage_2', 70, 70, '<span class="file-item m-1">', '<button class="btn-dark m-1" name="btnDelImg"><i class="fa fa-times"></i></button></span>');

					pageAct.imageFile.map(function (v, i) { if (v['file']) tmpGuidArr.push(v.file.guid); });
					if (jQuery.inArray(file.guid, tmpGuidArr) == -1) { //not in array
						let fd = new FormData();
						let f = file;
						fd.append('file', f);
						pageAct.imageFile.push({ "ori_file_name": f.name, "save_file_name": f.guid, "file": fd.get("file") });
					}
				}
				else if (/\.(xls?x|doc?x|ptt?x|pdf|zip|rar|7zip|txt|odt|xml|rtf|ods|odp|pps?x)$/i.test(file.name)) {
					fileHelper.readAndPreviewFiles(file, 'ope_forFile_2', 70, 70, "<div class='file-item'><i class='fas fa-file-alt fa-2x m-1'></i>", "<button class='btn-dark m-1' name='btnDelImg'><i class='fa fa-times'></i></button></div>");

					pageAct.imageFile.map(function (v, i) { if (v['file']) tmpGuidArr.push(v.file.guid); });
					if (jQuery.inArray(file.guid, tmpGuidArr) == -1) { //not in array
						let fd = new FormData();
						let f = file;
						fd.append('file', f);
						pageAct.imageFile.push({ "ori_file_name": f.name, "save_file_name": f.guid, "file": fd.get("file") });
					}
				}
			}
		});
	}

	function getFormId() {
		ytAjax = new YourTeam.Ajax(baseApiUrl + '/operation/GetFormId', objSendData, function (res) {
			if (!res || res.code != "0000" || !res.data) {

			} else {
				$(pageAct.work_type == '1' ? '#inpNumber' : '#inpNumber_2').val(res.data);
			}
		}, null, "POST").send();
	}

	function getUser() {
		ytAjax = new YourTeam.Ajax(baseApiUrl + "/api/getUser", null, function (res) {
			if (!res || res.code != "0000" || !res.data) {

			} else {
				$(pageAct.work_type == '1' ? '#inpWorPerId' : '#inpWorPerId_2').val(res.data);
			}
		}, null, "POST").send();
	}
</script>