<div class="title">編輯單元</div>
<ul class="table-toolbar" style="text-align: left;">
	<li><a class="toolbar-element btn btn-default btn-create" href="/unit"><i style="margin-right: 8px;"><span
						class="iconify" data-icon="typcn-arrow-back" data-inline="false"></span></i>返回</a></li>
</ul>
<div class="form-container">

	<form id="frmphp" class="form-horizontal" role="form" method="post" action="/unit/save">
		<?php if (isset($data) && !empty($data)): ?>
			<input type="hidden" name="id" value="<?= $data['id'] ?>">
			<input type="hidden" id="poststatus" name="status" value="<?=$data['status']?>">
		<?php endif; ?>
		<?php $disabled = (intval($data['inuse']) > 0) ? 'disabled' : ''; ?>
		<?php
		if ($disabled !== '') {
			echo '<span class="edit-warning">* 此項目正被使用，不能修改狀態</span>';
		}
		?>
		<div class="form-group mas-col">
			<div class="col-sm-3 text-center mas-title">
				<label>課程主分類</label>
			</div>
			<div class="col-sm-9 mas-box">
				<select id="course_category_id" class="select mas-select select2-offscreen form-control mas-input"
						name="course_category_id" tabindex="-1" data-id="<?= $data['course_category_id'] ?>"></select>
			</div>
		</div>
		<div class="form-group mas-col">
			<div class="col-sm-3 text-center mas-title">
				<label>課程次分類</label>
			</div>
			<div class="col-sm-9 mas-box">
				<select id="course_subcategory_id" class="select mas-select select2-offscreen form-control mas-input"
						name="course_subcategory_id" tabindex="-1"
						data-id="<?= $data['course_category_sub_id'] ?>"></select>
			</div>
		</div>
		<div class="form-group mas-col">
			<div class="col-sm-3 text-center mas-title">
				<label>課程名稱</label>
			</div>
			<div class="col-sm-9 mas-box">
				<select id="course_id" class="select mas-select select2-offscreen form-control mas-input"
						name="course_id" tabindex="-1" data-id="<?= $data['course_id'] ?>"></select>
			</div>
		</div>
		<div class="form-group mas-col">
			<div class="col-sm-3 text-center mas-title">
				<label for="title">單元名稱</label>
			</div>
			<div class="col-sm-9 text-center mas-title mas-box ">
				<input id="title" type="text" class="form-control mas-input" name="title" value="<?= $data['title'] ?>"
					   style="background-color: rgb(255, 255, 255);">
			</div>
		</div>
		<?php if (isset($status) && !empty($status)): ?>
			<div class="form-group mas-col">
				<div class="col-sm-3 text-center mas-title"><label for="status">狀態</label></div>
				<div class="col-sm-9 text-center mas-title mas-box ">
					<select class="select mas-select" id="status"
							data-disabled="<?= $disabled ?>" <?= $disabled ?>>
						<?php
						foreach ($status as $idx => $value) {
							if ($idx == $data['status']) {
								$selected = ' selected="selected"';
							} else {
								$selected = '';
							}
							echo sprintf('<option value="%s"%s>%s</option>', $idx, $selected, $value);
						}
						?>
					</select>
				</div>
			</div>
		<?php endif; ?>
		<div class="form-group mas-col">
			<div class="col-sm-3 text-center mas-title">
				<label for="remark">備註</label>
			</div>
			<div class="col-sm-9 mas-box">
				<textarea id="remark" class="form-control mas-textarea" rows="3" name="remark"
						  style="background-color: rgb(255, 255, 255);"><?= $data['remark'] ?></textarea>
			</div>
		</div>
		<?php if (isset($tenant_no) && !empty($tenant_no)): ?>
			<div class="form-footer">
				<?php
				if ($tenant_no === $data['tenant_no']) {
					?>
					<button class="btn btn-footer submit" type="button" id='btnEdit' style="display:none;">編輯</button>
					<button class="btn btn-footer submit" type="button" id='btnCancel' style="display:none;">取消</button>
					<?php
				}
				?>
				<button class="btn btn-footer submit" type="button" id="btnSubmit">提交</button>
				<a class="btn btn-footer reset" href="javascript:window.location.reload(true)">重設</a>
			</div>
		<?php endif; ?>
	</form>

</div>

<script>
	var viewMode = true;

	function getRemoteData(remote_url, data, callback, callbackFail) {
		$.ajax({
//async: false,
//timeout: 30000, //最長等候回應時間
			type: "GET", //提交類型
			url: remote_url, //提交地址
			data: data, //提交內容
			dataType: 'json', //返回數據類型
			success: function (data) { //請求完成並成功
				if (data.success) {
					callback(data.data);
				} else {
					callbackFail();
				}
			},
			error: function (data) { //請求返回錯誤信息
				callbackFail();
			},
			beforeSend: function (XHR) { //请求開始前执行
			},
			complete: function (XHR, status) { //请求完成后最终执行
			}
		});
	}

	function getRemoteDataFail() {
		alert("發生錯誤");
	}

	function changeMode() {
		$('.btn-footer').toggle();
		$('.form-control').prop('disabled', viewMode);
	}

	$(document).ready(function () {
		var li = $('#sidebar-menu li').filter(function (i) {
			return $(this).find('.menu-dropdown').find('.menu-text').text() === '單元管理';
		});
		li.addClass('active open');
		//disable tenant switch to prevent error
		$('#tenantswitch').prop('disabled',true);
		changeMode();
		getRemoteData("/api/unit/getcategories", {
			'mode': 'edit',
			'tenantno': '<?=$data['tenant_no']?>'
		}, getCategoriesOk, getRemoteDataFail);
	});

	$(document).on('change', '#course_subcategory_id', function () {
		getRemoteData(
				"/api/unit/getcourses",
				{
					course_category_id: $('SELECT[name="course_category_id"]').val(),
					course_subcategory_id: $('SELECT[name="course_subcategory_id"]').val(),
					'mode': 'edit', 'tenantno': '<?=$data['tenant_no']?>'
				},
				getCourseOk,
				getRemoteDataFail
		);
	});

	function getCourseOk(data) {
		var selectObj = $('SELECT[name="course_id"]');
		selectObj.empty();
		$('#s2id_course_id .select2-chosen').text('');
		$.each(data, function (k, v) {
			var o = parseInt(selectObj.data('id')) === parseInt(v.id) ? new Option(v.name, v.id, true, true) : new Option(v.name, v.id);
			$(o).html(v.name);
			selectObj.append(o);
		});
		selectObj.select2();
		selectObj.trigger('change');
	}

	$(document).on('change', '#course_category_id', function () {
		getRemoteData(
				"/api/unit/getsubcategories",
				{
					course_category_id: $('SELECT[name="course_category_id"]').val(),
					'mode': 'edit', 'tenantno': '<?=$data['tenant_no']?>'
				},
				getSubCategoryOk,
				getRemoteDataFail
		);
	});

	function getSubCategoryOk(data) {
//        console.log('subcategories:',data);
		var selectObj = $('SELECT[name="course_subcategory_id"]');
		selectObj.empty();
		$('#s2id_course_subcategory_id .select2-chosen').text('');
		$.each(data, function (k, v) {
			var o = parseInt(selectObj.data('id')) === parseInt(v.id) ? new Option(v.name, v.id, true, true) : new Option(v.name, v.id);
			$(o).html(v.name);
			selectObj.append(o);
		});
		selectObj.select2();
		selectObj.trigger('change');
	}

	function getCategoriesOk(categories) {
		console.log('categories:',categories);
		var selectObj = $('SELECT[name="course_category_id"]');
		selectObj.empty();
		$('#s2id_course_category_id .select2-chosen').text('');
		$.each(categories, function (k, v) {
			// console.log('selectedid:'+selectObj.data('id')+';v.id:'+v.id);
			var o = parseInt(selectObj.data('id')) === parseInt(v.id) ? new Option(v.name, v.id, true, true) : new Option(v.name, v.id);
			$(o).html(v.name);
			selectObj.append(o);
		});
		selectObj.select2();
		selectObj.trigger('change');
	}

	function validform() {
		var msg = '';
		if ($('#course_category_id').val() === null || $('#course_category_id').val() === '') {
			msg += "請輸入課程主分類\n";
		}
		if ($('#course_subcategory_id').val() === null || $('#course_subcategory_id').val() === '') {
			msg += "請輸入課程次分類\n";
		}
		if ($('#course_id').val() === null || $('#course_id').val() === '') {
			msg += "請輸入課程名稱\n";
		}
		if ($('#title').val() === '') {
			msg += "請輸入單元名稱\n";
		}
		if (msg !== '') {
			alert(msg);
		}
		return msg === '';
	}

	$(document).on('click', '#btnSubmit', function () {
		if (validform()) {
//            console.log('here');
			$('#frmphp').submit();
		}
	});
	$(document).on('click', '#btnEdit', function () {
		viewMode = false;
		changeMode();
	});
	$(document).on('click', '#btnCancel', function () {
		window.location.href = '/unit';
	});
	$(document).on('change','#status',function(){
		$('#poststatus').val($(this).val());
	});
</script>
