
register = function () {
	let _noteScrollTop = 0;
	let linePicUrl = null;
	let lineBase64Data = null;
	let customBase64Data = null;
	let finalase64Data = null;
	let registerAlert = "";
	let registerData = {
		healthAction: null,
		healthTopic: null,
		healthStatus: null,
		healthAdapt: null,
        healthThought: null,
        healthAge: null,
        healthNickname: null,
        healthGender: null,
		headSticker: null,
		healthGenderRole: null
	}
	let userData;


	//private methods
	function init() {
		console.log('register is loaded.');

		selectImage();

		// 換大頭照點擊
		$(".photo__icon-1").on("click", function(){
			$("#fileInput1").click();
		});

		// 多選題選中添加checked樣式
		$(".register .form__options__item input[type='checkbox']").change(function(){
			if($(this).prop("checked")) {
				$(this).parents(".form__options__item").addClass("checked");
			}else {
				$(this).parents(".form__options__item").removeClass("checked");
			}
		});

		// 單選題選中添加checked樣式
		$(".register .form__options__item input[type='radio']").change(function(){
			if($(this).prop("checked")) {
				$(this).parents(".form__options").children(".form__options__item").removeClass("checked");
				$(this).parents(".form__options__item").addClass("checked");
			}
		});

		// 多選限制複選數
		$('.register .form__item-healthThought .form__options__item').click(function() {
			// console.log("healthThought click")
            $(".form__item-healthThought .form__options__item input[type=checkbox]").attr('disabled', true);
            if ($(".form__item-healthThought .form__options__item input[type=checkbox]:checked").length >= 2) {
                $(".form__item-healthThought .form__options__item input[type=checkbox]:checked").attr('disabled', false);
            } else {
                $('.form__item-healthThought .form__options__item input[type=checkbox]').attr('disabled', false);
            }
        });

		// 點擊資料表單"下一步"
		$(".register .form-submit").on("click", function(){
			// console.log("form-submit click");
			$(this).addClass("disable");
            $(".form-submit p").text("傳送中...");

			if(checkRegister()) {
				sendRegister();
			}else {
				base.myAlert(registerAlert);
				$(this).removeClass("disable");
                $(".form-submit p").text("下一步");
			}
		});
	}

	// Line大頭貼
	function LinePicHandler(url) {

		linePicUrl = url;
		$(".photo__img").html("");
		$(".photo__img").append(`
			<img src="${linePicUrl}"/>
		`);
		
		$(".photo .load-wrapp ").hide();

		const imageURL = linePicUrl;
		if(imageURL.trim() !== '') {
			const img = new Image();
			img.src = imageURL;

			const canvas = document.createElement("canvas");
			const ctx = canvas.getContext("2d");
			img.crossOrigin = 'Anonymous';

			img.onload = function() {
				canvas.width = img.width;
				canvas.height = img.height;
				ctx.drawImage(img, 0, 0);

				// 將圖片轉換為 Base64
				lineBase64Data = canvas.toDataURL('image/jpeg')
				finalase64Data = lineBase64Data;

				// console.log(finalase64Data)

			}
		}
	}

	// 選照片
	function selectImage() {
		const fileInputs = document.querySelectorAll('.fileInput');
		const imagePreview = $('.photo__img');
		// console.log(fileInput.id)

		var templeteHelper = new photoHelper();

		fileInputs.forEach((fileInput)=> {
			// 當選擇圖片後，顯示圖片的預覽
			fileInput.addEventListener("change", function(e){
				console.log(fileInput.id)

				$(".photo .load-wrapp ").show();

				const selectedFile = fileInput.files[0];

				if(selectedFile) {

					if(fileInput.id == 'fileInput1') {
						templeteHelper.loadFile('#fileInput1',function (_photoData) {
							console.log('fileInput1 has loaded.');
							templateData = _photoData;
							
							finalase64Data = templateData;
							// console.log(finalase64Data)
							
							const img = new Image();
							img.src = templateData;
							imagePreview.html("");
							imagePreview.append(img);
							// $('.templete_output').attr('src', templateData);

							$(".photo .load-wrapp ").hide();
						});
					}

					if(fileInput.id == 'fileInput2') {
						templeteHelper.loadFile('#fileInput2',function (_photoData) {
							console.log('fileInput2 has loaded.');
							templateData = _photoData;
							
							finalase64Data = templateData;
							// console.log(finalase64Data)
	
							const img = new Image();
							img.src = templateData;
							imagePreview.html("");
							imagePreview.append(img);
							// $('.templete_output').attr('src', templateData);

							$(".photo .load-wrapp ").hide();
							
							setTimeout(()=>{
								// console.log(finalase64Data)
								sendBase64DataToApi(finalase64Data);
							}, 200);
						});
					}
					

				}else {
					if(fileInput.id == 'fileInput1') {
						LinePicHandler(linePicUrl);
					}
					if(fileInput.id == 'fileInput2') {
						imagePreview.html("");
						imagePreview.append(`<img src=${finalase64Data} />`);
						$(".photo .load-wrapp ").hide();
					}
				}

			});
		});

	}

	// 送出圖片
	function sendBase64DataToApi(finalase64Data) {

		GameService.getInstanse().userUpdatePhoto(finalase64Data).then(res => {
			console.log('userUpdatePhoto：', res);
			// base.myAlert('成功上傳。');
		});
		
	}

	function insertFromData(data) {
		resetRegister();
		let formData = data.filler_content;
		// console.log(formData)
		
		// 健康行動
		formData.healthAction.forEach((val)=>{
			$(`.form__item-healthAction input[value=${val}]`).prop("checked", true);
			$(`.form__item-healthAction input[value=${val}]`).parents(".form__options__item").addClass("checked");
		});

		// 對什麼健康話題有興趣
		formData.healthTopic.forEach((val)=>{
			$(`.form__item-healthTopic input[value=${val}]`).prop("checked", true);
			$(`.form__item-healthTopic input[value=${val}]`).parents(".form__options__item").addClass("checked");
		});

		// 身體狀況如何
		$(`input[value=${formData.healthStatus}]`).prop("checked",true);
		$(`input[value=${formData.healthStatus}]`).parents(".form__options__item").addClass("checked");

		// 最符合你的應對
		$(`input[value=${formData.healthAdapt}]`).prop("checked",true);
		$(`input[value=${formData.healthAdapt}]`).parents(".form__options__item").addClass("checked");

		// 符合你的想法
		formData.healthThought.forEach((val)=>{
			$(`.form__item-healthThought input[value=${val}]`).prop("checked", true);
			$(`.form__item-healthThought input[value=${val}]`).parents(".form__options__item").addClass("checked");
		});

		// 你的年齡
		$(`input[value=${formData.healthAge}]`).prop("checked",true);
		$(`input[value=${formData.healthAge}]`).parents(".form__options__item").addClass("checked");

		// 暱稱
		$(`input[id="nickName"]`).val(data.nickname);

		// 性別
		$(`select[id="gender"]`).val(formData.healthGender);

		// 頭貼
		$(".register .photo__img").append(`
			<img src=${data.head_sticker} />
		`);
	}


	// 取得選取的checkbox
	function getCheckboxVal(name) {

		let vals = $(".register input[type=checkbox][name="+name+"]:checked").map(function() {
			return $(this).val();
		}).get();

		return vals;
	}

	// 取得選取的radio
	function getRadioVal(name){
		return $("input[name="+name+"]:checked").val();
	}

	// 確認註冊表單
	function checkRegister(){
		let isComplete = true;
		registerAlert = "";

		if(getCheckboxVal("healthAction").length > 0) {
			registerData.healthAction = getCheckboxVal("healthAction");
		}else {
			isComplete = false;
		}

		if(getCheckboxVal("healthTopic").length > 0) {
			registerData.healthTopic = getCheckboxVal("healthTopic");
		}else {
			isComplete = false;
		}
		
		if(getRadioVal("healthStatus") !== "" && getRadioVal("healthStatus") !== undefined ) {
			registerData.healthStatus = getRadioVal("healthStatus");
		}else {
			isComplete = false;
		}

		if(getRadioVal("healthAdapt") !== "" && getRadioVal("healthAdapt") !== undefined ) {
			registerData.healthAdapt = getRadioVal("healthAdapt");
		}else {
			isComplete = false;
		}

		if(getCheckboxVal("healthThought").length > 0) {
			registerData.healthThought = getCheckboxVal("healthThought");
		}else {
			isComplete = false;
		}

		if(getRadioVal("healthAge") !== "" && getRadioVal("healthAge") !== undefined ) {
			registerData.healthAge = getRadioVal("healthAge");
		}else {
			isComplete = false;
		}

		if($("#nickName").val().trim() !== "") {
			registerData.healthNickname = $("#nickName").val().trim();
		}else {
			isComplete = false;
		}

		if($("#gender").val() !== "") {

			registerData.healthGender = $("#gender").val();

			if($("#gender").val() === "tag-8HwqQuQ43") {
				registerData.healthGenderRole = "female"
			} else if($("#gender").val() === "tag-F8Me8-UGg") {
				registerData.healthGenderRole = "male"
			}else {
				registerData.healthGenderRole = "";
			}

		}else {
			isComplete = false;
		}

		if(!isComplete) {
			registerAlert = "請確認問題皆已作答";
		}

		if(getCheckboxVal("methodsAgree").length == 0) {
			registerAlert == "" ? registerAlert = "請勾選'我同意個人資料使用方法'" : registerAlert+="<br>請勾選'我同意個人資料使用方法'";
			isComplete = false;
		}

		if(isComplete) {
			registerData.headSticker = $(".register .photo__img img").attr("src");
			console.log(registerData)
		}


		return isComplete;
	}

	// 送出表單
	function sendRegister() {

		// 測試用
		// base.sectionFadeOut(".register");
		// base.sectionFadeIn(".passport");
		// $(".register .form-submit").removeClass("disable");
        // $(".register .form-submit p").text("下一步");

		// 正式用
		GameService.getInstanse().userRegister(registerData)
			.then(_res => {
				console.log(_res);
				if(_res.result === 'successed') {
					$(".register .form-submit").removeClass("disable");
					$(".register .form-submit p").text("下一步");
					// 清除表單
					resetRegister();
					// 再次載入取得資料
					GameService.getInstanse().userLogin().then(_res => {
						console.log("_res: ",_res);
	
						userData = GameService.getInstanse().getUserData();
	
						console.log("userData: ",userData)
						
						base.sectionFadeOut(".register");
						base.sectionFadeIn(".passport");
						passport.buildPassportHandler(userData)

						GameService.getInstanse().sendCompleteMessage();
					})
				}
				
			})
			.catch(_err => {
				console.log(_err);
				// let msg = err.message.replaceAll("Error:", "");
				base.myAlert(_err);
				$(".register .form-submit").removeClass("disable");
                $(".register .form-submit p").text("下一步");
			})
	}

	// 重設表單
	function resetRegister() {
		$('.register .form input[type=checkbox], .register .form input[type=radio]').prop('checked', false);
		$(".register .form__options__item").removeClass("checked");
		$('.register .form input[type=text], .register .form select').val('');
	}
	


	//constructor

	{
		$(document).ready(function () {
			init();
		});
	}

	//public

	return {
		LinePicHandler: function(url) {
			LinePicHandler(url);
		},
		getCheckboxVal: function(name) {
			return getCheckboxVal(name)
		},
		getRadioVal: function(name) {
			return getRadioVal(name)
		},
		selectImage: function() {
			selectImage();
		},
		insertFromData: function(data) {
			insertFromData(data);
		}
	};
};

var register = new register();