LoadScript("sortableScript",wctx.url("/webjars/3rd-party/sneat/libs/sortablejs/sortable.js"));

function settingPhotoMain(pageName, crdnIdElement, carInfoFunc, carLinkFunc){

	let $P = pageObject[pageName];

	$P.existFileArr = [];
	$P.localUploadArr = [];

	$P.carInfoFunc = carInfoFunc;
	$P.carLinkFunc = carLinkFunc;

	//드래그앤드롭
	Sortable.create($P.findn("dragAndDrop"), {
		onEnd : function(evt){
			if(evt.oldIndex != evt.newIndex){
				$P.updateFileInfo("changeOrder");
			}
		}
	});

	//파일처리 버튼
	//추가버튼
	$P.$findn("btnAddFile").on('click', () => {
		$P.$findn("inputUploadSet").trigger("click");
	});
	//동영상캡쳐버튼
	$P.$findn("btnOpenVideoCapture").on('click', () => {
		var crdnId = $(crdnIdElement).val();

		var popupWidth = 1800;
		var popupHeight = 950;
		var popupX = (window.screen.width / 2) - (popupWidth / 2);
		var popupY= (window.screen.height / 2) - (popupHeight / 2);

		var popup = window.open(wctx.url("/sprt/sprt03/010/main.do?openerPageName="+pageName+"&"+"crdnId="+crdnId)
				,"newVideoCapture"
				,"width="+popupWidth+", height="+popupHeight+", left="+popupX+", top="+popupY
		);
		$.blockUI({message : ""});
		popup.onload = () => {
			popup.addEventListener('beforeunload', function() {
				$.unblockUI();
			});
		};
	});

	//편집버튼
	$P.$findn("btnEditPhoto").on('click', async() => {
		var checked = $P.$findn("displayForExist").find("[name='existPhoto']:checked");
		if(checked.length < 1){
			await alert2("선택된 사진이 없습니다.");
			return;
		}

		var fileId = checked.val();

		var popupWidth = 1400;
		var popupHeight = 750;
		var popupX = (window.screen.width / 2) - (popupWidth / 2);
		var popupY= (window.screen.height / 2) - (popupHeight / 2);

		var popup = window.open(wctx.url("/sprt/sprt03/020/main.do?openerPageName="+pageName+"&"+"fileId="+fileId)
				,"editPhoto"
				,"width="+popupWidth+", height="+popupHeight+", left="+popupX+", top="+popupY
		);
		$.blockUI({message : ""});
		popup.onload = () => {
			popup.addEventListener('beforeunload', function() {
				$.unblockUI();
			});
		};
	});
	//삭제버튼
	$P.$findn("btnDeleteExistPhoto").on('click', async() => {

		var checked = $P.$findn("displayForExist").find("[name='existPhoto']:checked");
		if(checked.length < 1){
			await alert2("선택된 사진이 없습니다.");
			return;
		}

		var target = checked[0].value;

		$P.existFileArr.forEach(function(item){
			if(item.FILE_ID == target){
				item.status = "delete";
			}
		});

		$P.updateFileInfo("delete");
	});

	$P.uploadSet = uploadSupport($P.selectorn("inputUploadSet"));

	$P.uploadSet.onDatasetChange  = () => {

		var files = $P.uploadSet.getDataset();
		if(files != null && files.length > 0){
			files.forEach(function(item){
				$P.localUploadArr.push(item);
			});

			$P.updateFileInfo("insert");
		}

	};

	$P.uploadSet.onRemove = () => { };


	//이미지 HTML태그 문자열 반환
	$P.fnMakeImgForExistFile = (fileArr) => {
		var tagsTextArr = [];

		for(var index = 0, j = 0; index < fileArr.length; index++){
			var item = fileArr[index];

			if(item.status == "delete"){
				continue;
			}

			// pageName에 따라 template이 다르다.
			var template;
            if (pageName == "rent02020") {
                template = $P.findn("imgRadioTemplateRentInfo").innerHTML;
            } else if (pageName == "rent03020") {
                template = $P.findn("imgRadioTemplateRentInfo").innerHTML;
			} else if (pageName == "sprt02020") {
				template = $P.findn("imgRadioTemplateTotalInfo").innerHTML;
			} else {
				template = $P.findn("imgRadioTemplate").innerHTML;
			}

			template = template.replace(/{name}/gi, "existPhoto");
			template = template.replace(/{value}/gi, item.FILE_ID);
			template = template.replace(/{src}/gi, item.URL);
			if(index != 0){
				template = template.replace("checked=\"\"", "");
			}
			template = template.replace(/{crdnPhotoId}/gi, "exist" + item.FILE_ID + pageName);
			template = template.replace(/{mosaic}/gi, ifEmpty(item.MOSAIC,""));

			tagsTextArr.push(template);

			if(j % 2 == 1){
				//tagsTextArr.push("<br />");
			}

			j++;
		}

		return tagsTextArr.join("");
	}

	//이미지 HTML 렌더링
	$P.fnDisplay = () => {

		var tagsText = $P.fnMakeImgForExistFile($P.existFileArr);

		if(tagsText == ""){
			$P.findn("dragAndDrop").innerHTML = "";
			$P.$findn("btnEditPhoto").hide();
		} else {
			$P.findn("dragAndDrop").innerHTML = tagsText;
			$P.$findn("btnEditPhoto").show();
		}

	};


	//동영상캡쳐 콜백
	$P.videoCallback = (snapshots) => {
		snapshots.forEach(function(canvas, index, array){
			canvas.toBlob(function(blob){
				var identify = new Date().getTime()+ "-" + index;
				var file = new File([blob], "capture-"+identify+".png", {type: "image/png"});
				file.id = "file-" + identify;
				file.url = (window.URL || window.webkitURL).createObjectURL(file);
				file.mosaic = "";

				$P.localUploadArr.push(file);
				if(index === array.length - 1){

					$P.updateFileInfo("insert");
				}
			});
		});

	}

	//사진 편집 콜백
	$P.editPhotoCallback = (modifiedFile, originalFileInfo, isNumberPlate) => {

		modifiedFile.id = "file-" + new Date().getTime() + "-" + "0";
		modifiedFile.url = (window.URL || window.webkitURL).createObjectURL(modifiedFile);

		if(isNumberPlate){
			modifiedFile.mosaic = "";
			$P.localUploadArr.push(modifiedFile);

			$P.updateFileInfo("insert");

		} else {
			$P.existFileArr.forEach(function(item,index){
				if(item.FILE_ID == originalFileInfo.FILE_ID){
					modifiedFile.URL = modifiedFile.url;
					modifiedFile.FILE_ID = originalFileInfo.FILE_ID;
					modifiedFile.SRT_ORD = originalFileInfo.SRT_ORD;
					modifiedFile.status = "modified";
					$P.existFileArr.splice(index, 1, modifiedFile);
				};
			});

			$P.updateFileInfo("modifiy");

		}
	}

	// 사진 저장
	$P.updateFileInfo = (flag) => {

		var formData = new FormData($P.findn("frmFile"));
		formData.append("crdnId", $(crdnIdElement).val());
		formData.append("atchFileCnt", $P.existFileArr.length);

		var fileProcessingURL = "";
		if(flag == "insert"){
			fileProcessingURL = wctx.url("crdn/crdn06/insertCrdnImageFile.do");

			formData.delete("newFileList");

			if ($P.localUploadArr.length > 0) {
				$P.localUploadArr.forEach(function(item){
					formData.append("newFileList", item);
				});
			}
		} else if(flag == "modifiy"){
			fileProcessingURL = wctx.url("crdn/crdn06/updateCrdnImageFile.do");

			formData.delete("modifyFile");

			if($P.existFileArr.length > 0) {
				$P.existFileArr.forEach(function(item){
					if(item.status == "modified"){
						formData.append("beforeKey", item.FILE_ID);
						formData.append("beforeOrder", item.SRT_ORD);
						formData.append("modifyFile", item);
					}
				});
			}
		} else if(flag == "delete"){
			fileProcessingURL = wctx.url("crdn/crdn06/deleteCrdnImageFile.do");

			if($P.existFileArr.length > 0) {
				$P.existFileArr.forEach(function(item){
					if(item.status == "delete"){
						formData.append("deleteKeys", item.FILE_ID);
					}
				});
			}
		} else if(flag == "changeOrder"){
			fileProcessingURL = wctx.url("crdn/crdn06/changeOrderCrdnImageFile.do");

			var inputs = $P.$findn("dragAndDrop").find("input[name='existPhoto']");
			for(var i=0; i < inputs.length; i++){
				formData.append("orderedKeys", inputs[i].value);
			}
		}

		ajax.post({
			url : fileProcessingURL,
			data : formData, contentType : false, processData : false,
			success : (resp) => {
				if(resp.saved){

					var crdnId = $(crdnIdElement).val();
					ajax.post({
						url : wctx.url("crdn/crdn06/fileList.do"),
						data : {
							infoKeys : crdnId,
							infoType : "100"
						},
						success : (resp) => {
							var hasVideo = false;
							if(resp.cvlcptVideoExistYn == "Y"){
								hasVideo = true;
							}
							initPhotoMain(pageName, resp.fileList, hasVideo);
						}
					});
				}
			},
		});
	}
}

function initPhotoMain(pageName, fileList, existVideo, showBtn=true){

	let $P = pageObject[pageName];

	//동영상캡쳐버튼
	if(existVideo){
		$P.$findn("btnOpenVideoCapture").show();
	} else {
		$P.$findn("btnOpenVideoCapture").hide();
	}
    // 버튼 div를 숨긴다.
    if (showBtn) {
        $P.$findn("divBtn").show();
    } else {
        $P.$findn("divBtn").hide();
    }

	$P.existFileArr = [];
	if(fileList){
		fileList.forEach(function(item){
			item.status = "";
			$P.existFileArr.push(item);
		});
	}

	$P.localUploadArr = [];
	$P.findn("inputUploadSet").value = "";
	$P.$findn("inputUploadSet").trigger("change");

	$P.fnDisplay();
}