/*
NAME: 
DESCRIPTION: ;
PARAMETER:
    [
		{
			name : 'step',
			title : 'step',
			type : 'LineEdit',
			property : {tool_tip : '目标step,默认是orig'},
		},
		{
            name : 'auto_save',
			title : '自动保存',
            type : 'RadioBox',
            property : {
				item_list:[
					{name:'yes',text:'YES'},
					{name:'no',text:'NO'},
				],
				tool_tip:'是否自动保存料号开关'
			}
        }
	]
	
 VERSION_HISTORY:
	V1.00 2020-09-01 Scott Sun
	    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> step信息 </p>
		<br>
		<font size="3" color="#003DB2"><p>注意事项</p></font>
		<p> 无 </p>
		<br>
	</body></html>	
*/
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
console.log("==============================>template");
// 引入模块 包
var $ = require('topcam.scriptfunc').argv();
var fs = require('fs');
var _ = require('lodash');
var mode = $.ikm ? "topcam" : "aimdfm";
var IKM = $.ikm; 
if (IKM==undefined ) { IKM = require('topcam.ikm6')($) }
var GEN = $.gen;
var GUI = $.gui || {};
var Job = $.job || $.job_name;
var JobId = $.job_id;
var db = $.db || IKM.db
var PAR = {}
if ($.par) { PAR = $.par } else if ($.hasOwnProperty('script_parameter')){ PAR = JSON.parse($.script_parameter); }
if (mode === "aimdfm") {
	var database = require("topsin.database");
	database.addConnection($.conf.database_conf, "DFM");
	var QDfm = database.query("DFM");
	$.QDfm = QDfm;
	if ($.conf.product_type == "aimdfm") {
		QDfm.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: "unit",
	auto_save: "No",
	units:"mm"
}
for(var key in default_par){ if (!par.hasOwnProperty(key) || par[key] == ""){ par[key] = default_par[key] }}
var job = Job;
try {
	if(_.isEmpty(job)){throw "参数job不存在"} else { job = job.toLowerCase() }
	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" } else { GEN.checkInout({job:job,mode:"out"}) } }
	var stepList = GEN.getStepList({job:job})
	stepList = stepList.filter(function(step){
		var reg = new RegExp(par.step,"ig")
		return reg.test(step)
	})
	
	var worklayer = [{},{}];
	var matrix = GEN.getMatrix({job:job})
	var tmp_e = {
		top:0,
		bot:1,
		bottom:1
	}
	for (var key in matrix) {
		var info = matrix[key];
		if(info.context == "board"){
			if(info.layer_type == "solder_mask" && /top|bot/.test(info.side)){
				worklayer[tmp_e[info.side]].sm = key;
			}
			if(info.layer_type == "signal" && /top|bot/.test(info.side)){
				worklayer[tmp_e[info.side]].sig = key;
			}
		}
	}

	stepList.forEach(function(step){
		GEN.openStep({job:job, name:step})
        GEN.units({type:par.units})
		GEN.clearLayers()
		worklayer.forEach(function(item){
			if(item.sig && item.sm){
				var sig = item.sig;
				var sm = item.sm;
				// 选择全包围类型
				GEN.workLayer({name:sm,display_number:2,clear_before:'yes'})
				GEN.COM("filter_atr_set,filter_name=ref_select,condition=yes,attribute=.smd")
				GEN.COM("sel_ref_feat,layers="+sig+",use=filter,mode=touch,pads_as=shape,f_types=line\;pad\;surface\;arc\;text,polarity=positive,include_syms=,exclude_syms=")
				GEN.COM("filter_atr_reset,filter_name=ref_select")
				if(GEN.getSelectCount() > 0) {
					delLayer(sm+"_tmp1");
					GEN.selCopyOther({dest:'layer_name',target_layer:sm+"_tmp1",invert:'no',dx:0,dy:0,size:0})
					GEN.workLayer({name:sm+"_tmp1",display_number:2,clear_before:'yes'})
					GEN.COM("sel_ref_feat,layers="+sig+",use=filter,mode=multi_cover,pads_as=shape,f_types=line\;pad\;surface\;arc\;text,polarity=positive\;negative,include_syms=,exclude_syms=")
					if(GEN.getSelectCount() > 0) {
						delLayer([sm+"_tmp2",sm+"_tmp3"]);
						GEN.selMoveOther({target_layer:sm+"_tmp2",invert:'no',dx:0,dy:0,size:0})
						// 制作 负性环
						GEN.workLayer({name:sm+"_tmp2",display_number:2,clear_before:'yes'})
						GEN.selCopyOther({dest:'layer_name',target_layer:sm+"_tmp3",invert:'no',dx:0,dy:0,size:0})
						GEN.selResize({size:-50})
						GEN.selMoveOther({target_layer:sm+"_tmp3",invert:'yes',dx:0,dy:0,size:0})
						delLayer([sm+"_tmp2"]);
						GEN.workLayer({name:sm+"_tmp3",display_number:2,clear_before:'yes'})
						GEN.selContourize()
						GEN.selMoveOther({target_layer:sm,invert:'yes',dx:0,dy:0,size:0})
						delLayer([sm+"_tmp3"]);
					}
					GEN.workLayer({name:sm+"_tmp1",display_number:2,clear_before:'yes'})
					GEN.COM("sel_ref_feat,layers="+sig+",use=filter,mode=touch,pads_as=shape,f_types=line\;arc,polarity=positive,include_syms=,exclude_syms=")
					GEN.selReverse()
					if(GEN.getSelectCount() > 0) {GEN.selDelete()}
					// 制作反层
					delLayer([sm+"_tmp4"]);
					GEN.createLayer({job:job,layer:sm+"_tmp4",type:'document'})
					GEN.workLayer({name:sm+"_tmp4",display_number:2,clear_before:'yes'})
					GEN.COM("sr_fill,polarity=positive,step_margin_x=0,step_margin_y=0,step_max_dist_x=100,\
				step_max_dist_y=100,sr_margin_x=0,sr_margin_y=0,sr_max_dist_x=0,sr_max_dist_y=0,\
				nest_sr=yes,stop_at_steps=,consider_feat=no,consider_drill=no,consider_rout=no,\
				dest=affected_layers,attributes=no");
					GEN.workLayer({name:sm+"_tmp1",display_number:2,clear_before:'yes'})
					GEN.selAllFeat()
					if(GEN.getSelectCount() > 0) {
						delLayer([sm+"_tmp5"]);
						GEN.selCopyOther({dest:'layer_name',target_layer:sm+"_tmp4",invert:'yes',dx:0,dy:0,size:0})
						GEN.workLayer({name:sig,display_number:2,clear_before:'yes'})
						GEN.COM("filter_set,filter_name=popup,update_popup=no,feat_types=line\;arc")
						GEN.COM("sel_ref_feat,layers="+sm+"_tmp1"+",use=filter,mode=touch,pads_as=shape,f_types=line\;pad\;surface\;arc\;text,polarity=positive\;negative,include_syms=,exclude_syms=")
						GEN.COM("filter_reset,filter_name=popup")
						if(GEN.getSelectCount() > 0) {
							GEN.selCopyOther({dest:'layer_name',target_layer:sm+"_tmp5",invert:'no',dx:0,dy:0,size:0})
						}
						GEN.COM("filter_reset,filter_name=popup")
						GEN.COM("filter_set,filter_name=popup,update_popup=no,feat_types=pad")
						GEN.COM("sel_ref_feat,layers="+sm+"_tmp1"+",use=filter,mode=touch,pads_as=shape,f_types=line\;pad\;surface\;arc\;text,polarity=positive\;negative,include_syms=,exclude_syms=")
						if(GEN.getSelectCount() > 0) {
							GEN.selCopyOther({dest:'layer_name',target_layer:sm+"_tmp5",invert:'yes',dx:0,dy:0,size:30})
						}
						GEN.workLayer({name:sm+"_tmp4",display_number:2,clear_before:'yes'})
						GEN.selContourize()
						GEN.selCopyOther({dest:'layer_name',target_layer:sm+"_tmp5",invert:'yes',dx:0,dy:0,size:0})
						GEN.workLayer({name:sm+"_tmp5",display_number:2,clear_before:'yes'})
						GEN.PAUSE(0)
						GEN.selContourize()
						GEN.selResize({size: 100})
						GEN.workLayer({name:sig,display_number:2,clear_before:'yes'})
						GEN.COM("filter_reset,filter_name=popup")
						GEN.COM("filter_set,filter_name=popup,update_popup=no,feat_types=pad")
						GEN.COM("sel_ref_feat,layers="+sm+"_tmp1"+",use=filter,mode=touch,pads_as=shape,f_types=line\;pad\;surface\;arc\;text,polarity=positive\;negative,include_syms=,exclude_syms=")
						if(GEN.getSelectCount() > 0) {
							GEN.selCopyOther({dest:'layer_name',target_layer:sm+"_tmp5",invert:'yes',dx:0,dy:0,size:30})
						}
						GEN.workLayer({name:sm+"_tmp5",display_number:2,clear_before:'yes'})
						GEN.selContourize()
						GEN.PAUSE(1)
						GEN.selCopyOther({dest:'layer_name',target_layer:sm,invert:'yes',dx:0,dy:0,size:0})
						delLayer([sm+"_tmp5",sm+"_tmp1"]);
					}
					delLayer([sm+"_tmp4"]);
				}
			}
		})
	})


	// 保存 
	if(/yes/ig.test(par.auto_save)){GEN.checkInout({job:job,mode:"out"}); GEN.saveJob({ job: job });GEN.checkInout({job:job,mode:"in"});GEN.closeJob({job:job});} else {GEN.checkInout({job:job,mode:"in"})}
	if (mode === "aimdfm") {
		$.QDfm.updateRow({table: "pdm_aimdfm_task",data: {progress: 33.33},where: { id: $.task_id }});
		if (GEN.hasError()) { Status = 'error';resultData.push({ type: "error", title: "GEN错误!", detail: [{ desc: _.join(GEN.STATUS, "\n") }] });
			return {status: Status,result_data: resultData};
		} else { resultData.push({ type: "info", title: "操作完成, 请注意检查!" }); return {status: Status,result_data: resultData}; }
	}else { return "Done" }
} catch (e) {
	IKM.msg(_.join(GEN.STATUS, "\n"));IKM.msg(e);Status = 'error';
    resultData.push({type: "error", title: "脚本执行出错!", detail: [{desc: _.toString(e)}]});
    return (mode === "aimdfm") ? {status: Status, result_data: resultData} : "Error";
}


function delLayer(layers){
	if(!Array.isArray(layers)){ layers = [layers] };
	layers.forEach(function(v){
		if(GEN.isLayerExists({job:Job, layer:v})){GEN.deleteLayer({job:Job, layer:[v]})}
	})
}