
function init_language() {
    jQuery.i18n.properties({
        name: 'common',
        path: '../lang/',
        mode: 'map',
        language: window.parent.get_language_setup(),
        callback: function () {
            $('#header_text').html($.i18n.prop('screen_setting'));
            $('#display_tip_text').html($.i18n.prop('screen_display_tip_text'));
            $('#priority_tip_text').html($.i18n.prop('screen_priority_tip_text'));
            $('#layoutset_enable_txt').html($.i18n.prop('layoutset_enable_txt'));
            $('#layoutset_enable_text').html($.i18n.prop('index_common_enable'));
            $('#layoutset_disable_text').html($.i18n.prop('index_common_disable'));
			$('#screen_background_txt').html($.i18n.prop('screen_background_txt'));
			for(var i = 0; i < 4; i++){
				$('#screen_sub_txt_' + i).html($.i18n.prop('screen_sub_txt') + (i+1));
				$('#sub_info_' + i).html($.i18n.prop('screen_sub_txt') + (i+1));
				$('#display_txt_' + i).html($.i18n.prop('screen_sub_txt') + (i+1));
				$('#sub_position_' + i).html($.i18n.prop('sub_position'));
				$('#sub_size_' + i).html($.i18n.prop('sub_size'));
				$('#sub_size_w_' + i).html($.i18n.prop('sub_size_w'));
				$('#sub_size_h_' + i).html($.i18n.prop('sub_size_h'));
				// $('#' + i).html($.i18n.prop(''));
			}
			$('#system_setting').val($.i18n.prop('system_setting'));
			$('#default_setting').val($.i18n.prop('default_setting'));
			refresh_layout_window_panels();

        }
    });
}

function update_window_panel_state(index) {
	var panel = $("#layout_window_panel_" + index);
	if (!panel.length) return;
	var is_hidden = $("#screen_sub_" + index).hasClass("display_off");
	panel.toggleClass("is-hidden", is_hidden);
	$("#layout_window_state_" + index).html(is_hidden ? $.i18n.prop('index_common_disable') : $.i18n.prop('index_common_enable'));
}

function refresh_layout_window_panels() {
	for (var i = 0; i < 4; i++) {
		var panel = $("#layout_window_panel_" + i);
		if (!panel.length) continue;
		if (i < wnd) {
			panel.removeClass("display_off");
			update_window_panel_state(i);
		} else {
			panel.addClass("display_off");
		}
	}
}

function layoutsetEnable(){
	var enable = $("#layoutset_enable").val();
	if(enable == 0){
		$("#screen_background").addClass("layoutset_disable");
		for(var i = 0; i < wnd; i++){
			$("#sub_display_" + i).addClass("layoutset_disable");
		}
	}else if(enable == 1){
		$("#screen_background").removeClass("layoutset_disable");
		for(var i = 0; i < wnd; i++){
			$("#sub_display_" + i).removeClass("layoutset_disable");
		}
	}
}

//布局设置部分
var wnd = 0;
function get_screen_resolution(){
	$.ajax({
		type: "GET",
		url: "http://" + xc_gethost() + "/get_vopos",
		dataType: "xml",
		cache: false,
		async: false,
		error: function () {
		},
		success: function (data) {
			var vo_enable = $(data).find("vopos").find("enable").text();
			$("#layoutset_enable").val(vo_enable);
			wnd = $(data).find("vopos").find("wndnum").text();
			layoutsetEnable();
			for(var i = 0; i < wnd; i++){
				$("#screen_sub_" + i).removeClass("display_off");
				$("#sub_display_" + i).removeClass("display_off");
				var vo_pos_show = $(data).find("vopos").find("show" + i).text();
				$("#screen_sub_display_" + i).val(vo_pos_show);
				if(vo_pos_show == 0){
					$("#screen_sub_" + i).addClass("display_off");
					$("#screen_sub_display_" + i).addClass("operation_hide");
				}else if(vo_pos_show == 1){
					$("#screen_sub_display_" + i).addClass("operation_display");
				}

				var vo_pos_x = $(data).find("vopos").find("voposx" + i).text();
				var vo_pos_y = $(data).find("vopos").find("voposy" + i).text();
				var vo_pos_w = $(data).find("vopos").find("voposw" + i).text();
				var vo_pos_h = $(data).find("vopos").find("voposh" + i).text();
				if(vo_pos_w < minWidth)
					vo_pos_w = minWidth;
				if(vo_pos_h < minHeight)
					vo_pos_h = minHeight;
				$("#screen_sub_" + i).attr("style", "margin: 0px");
				$("#screen_sub_" + i).css({
					'left': (vo_pos_x*0.4) + 'px',
					'top': (vo_pos_y*0.4) + 'px',
					'width': (vo_pos_w*0.4) + 'px',
					'height': (vo_pos_h*0.4) + 'px'
				});
				$("#voposx" + i).val(vo_pos_x);
				$("#voposy" + i).val(vo_pos_y);
				$("#voposw" + i).val(vo_pos_w);
				$("#voposh" + i).val(vo_pos_h);

			}
			refresh_layout_window_panels();
		}
	});
}


function set_screen_resolution(){
	var tmp = "";
	var vo_enable = $("#layoutset_enable").val();
	tmp += "enable=" + vo_enable + "&";
	for(var i = 0; i < wnd; i++){
		if ($("#screen_sub_" + i).hasClass("display_off")){

		}else{
			var vo_pos_show = $("#screen_sub_display_" + i).val();
			tmp += "show" + i + "=" + vo_pos_show + "&";

			var vo_pos_x = $("#voposx" + i).val();
			tmp += "voposx" + i + "=" + vo_pos_x + "&";
			var vo_pos_y = $("#voposy" + i).val();
			tmp += "voposy" + i + "=" + vo_pos_y + "&";

			var vo_pos_w = $("#voposw" + i).val();
			tmp += "voposw" + i + "=" + vo_pos_w + "&";
			var vo_pos_h = $("#voposh" + i).val();
			tmp += "voposh" + i + "=" + vo_pos_h + "&";
		}
	}
	console.log("tmp=" + tmp);
	$.ajax({
		type: "GET",
		url: "http://" + xc_gethost() + "/set_vopos" + "?" + tmp,
		cache: false,
		async: false,
		success: function (data) {
			var ret = $(data).find("return").text();
			if ("ok" == ret) {
				console.log("vopos succeed");
				alert($.i18n.prop('system_setting_success'));
			}
		},
		error: function (){
			alert($.i18n.prop('system_setting_failed'));
		}
	});
}

function sub_screen_display(i){
	var display = $("#screen_sub_display_" + i).val();
	if(display == 0){
		if(wnd == 4){
			init4ChnDisplay();
		}else{
			$("#screen_sub_" + i).removeClass("display_off");
			$("#screen_sub_display_" + i).removeClass("operation_hide");
			$("#screen_sub_display_" + i).addClass("operation_display");
			display = 1;
			$("#screen_sub_display_" + i).val(display);
		}
	}else if(display == 1){
		$("#screen_sub_" + i).addClass("display_off");
		$("#screen_sub_display_" + i).removeClass("operation_display");
		$("#screen_sub_display_" + i).addClass("operation_hide");
		display = 0;
		$("#screen_sub_display_" + i).val(display);
	}
	update_window_panel_state(i);
}

function chnlayout_default(){
	$("#layoutset_enable").val(0);
	if(wnd == 1){
		init1ChnDisplay();
	}else if(wnd == 4){
		init4ChnDisplay();
	}
}

function init1ChnDisplay(){
	$("#screen_sub_0").removeClass("display_off");
	$("#screen_sub_display_0").val(1);
	$("#screen_sub_display_0").removeClass("operation_hide");
	$("#screen_sub_display_0").addClass("operation_display");
	$("#screen_sub_0").css({
		'left': '0px',
		'top': '0px',
		'width': '768px',
		'height': '432px'
	});

	$("#voposx0").val(0);
	$("#voposy0").val(0);
	$("#voposw0").val(1920);
	$("#voposh0").val(1080);
	update_window_panel_state(0);
}

function init4ChnDisplay(){
	var showNum = 0;
	var midWidth = 960;
	var midHeight = 540;
	var defWidth = 384;
	var defHeight = 216;

	for(var i = 0; i < 4; i++){
		$("#screen_sub_" + i).removeClass("display_off");
		$("#screen_sub_display_" + i).val(1);
		$("#screen_sub_display_" + i).removeClass("operation_hide");
		$("#screen_sub_display_" + i).addClass("operation_display");
		$("#screen_sub_" + i).css({
			'left': (showNum % 2)*defWidth + 'px',
			'top': (Math.floor(showNum / 2))*defHeight + 'px',
			'width': defWidth + 'px',
			'height': defHeight + 'px'
		});

		$("#voposx" + i).val((showNum % 2)*midWidth);
		$("#voposy" + i).val((Math.floor(showNum / 2))*midHeight);
		$("#voposw" + i).val(midWidth);
		$("#voposh" + i).val(midHeight);

		showNum++;
		update_window_panel_state(i);
	}
}

// 设置修改input同步改变图形位置尺寸功能
function x_change(i){
	var x_input = $("#voposx" + i).val();
	x_input = parseInt((x_input*0.4), 10);

	$("#screen_sub_" + i).css({
		'left': x_input + 'px'
	});
}

function y_change(i){
	var y_input = $("#voposy" + i).val();
	y_input = parseInt((y_input*0.4), 10);
	$("#screen_sub_" + i).css({
		'top': y_input + 'px'
	});
}

function w_change(i){
	var w_input = $("#voposw" + i).val();
	w_input = parseInt((w_input*0.4), 10);
	$("#screen_sub_" + i).css({
		'width': w_input + 'px'
	});
}

function h_change(i){
	var h_input = $("#voposh" + i).val();
	h_input = parseInt((h_input*0.4), 10);
	$("#screen_sub_" + i).css({
		'height': h_input + 'px'
	});
}

function setupDragAndResize(index){
    const parentContainer = $("#screen_background")[0]; // 转为DOM对象
	const $resizableDiv = $("#screen_sub_" + index); // jQuery对象
	const $xValue = $("#voposx" + index); 
	const $yValue = $("#voposy" + index); 
	const $widthValue = $("#voposw" + index);
	const $heightValue = $("#voposh" + index); 

	// 获取DOM对象用于事件监听
	const resizableDiv = document.getElementById("screen_sub_" + index);
	const resizeHandle = document.getElementById("resize_handle_" + index);

	let isDragging = false;
	let isResizing = false;
	let dragStartX, dragStartY, dragStartLeft, dragStartTop;
	let resizeStartX, resizeStartY, resizeStartWidth, resizeStartHeight;

	$("#screen_sub_" + index).mousedown(function(e) {
		// 防止重复触发
		e.stopImmediatePropagation();

		if (e.target === resizeHandle) return;
		
		isDragging = true;
		dragStartX = e.clientX;
		dragStartY = e.clientY;
		dragStartLeft = parseInt(document.defaultView.getComputedStyle(resizableDiv).left, 10);
		dragStartTop = parseInt(document.defaultView.getComputedStyle(resizableDiv).top, 10);
		
		e.preventDefault();
	});
	
	resizeHandle.addEventListener('mousedown', function(e) {
		isResizing = true;
		resizeStartX = e.clientX;
		resizeStartY = e.clientY;
		resizeStartWidth = parseInt(window.getComputedStyle(resizableDiv).width, 10);
		resizeStartHeight = parseInt(window.getComputedStyle(resizableDiv).height, 10);
		
		e.preventDefault();
		e.stopPropagation(); // 阻止事件冒泡到DIV的mousedown
	});

	document.addEventListener('mousemove', function(e) {
		if (isDragging) {
			getVisibleDivs();
			const newLeft = dragStartLeft + e.clientX - dragStartX;
			const newTop = dragStartTop + e.clientY - dragStartY;
			
			const parentWidth = parentContainer.clientWidth;
			const parentHeight = parentContainer.clientHeight;
			
			const divWidth = parseFloat(window.getComputedStyle(resizableDiv).width, 10);
			const divHeight = parseFloat(window.getComputedStyle(resizableDiv).height, 10);
			
			const boundedLeft = Math.max(0, Math.min(newLeft, parentWidth - divWidth));
			const boundedTop = Math.max(0, Math.min(newTop, parentHeight - divHeight));
		
			// 检查并调整位置以避免重叠
			const validPosition = findValidPosition(boundedLeft, boundedTop, divWidth, divHeight, index);

			$resizableDiv.css({
				'left': validPosition.left + 'px',
				'top': validPosition.top + 'px'
			});
			
			$xValue.val(parseInt((validPosition.left * 2.5), 10));
			$yValue.val(parseInt((validPosition.top * 2.5), 10));
			// $xValue.val(validPosition.left);
			// $yValue.val(validPosition.top);
		}
		
		if (isResizing) {
			getVisibleDivs();
			const newWidth = resizeStartWidth + e.clientX - resizeStartX;
			const newHeight = resizeStartHeight + e.clientY - resizeStartY;
			
			const parentWidth = parentContainer.clientWidth;
			const parentHeight = parentContainer.clientHeight;
			
			const divLeft = parseFloat(window.getComputedStyle(resizableDiv).left, 10);
			const divTop = parseFloat(window.getComputedStyle(resizableDiv).top, 10);
			
			// 最小尺寸在config.js中设置
			const maxWidth = parentWidth - divLeft;
			const maxHeight = parentHeight - divTop;
			
			const boundedWidth = Math.max((minWidth*0.4), Math.min(newWidth, maxWidth));
			const boundedHeight = Math.max((minHeight*0.4), Math.min(newHeight, maxHeight));
			
			// 检查并调整尺寸以避免重叠
			const validSize = findValidSize(divLeft, divTop, boundedWidth, boundedHeight, index);
			
			$resizableDiv.css({
				'width': validSize.width + 'px',
				'height': validSize.height + 'px'
			});
			
			$widthValue.val(parseInt((validSize.width * 2.5), 10));
			$heightValue.val(parseInt((validSize.height * 2.5), 10));
			// $widthValue.val(validSize.width);
			// $heightValue.val(validSize.height);
		}
	});
	
	document.addEventListener('mouseup', function(e) {
		isDragging = false;
		isResizing = false;
	});

}

// 禁止画面重叠
const visibleDivs = [];
function getVisibleDivs(){
	for(var i = 0; i < xc_getwndnum(); i++){
		if($("#screen_sub_" + i).hasClass("display_off")){
			visibleDivs[i] = 0;
		}else{
			const divElement = $("#screen_sub_" + i)[0];
			var rect = {
				left: parseInt(window.getComputedStyle(divElement).left, 10),
				top: parseInt(window.getComputedStyle(divElement).top, 10),
				width: parseInt(window.getComputedStyle(divElement).width, 10),
				height: parseInt(window.getComputedStyle(divElement).height, 10)
			};
			rect.right = rect.left + rect.width;
			rect.bottom = rect.top + rect.height;
			visibleDivs[i] = rect;
		}
	}
}

// 检查两个矩形是否重叠
function isOverlapping(rect1, rect2) {
	return !(rect1.right <= rect2.left || 
			rect1.left >= rect2.right || 
			rect1.bottom <= rect2.top || 
			rect1.top >= rect2.bottom);
}

// 检查指定位置和大小是否与其他div重叠
function checkCollision(left, top, width, height, currentIndex) {
	const currentRect = {
		left: left,
		top: top,
		width: width,
		height: height,
		right: left + width,
		bottom: top + height
	};

	for (let i = 0; i < visibleDivs.length; i++) {
		// 跳过当前操作的div和不可见的div（值为0）
		if (i !== currentIndex && visibleDivs[i] !== 0 && isOverlapping(currentRect, visibleDivs[i])) {
			return true; // 发生重叠
		}
	}
	return false; // 没有重叠
}

// 找到不重叠的最近有效位置（用于拖拽）
function findValidPosition(targetLeft, targetTop, width, height, currentIndex) {
	// 如果目标位置不重叠，直接返回
	if (!checkCollision(targetLeft, targetTop, width, height, currentIndex)) {
		return { left: targetLeft, top: targetTop };
	}

	const step = 1; // 每次移动5像素
	const maxDistance = 50; // 最大搜索距离
	const parentContainer = $("#screen_background")[0];

	for (let distance = step; distance <= maxDistance; distance += step) {
		// 尝试8个方向
		const directions = [
			[0, -distance],  // 上
			[distance, 0],   // 右
			[0, distance],   // 下
			[-distance, 0],  // 左
			[distance, -distance], // 右上
			[distance, distance],  // 右下
			[-distance, distance], // 左下
			[-distance, -distance] // 左上
		];

		for (let dir of directions) {
			const newLeft = targetLeft + dir[0];
			const newTop = targetTop + dir[1];
			
			// 检查是否在父容器范围内
			if (newLeft >= 0 && newTop >= 0 && 
				newLeft + width <= parentContainer.clientWidth &&
				newTop + height <= parentContainer.clientHeight) {
				
				if (!checkCollision(newLeft, newTop, width, height, currentIndex)) {
					return { left: newLeft, top: newTop };
				}
			}
		}
	}
	// 如果找不到合适位置，返回当前位置
	const resizableDiv = document.getElementById("screen_sub_" + currentIndex);
	return {
		left: parseInt(window.getComputedStyle(resizableDiv).left, 10),
		top: parseInt(window.getComputedStyle(resizableDiv).top, 10)
	};
}

// 找到不重叠的最大有效尺寸（用于调整大小）
function findValidSize(left, top, targetWidth, targetHeight, currentIndex) {
	// 如果目标尺寸不重叠，直接返回
	if (!checkCollision(left, top, targetWidth, targetHeight, currentIndex)) {
		return { width: targetWidth, height: targetHeight };
	}

	// 从目标尺寸开始，逐步缩小直到不重叠
	const minSize = Math.min(minWidth * 0.4, minHeight * 0.4);
	for (let w = targetWidth; w >= minSize; w -= 5) {
		if (!checkCollision(left, top, w, targetHeight, currentIndex)) {
			return { width: w, height: targetHeight };
		}
	}
	for (let h = targetHeight; h >= minSize; h -= 5) {
		if (!checkCollision(left, top, targetWidth, h, currentIndex)) {
			return { width: targetWidth, height: h };
		}
	}
	for (let w = targetWidth; w >= minSize; w -= 5) {
		for (let h = targetHeight; h >= minSize; h -= 5) {
			if (!checkCollision(left, top, w, h, currentIndex)) {
				return { width: w, height: h };
			}
		}
	}
	const resizableDiv = document.getElementById("screen_sub_" + currentIndex);
	return {
		width: parseInt(window.getComputedStyle(resizableDiv).width, 10),
		height: parseInt(window.getComputedStyle(resizableDiv).height, 10)
	};
}


$(function () {
	init_language();
	get_screen_resolution();

	for(var i = 0; i < 4; i++){
		setupDragAndResize(i);
	}
});
