/*
NAME: JNS_ss_font_fill
DESCRIPTION: 空心文字填实
PARAMETER:
	[
		{
			name : 'step',
			title : 'step',
			type : 'LineEdit',
			property : {tool_tip : '目标step,默认是orig'}
		},
		{
			name : 'workLayers',
			title : 'workLayers',
			type : 'LineEdit',
			property : {tool_tip : '工作层'}
		},
		{
			name : 'auto_save',
			title : '自动保存',
			type : 'RadioBox',
			property : {
				item_list:[
					{name:'yes',text:'YES'},
					{name:'no',text:'NO'},
				],
				tool_tip:'是否自动保存料号开关'
			}
		}
	]
	
 VERSION_HISTORY:
	V1.00 2023-02-14 kunli
		1.新版本
	
		
 HELP:
	  <html><body bgcolor="#DDECFE">
		<font size="3" color="#003DB2"><p>功能简介</p></font>
		<p> 空心文字填实 </ p>
		<br>
		<font size="3" color="#003DB2"><p>参数配置</p></font>
		<p>  </p>
		<br>
		<font size="3" color="#003DB2"><p>注意事项</p></font>
		<p> 非同一回路的非线属性的文字无法填实，需要手动作业 </p>
		<br>
	</body></html>	
*/

// 引入模块 包 外部参数
var $ = require('topcam.scriptfunc').argv();
var fs = require('fs');
var _ = require('lodash');
var mode = $.ikm ? "topcam" : "aimdfm";
var IKM = $.ikm ? $.ikm : require('topcam.ikm6')($);
var GEN = $.gen;
var Job = $.job || $.job_name;
var JobId = $.job_id;
var db = $.db || IKM.db;
var plugin = require('topsin.gengui');
var GUI = plugin.newGui(plugin.__dirname);
var PAR = {};
if ($.par) {
	PAR = $.par;
} else if ($.hasOwnProperty('script_parameter')) {
	PAR = JSON.parse($.script_parameter);
}
if (mode === "aimdfm") {
	IKM.crud("updateRow", {
		table: "pdm_aimdfm_task",
		data: { current_process_title: $.process_title },
		where: { id: $.task_id }
	});
}
var Status = 'ok';
var resultData = [];
var par = PAR; // 接收参数
var default_par = { // 设置默认参数
	step: "cad",
	auto_save: "No",
	workLayers: "out",
	units: "mm"
};
for (var key in default_par) {
	if (!par.hasOwnProperty(key) || par[key] == "") {
		par[key] = default_par[key];
	}
}

// 定义变量
var job = Job.toLowerCase();
require("topsin.genmath");
var genMath = new GenMath();
var last_move_distance = 0;
try {

	// 常规验证 准备工作
	if (!GEN.isJobExists({ job: job })) { throw "料号" + job + "不存在" }
	if (!GEN.isJobOpen({ job: job })) { GEN.openJob({ job: job }) }
	if (mode == "aimdfm") {
		if (GEN.checkInout({ job: job, mode: "test" }) != 0) {
			throw "the job check"
		}
		GEN.checkInout({ job: job, mode: "out" });
	}
	// 主体
	var stepList = GEN.getStepList({ job: job });
	stepList = stepList.filter(function (v) {
		var tmpreg = new RegExp(par.step, "ig");
		return tmpreg.test(v);
	});
	if (stepList.length == 0) {
		throw "未找到" + par.step
	}

	var workLayers = par.workLayers.split(";")
	workLayers = workLayers.filter(function (l) { return GEN.isLayerExists({ job: job, layer: l }) })
	if (workLayers.length == 0) {
		throw "没有找到工作层"
	}

	for (var step_cot = 0; step_cot < stepList.length; step_cot++) {
		var step = stepList[step_cot];
		GEN.openStep({ job: job, name: step });
		GEN.clearLayers();  //清除层显示
		GEN.affectedLayer({ mode: 'all', affected: 'no' }); //设置影响层全部不影响
		GEN.COM("sel_options,clear_mode=clear_after,display_mode=all_layers,area_inout=inside,area_select=select,select_mode=standard,area_touching_mode=exclude");
		GEN.units({ type: par.units }); //单位初始化
		GEN.zoomHome();  //窗口显示回到原始位置
		GEN.selClearFeature()
        var select_ans = GEN.PAUSE('Please select features');
						if (!_.eq(select_ans, "OK")) {
							return 'Done';
						}

		// for (var work_layer_cot = 0; work_layer_cot < workLayers.length; work_layer_cot++) {
		// 	var work_layer = workLayers[work_layer_cot];
		// 	var ans = 'OK';
		// 	do {

		// 		var line_type = 0; //1 代表横，2代表竖
		// 		var line_info = [];
		// 		do {
		// 			do {
		// 				GEN.workLayer({ name: work_layer, display_number: 1, clear_before: "yes" });
		// 				var select_ans = GEN.PAUSE('Please select features');
		// 				if (!_.eq(select_ans, "OK")) {
		// 					return 'Done';
		// 				}

		// 			} while (GEN.getSelectCount() == 0);
		// 			line_info = GEN.getFeatures({ job: job, step: step, layer: work_layer, options: "select+feat_index", units: 'mm' });
		// 			GEN.selClearFeature();
		// 			var line_k = -999;
		// 			var has_err = 0;
		// 			for (var i = 0; i < line_info.length; i++) {
		// 				var cur_kb_val = genMath.getLineKb(line_info[i]);
		// 				var cur_k_val = 999;
		// 				if (_.isValid(cur_kb_val["k"]) && _.fuzzyEqual(_.toNumber(cur_kb_val["k"]), 0)) {
		// 					cur_k_val = cur_kb_val["k"];
		// 				}
		// 				// GUI.debug({ text: '--cur_kb_val-' + _.toString(cur_kb_val) +"--" + _.toString(cur_k_val) });

		// 				if (i === 0) {
		// 					line_k = cur_k_val;
		// 				} else if (!_.fuzzyEqual(line_k, cur_k_val)) {
		// 					GUI.msgBox({
		// 						title: '错误提示',
		// 						text: '选择的非同一方向的线，请重选',
		// 						buttons: ['Ok', 'Cancel']
		// 					});
		// 					has_err = 1;
		// 					break;
		// 				}
		// 			}
		// 			// GUI.debug({ text: '--line_info-' + _.toString(line_info) +"--" + _.toString(line_k) + "==" + has_err});

		// 			if (has_err == 1) {
		// 				line_type = 0;
		// 			} else {
		// 				if (_.fuzzyEqual(line_k, 0)) {
		// 					line_type = 1;
		// 				} else if (_.fuzzyEqual(line_k, 999)) {
		// 					line_type = 2;
		// 				}
		// 			}
		// 		} while (line_type == 0);
		// 		// GUI.debug({ text: '--line_type-' + _.toString(line_type) });

		// 		var move_info = get_move_info(line_type);
		// 		if (_.isEmpty(move_info)) {
		// 			return 'Cancel';
		// 		}
		// 		// GUI.debug({ text: '--move_info-' + _.toString(move_info) });


		// 		// move
		// 		var move_distance = move_info["move_distance"];
		// 		var move_direction = move_info["move_direction"];
		// 		last_move_distance = move_distance;
		// 		var dx_v = 0;
		// 		var dy_v = 0;
		// 		if (_.eq(move_direction, "up")) {
		// 			dx_v = 0;
		// 			dy_v = move_distance;
		// 		} else if (_.eq(move_direction, "down")) {
		// 			dx_v = 0;
		// 			dy_v = -move_distance;
		// 		} else if (_.eq(move_direction, "left")) {
		// 			dx_v = -move_distance;
		// 			dy_v = 0;
		// 		} else if (_.eq(move_direction, "right")) {
		// 			dx_v = move_distance;
		// 			dy_v = 0;
		// 		}


		// 		for (var i = 0; i < line_info.length; i++) {
		// 			GEN.selLayerFeat({ layer: work_layer, index: line_info[i].index, operation: "select" });
		// 		}
		// 		GEN.selMove({ dx: dx_v, dy: dy_v });
		// 		GEN.selClearFeature();

		// 		ans = GUI.msgBox({
		// 			title: '错误提示',
		// 			text: '是否继续移动',
		// 			buttons: ['Ok', 'Cancel']
		// 		});
		// 		// GUI.debug({ text: '--ans-' + _.toString(ans) });

		// 	} while (/ok/i.test(ans));


		// };

		GEN.affectedLayer({ mode: 'all', affected: 'no' }); //设置影响层全部不影响
		GEN.clearLayers();  //清除层显示
	};

	// 保存料号
	if (/yes/ig.test(par.auto_save)) {
		GEN.checkInout({ job: job, mode: "out" });
		GEN.saveJob({ job: job });
		GEN.checkInout({ job: job, mode: "in" });
	}

	// 结尾返回  固定写法
	var Return = "Done";
	if (mode === "aimdfm") {
		IKM.crud("updateRow", {
			table: "pdm_aimdfm_task",
			data: { progress: 100 },
			where: { id: $.task_id }
		});
		var tmperr = { type: "info", title: "操作完成, 请注意检查!" };
		if (GEN.hasError()) {
			Status = 'error';
			tmperr = { type: "error", title: "GEN错误!", detail: [{ desc: GEN.STATUS.join("\n") }] };
		}
		resultData.push(tmperr);
		Return = { status: Status, result_data: resultData };
	}
	return Return;
} catch (e) {
	var showGUI = true;
	if (GEN.STATUS.length > 0) {
		if (GEN.STATUS.indexOf("Pause Exit:0") >= 0) {
			showGUI = false;
		}
		e = _.toString(e) + "\n" + GEN.STATUS.join("\n");
	}
	if (showGUI) {
		IKM.msg(e);
	}

	Status = 'error';
	resultData.push({ type: "error", title: "脚本执行出错!", detail: [{ desc: _.toString(e) }] });
	return mode === "aimdfm" ? { status: Status, result_data: resultData } : "Error";
}

/**
 * 
 * @param {*} layer 
 */
function delLayer(layer) {
	if (!Array.isArray(layer)) {
		layer = [layer]
	}
	layer = layer.filter(function (v) { return GEN.isLayerExists({ job: job, layer: v }) })
	if (layer.length > 0) {
		GEN.deleteLayer({ job: job, layer: layer })
	}
}

/**
 * 获取v-cut预放值，单位是mm,以及移动方向
 */
function get_move_info(iLineType) {
	var func = "function (props) {\
		return GUI.showForm({\
			title: 'v-cut移动距离(mm)',\
			size: '240x200',\
			use_core_engine: true,\
			include_hidden_items: true,\
			items: {\
				type: 'ScrollArea',\
				property: {\
					widget_resizable: true,\
					frame_shape: 'NoFrame'\
				},\
				child: [{\
					type: 'FormGridLayout',\
					property: {},\
					child: props.child\
				}]\
			},\
			values: props.value,\
		})\
	}";
	var child = [{
		name: 'move_distance',
		title: '移动距离:',
		type: 'DoubleLineEdit',
		property: {
			tool_tip: '移动距离'
		}
	}
	];
	if (iLineType == 1) {
		child.unshift({
			name: 'move_direction',
			title: '移动方向:',
			type: 'RadioBox',
			property: {
				item_list: [
					{ name: 'up', text: 'Up' },
					{ name: 'down', text: 'Down' },
				],
				tool_tip: '移动方向'
			}

		});
	} else {
		child.unshift({
			name: 'move_direction',
			title: '移动方向:',
			type: 'RadioBox',
			property: {
				item_list: [
					{ name: 'left', text: 'Left' },
					{ name: 'right', text: 'Right' },
				],
				tool_tip: '移动方向'
			}

		});
	}
	var value = {move_distance :last_move_distance};

	var data = IKM.command(func, { child: child, value: value }, 1).data;
	// GUI.debug({text: 'data-----' + _.toString(data)});
	return data;
}