/****************************************************************************
* 거래처 정보 상세 조회
****************************************************************************/
function fn_selectCompany(){
	let formData = new FormData();
	formData.append("menuClass", menuClass);
	formData.append("muCompanyId", muCompanyId);

	$.ajax({
		url: encodeURI('/webcompany/selectCompany.do'),
		data: formData,
		dataType: "json",
		processData: false,
		contentType: false,
		type: 'POST',
		async: true,
		success: function(data){
			if('0'==data.msgCode){
				$("#companyName").val(data.rows[0].companyName);
				$("#businessNumber").val(data.rows[0].businessNumber);
				$("#userName").val(data.rows[0].userName);
				$("#phoneNumber").val(data.rows[0].phoneNumber);
				$("#email").val(data.rows[0].email);
				$("#memo").val(data.rows[0].memo);
				
				fn_addRow2(data.rows[0].companyProductList);
			}
			else{
				modalEvent.danger("조회 오류", data.msgDesc);
			}
		},
		error : function(xhr, status, error) {
			modalEvent.danger("조회 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
		},
		beforeSend:function(){
			
		},
		complete:function(){
			
		}
	});
}


/****************************************************************************
* 조회 row 추가 이벤트
****************************************************************************/
function fn_addRow2(detailList){
	let addRowHtml = '';
	
	if(0<detailList.length){
		for(let i = 0; i < detailList.length; i++){
			console.log(detailList[i]);
			let muProductId   = detailList[i].muProductId;
			let muTreatmentId = detailList[i].muTreatmentId;
			let treatmentName = detailList[i].treatmentName;
			let productName   = detailList[i].productName;
			let volume        = detailList[i].volume;
			let usage_volume  = detailList[i].usage_volume;
			let unitName      = detailList[i].unitName;
			let unitCode      = detailList[i].unitCode;
			let usage_unitName      = detailList[i].usage_unitName;
			let usage_unitCode      = detailList[i].usage_unitCode;

			addRowHtml += '<tr>';
			addRowHtml += '	<td>';			
			addRowHtml += '		<div class="select_box first dropdown">';
			addRowHtml += '			<button class="label" type="button" id="treatment'+i+'" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">재고구분</button>';
			addRowHtml += '			<input type="hidden" name="muTreatmentId" value="'+muTreatmentId+'"/>';
			addRowHtml += '			<ul class="select_option_list dropdown-menu">';
			addRowHtml += '		</div>';			
			addRowHtml += '	</td>';
			
			addRowHtml += '	<td>';
			addRowHtml += '		<div class="input_box">';
			addRowHtml += '			<input type="hidden" name="muProductId" value="'+muProductId+'"/>';
			addRowHtml += '			<input type="text" name="productName" placeholder="" value="'+productName+'" maxlength="35" >';
			addRowHtml += '		</div>';
			addRowHtml += '	</td>';
			
			addRowHtml += '	<td>';
			addRowHtml += '		<div class="input_box">';
			addRowHtml += '			<input type="text" name="volume" placeholder="" value="'+volume+'" maxlength="255" >';
			addRowHtml += '		</div>';
			addRowHtml += '	</td>';
			
			addRowHtml += '	<td>';
			addRowHtml += '		<div class="select_box dropdown">';
			addRowHtml += '			<button class="label" type="button" id="unit'+i+'" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">제품단위</button>';
			addRowHtml += '			<input type="hidden" name="unit" value="'+unitCode+'"/>';
			addRowHtml += '			<ul class="select_option_list dropdown-menu">';
			addRowHtml += '		</div>';
			addRowHtml += '	</td>';
			
			addRowHtml += '	<td>';
			addRowHtml += '		<div class="input_box">';
			addRowHtml += '			<input type="text" name="usage_volume" placeholder="" value="'+usage_volume+'" maxlength="255" >';
			addRowHtml += '		</div>';
			addRowHtml += '	</td>';
			
			addRowHtml += '	<td>';
			addRowHtml += '		<div class="select_box dropdown">';
			addRowHtml += '			<button class="label" type="button" id="usage_unit'+i+'" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">제품단위</button>';
			addRowHtml += '			<input type="hidden" name="usage_unit" value="'+usage_unitCode+'"/>';
			addRowHtml += '			<ul class="select_option_list dropdown-menu">';
			addRowHtml += '		</div>';
			addRowHtml += '	</td>';
						
			addRowHtml += '	<td>';
			if(i==0){
				addRowHtml += '	<div class="add_box">';
				addRowHtml += '		<button class="add_btn" onclick="javascript:fn_removeRow2(this);"><img src="/image/web/subtract.svg" alt="삭제"/></button>';
				addRowHtml += '		<button class="add_btn" onclick="javascript:fn_addRow(this);"><img src="/image/web/add.svg" alt="추가"/></button>';
				addRowHtml += '	</div>';
			}
			else{
				addRowHtml += '	<div class="add_box" style="display:none;"><button class="add_btn add_box" onclick="javascript:fn_addRow(this);"><img src="/image/web/add.svg" alt="추가"/></button></div>';
				addRowHtml += '	<div class="subtract_box"><button class="add_btn subtract_box" onclick="javascript:fn_removeRow(this);"><img src="/image/web/subtract.svg" alt="삭제"/></button></div>';
			}
			addRowHtml += '	</td>';
			addRowHtml += '</tr>';
		}
		$('#productList').empty().html(addRowHtml).trigger("create");
		let parentTable = $("#productList");	
		fn_setTreatmentCombo();		
		fn_setUnitCombo();		
		fn_companyRefreshOrderNumber(parentTable);
		for(let i = 0; i < detailList.length; i++){
			$('#treatment' + i).text(detailList[i].treatmentName);
			$('#unit' + i).text(detailList[i].unitName);
			$('#usage_unit' + i).text(detailList[i].usage_unitName);
		}
	}
	else{
		fn_addRow();
	}
	
}

/****************************************************************************
* row 추가 이벤트
****************************************************************************/
function fn_addRow(param){
	let addRowHtml = '';
	addRowHtml += '<tr>';
	addRowHtml += '	<td>';
	addRowHtml += '		<div class="select_box first dropdown">';
	addRowHtml += '			<button class="label" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">재고구분</button>';
	addRowHtml += '			<input type="hidden" name="muTreatmentId" value=""/>';
	
	addRowHtml += '			<ul class="select_option_list dropdown-menu">';
	addRowHtml +='			</ul>';
	addRowHtml += '		</div>';
	addRowHtml += '	</td>';
	
	addRowHtml += '	<td>';
	addRowHtml += '		<div class="input_box">';
	addRowHtml += '			<input type="hidden" name="muProductId" value=""/>';
	addRowHtml += '			<input type="text" name="productName" placeholder="" value="" maxlength="35">';
	addRowHtml += '		</div>';
	addRowHtml += '	</td>';
	
	addRowHtml += '	<td>';
	addRowHtml += '		<div class="input_box">';
	addRowHtml += '			<input type="text" name="volume" placeholder="" value="" maxlength="255">';
	addRowHtml += '		</div>';
	
	addRowHtml += '	</td>';
	addRowHtml += '	<td>';
	addRowHtml += '		<div class="select_box dropdown">';
	addRowHtml += '			<button class="label" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">제품단위</button>';
	addRowHtml += '			<input type="hidden" name="unit" value=""/>';
	
	addRowHtml += '			<ul class="select_option_list dropdown-menu">';
	addRowHtml +='			</ul>';
	addRowHtml += '		</div>';
	addRowHtml += '	</td>';
	
	addRowHtml += '	<td>';
	addRowHtml += '		<div class="input_box">';
	addRowHtml += '			<input type="text" name="usage_volume" placeholder="" value="" maxlength="255">';
	addRowHtml += '		</div>';
	
	addRowHtml += '	</td>';
	addRowHtml += '	<td>';
	addRowHtml += '		<div class="select_box dropdown">';
	addRowHtml += '			<button class="label" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">제품단위</button>';
	addRowHtml += '			<input type="hidden" name="usage_unit" value=""/>';
	
	addRowHtml += '			<ul class="select_option_list dropdown-menu">';
	addRowHtml +='			</ul>';
	addRowHtml += '		</div>';
	addRowHtml += '	</td>';

	addRowHtml += '	<td>';
	addRowHtml += '		<div class="add_box"><button class="add_btn" onclick="javascript:fn_addRow(this);"><img src="/image/web/add.svg" alt="추가"/></button></div>';
	addRowHtml += '		<div class="subtract_box" style="display:none;"><button class="add_btn" onclick="javascript:fn_removeRow(this);"><img src="/image/web/subtract.svg" alt="삭제"/></button></div>';
	addRowHtml += '	</td>';
	addRowHtml += '</tr>';
	$('#productList').append(addRowHtml).trigger("create");

	$('[name=volume]').on('input', function() {
		// 입력된 키가 숫자가 아닌 경우 입력을 막음
		this.value = this.value.replace(/\D/g, '');
	});

	let parentTable = $("#productList");	
	fn_setTreatmentCombo();	
	fn_setUnitCombo();	
	fn_companyRefreshOrderNumber(parentTable);
}

/****************************************************************************
* row 삭제 이벤트
****************************************************************************/
function fn_removeRow(param){
	let liLength = $('#productList').children('tr').length;
	
	if(1 < liLength){
		let liNum = $(param).closest('tr').prevAll().length;
		$('#productList').children('tr').eq(liNum).remove();
	}
	else{
		modalEvent.warning("입력 오류", "더 이상 삭제할 수 없습니다.");
	}
}

/****************************************************************************
* row 삭제 이벤트
****************************************************************************/
function fn_removeRow2(param){

	let liNum = $(param).closest('tr').prevAll().length;
	$('#productList').children('tr').eq(liNum).remove();

	fn_addRow();
}

/****************************************************************************
* 전체 row 버튼 변경
****************************************************************************/
function fn_companyRefreshOrderNumber(param){
	// row 추가/삭제 버튼 처리
	$(param).find(".add_box").hide();
	$(param).find('.subtract_box').show();
	$(param).children("tr:eq(0)").find(".subtract_box").hide();
	$(param).children("tr:eq(0)").find(".add_box").show();
}

function fn_setTreatmentCombo(){
	
	const target = $('#productList').children('tr').find('input[name="muTreatmentId"]').siblings("ul.select_option_list");
	
	let category = fn_selectCategoryList2();
	let reservationCategory = category.find(cat => cat.categoryName === '재고구분');			
	if (reservationCategory) {
		fn_selectModalOtherOption2(reservationCategory.categoryCode);		
	}
	target.find("li.option_list_item").click(function () {
		let selectIdArr = $(this).prop("id").split('_');
		let selectId    = selectIdArr[1];
		let selectName  = $(this).text();

		$(this).parent().siblings("button").text(selectName);
		$(this).parent().siblings("input").val(selectId);
	});
}
/****************************************************************************
 * 제품 단위 콤보데이타 설정 (동적 추가)
 ****************************************************************************/
function fn_setUnitCombo(){
	const target = $('#productList').children('tr').find('input[name="unit"]').siblings("ul.select_option_list");
	let category = fn_selectCategoryList2();
	let reservationCategory = category.find(cat => cat.categoryName === '제품단위');

	if (reservationCategory) {
		fn_selectModalOtherOption2(reservationCategory.categoryCode);
	}	
	
	const target2 = $('#productList').children('tr').find('input[name="usage_unit"]').siblings("ul.select_option_list");
	let category2 = fn_selectCategoryList2();
	let reservationCategory2 = category2.find(cat => cat.categoryName === '제품단위');

	if (reservationCategory2) {
		fn_selectModalOtherOption2(reservationCategory2.categoryCode);
	}
	
	target.find("li.option_list_item").click(function () {
		console.log(target);				
		let selectIdArr = $(this).prop("id").split('_');
		let selectId    = selectIdArr[1];
		let selectName  = $(this).text();

		$(this).parent().siblings("button").text(selectName);
		$(this).parent().siblings("input").val(selectId);
	});
		
	target2.find("li.option_list_item").click(function () {		
		let selectIdArr = $(this).prop("id").split('_');
		let selectId    = selectIdArr[1];
		let selectName  = $(this).text();

		$(this).parent().siblings("button").text(selectName);
		$(this).parent().siblings("input").val(selectId);
	});
}


/****************************************************************************
* select box 선택 값 id, text로 셋팅
****************************************************************************/
function fn_clickSelectValue(target){
	let selectIdArr = $(target).prop("id").split('_');
	let selectId    = selectIdArr[1];
	let selectName  = $(target).text();
	
	$(target).parent().siblings("button").text(selectName);
	$(target).parent().siblings("input").val(selectId);
}

/****************************************************************************
* select box 선택 값 셋팅
****************************************************************************/
function fn_clickSelectTextValue(target, param, paramText){
	$(target).parent().siblings("button").text(paramText);
	$(target).parent().siblings("input").val(param);
}

/****************************************************************************
* 직원 정보 수정
****************************************************************************/
function fn_updateCompany(){
	let companyName      = $("#companyName").val();
	let businessNumber   = $("#businessNumber").val();
	let userName         = $("#userName").val();
	let phoneNumber      = $("#phoneNumber").val();
	let email            = $("#email").val();
	let memo             = $("#memo").val();
	
	let reg_email    = /^([0-9a-zA-Z_\.-]+)@([0-9a-zA-Z_-]+)(\.[0-9a-zA-Z_-]+){1,2}$/;
	let reg_tel      = /^[0-9]{8,11}$/;

	// 제품 정보
	let detailArray = new Object();
	
	if("Y"!=updateUseYn){
		modalEvent.warning("수정", "수정 권한이 없습니다.");
		return false;
	}
	
	if(true != fn_emptyCheck(muCompanyId)){
		modalEvent.warning("수정", "거래처 정보가 없습니다.");	
		return;
	}
	
	if(true != fn_emptyCheck(companyName)){
		modalEvent.warning("수정", "거래처명 정보가 없습니다.");	
		return;
	}
	else{
		if(true != fn_lengthCheck(companyName, 35)) {
			modalEvent.warning("수정", "거래처명 정보는 35자를 넘을 수 없습니다.");	
			return;
		}
	}
	
	// if(true != fn_emptyCheck(businessNumber)){
	// 	modalEvent.warning("수정", "사업자번호 정보가 없습니다.");
	// 	return;
	// }
	
	if(true == fn_emptyCheck(userName)&&true != fn_lengthCheck(userName, 35)) {
		modalEvent.warning("수정", "담당자명 정보는 35자를 넘을 수 없습니다.");
		return;
	}
	if(true == fn_emptyCheck(phoneNumber)&&reg_tel.test(phoneNumber) != true){
		modalEvent.warning("등록", "연락처 정보는 숫자 8~11자리여야 합니다");
		return;
	}
	else{
		phoneNumber = phoneNumber.replace("-", "");
	}

	if(true == fn_emptyCheck(email)&&!reg_email.test(email)) {
		modalEvent.warning("등록", "이메일 정보를 형식에 맞게 입력해주세요");
		return ;
	}
	
	// 제품 정보
	let productTr = $('#productList').children('tr');
	let trLength  = productTr.length;
	
	let tempArray = new Array();
	for(let i=0 ; i < trLength ; i++){
		let muProductId      = productTr.eq(i).find('input[name="muProductId"]').val();
		let muTreatmentId    = productTr.eq(i).find('input[name="muTreatmentId"]').val();
		let productName      = productTr.eq(i).find('input[name="productName"]').val();
		let volume           = productTr.eq(i).find('input[name="volume"]').val();
		let unitCode         = productTr.eq(i).find('input[name="unit"]').val();
		let unitName         = productTr.eq(i).find('input[name="unit"]').siblings('button').text();
		let usage_volume    = productTr.eq(i).find('input[name="usage_volume"]').val();
		let usage_unitCode  = productTr.eq(i).find('input[name="usage_unit"]').val();
		let usage_unitName  = productTr.eq(i).find('input[name="usage_unit"]').siblings('button').text();


		let arr_sub 	= new Object();
		arr_sub.muProductId  	= muProductId;
		arr_sub.muTreatmentId   = muTreatmentId;
		arr_sub.productName  	= productName;
		arr_sub.volume       	= volume;
		arr_sub.unitCode        = unitCode;
		arr_sub.unitName        = unitName==='제품단위'?'':unitName;
		arr_sub.usage_volume   = usage_volume;
		arr_sub.usage_unitCode = usage_unitCode;
		arr_sub.usage_unitName = usage_unitName==='제품단위'?'':usage_unitName;
		console.log(volume);
		if(muTreatmentId||productName||volume||unitCode||arr_sub.unitName||usage_volume||usage_unitCode||arr_sub.usage_unitName) {
			if (true != fn_emptyCheck(muTreatmentId)) {
				modalEvent.warning("등록", "거래처 제품 중 구분 정보가 없습니다.");
				return;
			} else if (true != fn_emptyCheck(productName)) {
				modalEvent.warning("등록", "거래처 제품 중 제품명 정보가 없습니다.");
				return;
			} else if (true != fn_emptyCheck(volume)) {
				modalEvent.warning("등록", "거래처 제품 중 용량 정보가 없습니다.");
				return;
			} else if (true != fn_emptyCheck(unitCode)) {
				modalEvent.warning("등록", "거래처 제품 중 단위 정보가 없습니다.");
				return;
			} else if (true != fn_emptyCheck(unitName)) {
				modalEvent.warning("등록", "거래처 제품 중 단위 정보가 없습니다.");
				return;
			} else if (true != fn_emptyCheck(usage_volume)) {
				modalEvent.warning("등록", "거래처 제품 중 사용량 정보가 없습니다.");
				return;
			} else if (true != fn_emptyCheck(usage_unitCode)) {
				modalEvent.warning("등록", "거래처 제품 중 사용량 단위 정보가 없습니다.");
				return;
			} else if (true != fn_emptyCheck(usage_unitName)) {
				modalEvent.warning("등록", "거래처 제품 중 사용량 단위 정보가 없습니다.");
				return;
			}
			tempArray.push(arr_sub);
		}
		detailArray.data = tempArray;
	}

	modalEvent.info("수정", "거래처 정보를 수정하시겠습니까?", function(){
		let formData = new FormData();
		formData.append("menuClass", menuClass);
		formData.append("muCompanyId", muCompanyId);
		formData.append("companyName", companyName);
		formData.append("businessNumber", businessNumber);
		formData.append("userName", userName);
		formData.append("phoneNumber", phoneNumber);
		formData.append("email", email);
		formData.append("memo", memo);
		formData.append("companyProductRows",JSON.stringify(detailArray));		
		$.ajax({
			url: encodeURI('/webcompany/updateCompany.do'),
			data: formData,
			dataType: 'json',
			processData: false,
			contentType: false,
			type: 'POST',
			async: true,
			success: function(data){
				if('0'==data.msgCode){
					modalEvent.success("수정 성공", data.msgDesc, function(){
						fn_companyOk();
					});
				}
				else{
					modalEvent.danger("수정 오류", data.msgDesc);
				}
			},
			error : function(xhr, status, error) {
				modalEvent.danger("수정 오류", "수정 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
			},
			beforeSend:function(){
				
			},
			complete:function(){
				
			}
		});
	});
}

function fn_companyOk(){
	let pagingParam = "?menuClass="+menuClass;
	pagingParam    += "&companySearchKeywordParam="+companySearchKeywordParam;
	pagingParam    += "&companySort="+companySort;
	pagingParam    += "&companyDir="+companyDir;
	pagingParam    += "&companyStart="+companyStart;
	pagingParam    += "&companyLimit="+companyLimit;
	
	fn_leftFormAction("/webcompany/selectListCompanyIntro.do"+pagingParam);
}

function fn_companyCancel(){
	let pagingParam = "?menuClass="+menuClass;
	pagingParam    += "&companySearchKeywordParam="+companySearchKeywordParam;
	pagingParam    += "&companySort="+companySort;
	pagingParam    += "&companyDir="+companyDir;
	pagingParam    += "&companyStart="+companyStart;
	pagingParam    += "&companyLimit="+companyLimit;
	
	fn_leftFormAction("/webcompany/selectListCompanyIntro.do"+pagingParam);
}

/****************************************************************************
* 페이지 init
****************************************************************************/
function fn_pageInit(){
	// 뒤로가기 버튼 이벤트 및 노출
	$(".back").removeAttr("onclick");
	$(".back").attr("onclick", "fn_companyCancel();");
	$(".back").show();
	
	fn_selectCompany();
}

/****************************************************************************
* 페이지 event
****************************************************************************/
function fn_pageEvent(){
	// 저장 버튼
	$("#btnUpdateCompany").click(function () {
		fn_updateCompany();
	});
}

$(function(){
	// 페이지 init
	fn_pageInit();
	
	// 페이지 event
	fn_pageEvent();
});