/*
NAME: 
DESCRIPTION: ;
PARAMETER:
    [
		{
			name : 'step',
			title : 'step',
			type : 'LineEdit',
			property : {tool_tip : '目标step,默认是orig'},
        },
        {
			name : 'line_number_min',
			type : 'LineEdit',
			title : 'line转铜最小数量',
			pack : {row:0,column:1},
			property:{tool_tip:'line转铜最小数量'},
		},
		{
			name : 'bak_layer_suf',
			type : 'LineEdit',
			title : '备份层后缀',
			pack : {row:0,column:1},
			property:{tool_tip:'去铜丝参数'},
        },
        {
			name : 'layer_type',
			title : '工作层',
			type : 'ComboBox',
			property : {
			    size_policy:'Expanding,Fixed',
			    item_list:[
			        {name:'outer',text:'outer'},
			        {name:'inner_negative',text:'inner_negative'},
			        {name:'inner_positive',text:'inner_positive'}
			    ],
			    tool_tip:'分析模式必须设置，未设定则退出'
			},
			pack : {row:1,column:1},
		},
		{
            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: "edit",
    line_number_min:"max",
    auto_save: "No",
    bak_layer_suf:"++-bak-suface++",
	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})     // 工作step列表
	stepList = stepList.filter(function(step){
		var reg = new RegExp(par.step,"ig")
		return reg.test(step)
	})
    var layer_type = par.layer_type;
	var matrix = GEN.getMatrix({job:job})
	var worklayers = Object.keys(matrix).filter(function(layer) {  // 找工作层
		var layer_info = matrix[layer];
		var tmp_layer_type = /inner_negative/.test(layer_type) ? "power_ground" : "signal";
		var side_reg = /out/.test(layer_type)? /top|bot/ : /inner/;
		return layer_info.context == "board" && layer_info.layer_type == tmp_layer_type && side_reg.test(layer_info.side) 
	})
	if(worklayers.length == 0) { throw "没有找到工作层" + layer_type}
	stepList.forEach(function(step) {
        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: "inch" }); //单位初始化
        GEN.zoomHome(); //窗口显示回到原始位置
		GEN.selClearFeature()
        GEN.COM("disp_off")
        worklayers.forEach(function(layer){
            var feat = GEN.getFeatures({job:job,step:step,layer:layer,options:'break_sr'});
            if(feat.length){
                var line_info = {} 
                feat.filter(function(v){
                    if(/line|arc/.test(v.type)){
                        line_info[v.symbol] = line_info[v.symbol] ? ++line_info[v.symbol] : 1
                    } 
                })
                if(Object.keys(line_info).length){
                    var tmp = Object.keys(line_info).sort(function(a,b){return line_info[b] - line_info[a]})   
                    // 创建铜皮层
                    var line_suface = 'tl++tmp+line+suf+++';
                    var line_chek = 'tl++check+line++type++';
                    GEN.createLayer({job:job,layer:line_suface,context:'misc',type:'document',delete_exists:'yes'});
                    GEN.createLayer({job:job,layer:line_chek,context:'misc',type:'document',delete_exists:'yes'});
                    // 备份层
                    var bak_layer = layer + par.bak_layer_suf;
                    GEN.createLayer({job:job,layer:bak_layer,context:'misc',type:'document',delete_exists:'yes'});
                    GEN.affectedLayer({affected:'yes',layer:layer,clear_before:'yes'});
                    GEN.selCopyOther({target_layer:bak_layer,invert:'no'});
        
                    if(par.line_number_min == 'max'){
                        select_line_suface({job:job,step:step,symbol_data:tmp[0],layer:layer,surface:line_suface,line_check:line_chek});
                    }else{
                        tmp.forEach(function(data){
                            if(line_info[data] >= par.line_number_min){
                                select_line_suface({job:job,step:step,symbol_data:data,layer:layer,surface:line_suface,line_check:line_chek});
                            }
                        })
                    }
            
                    if(!GEN.isLayerEmpty({job:job,step:step,layer:line_chek})){
                        GEN.COM("disp_on");
                        GEN.clearLayers();
                        GEN.affectedLayer( {mode:'all',affected:'no'} );
                        GEN.workLayer({name:line_chek,display_number:1,clear_before:'yes'});
                        GEN.displayLayer({name:line_suface,number:2});
                        GEN.PAUSE("Please check line type!");
                        GEN.COM("disp_off")
                        if ( GEN.getSelectCount() > 0 ){GEN.selMoveOther({target_layer:line_suface,invert:'no'}) };
                        GEN.selMoveOther({target_layer:layer,invert:'no'});
                        GEN.clearLayers();
                        GEN.deleteLayer({job:job,layer:[line_chek]});
                        
                    }else{
                        GEN.deleteLayer({job:job,layer:[line_chek]});
                    }
            
                    if(! GEN.isLayerEmpty({job:job,step:step,layer:line_suface})){
                        GEN.COM("disp_on");
                        GEN.clearLayers();
                        GEN.affectedLayer( {mode:'all',affected:'no'} );
                        GEN.workLayer({name:line_suface,display_number:1,clear_before:'yes'});
                        GEN.displayLayer({name:layer,number:2});
                        GEN.PAUSE("Please check !");
                        GEN.COM("disp_off");
                        GEN.selContourize();
                        GEN.selMoveOther({target_layer:layer,invert:'no'});
                        GEN.clearLayers();
                        GEN.deleteLayer({job:job,layer:[line_suface]});
                    }else{
                        GEN.deleteLayer({job:job,layer:[line_suface]});
                        GEN.copyLayer({source_job:job,source_step:step,source_layer:bak_layer,dest_layer:layer,mode:'replace',invert:'no'}) ;
                    }
                
                }
            }
        })
        GEN.units({ type: par.units }); //单位初始化

	})
    





	// 保存 
	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 select_line_suface(props){
    var job = props.job
    var step = props.step
	GEN.affectedLayer({affected:'yes',layer:props.layer,clear_before:'yes'});
	// 挑选最多D码的线
	var line_tmp = '++-+tl+tmp++line';
	GEN.createLayer({job:job,layer:line_tmp,context:'misc',type:'document',delete_exists:'yes'});
	GEN.selectByFilter({feat_types:'line\;arc',polarity:'positive',include_syms:props.symbol_data,profile:'all'});
	if ( GEN.getSelectCount() > 0 ){GEN.selMoveOther({target_layer:line_tmp,invert:'no'}) };

	// 挑选PAD
	var pad_tmp = '++-+tl+tmp++pad';
	GEN.createLayer({job:job,layer:pad_tmp,context:'misc',type:'document',delete_exists:'yes'});
	GEN.selectByFilter({feat_types:'pad',polarity:'positive',profile:'all'});
	GEN.selCopyOther({target_layer:pad_tmp,invert:'no',size:0});
	// 删除cover的pad
	var line_tmp2 = '++-+tl+tmp++line2';
	GEN.createLayer({job:job,layer:line_tmp2,context:'misc',type:'document',delete_exists:'yes'});
	GEN.affectedLayer({affected:'yes',layer:line_tmp,clear_before:'yes'});
	GEN.selCopyOther({target_layer:line_tmp2,invert:'no'});
	GEN.affectedLayer({affected:'yes',layer:line_tmp2,clear_before:'yes'});
	GEN.selContourize();
	GEN.affectedLayer({affected:'yes',layer:pad_tmp,clear_before:'yes'});
	GEN.selRefFeat({layers:line_tmp2,use:'filter',mode:'cover'});
	if ( GEN.getSelectCount() > 0 ){GEN.selDelete() };
	GEN.COM('truncate_layer', {layer :line_tmp2});

	// 挑选与pad连接的线
	GEN.affectedLayer({affected:'yes',layer:line_tmp,clear_before:'yes'});
	GEN.selRefFeat({layers:pad_tmp,use:'filter',mode:'touch'});
	var touch_pad_line = '++-+touch++pad++line';
	if ( GEN.getSelectCount() > 0 ){
		GEN.createLayer({job:job,layer:touch_pad_line,context:'misc',type:'document',delete_exists:'yes'});
		GEN.selMoveOther({target_layer:touch_pad_line,invert:'no'});
	}

	// 挑选单独的线移回工作层
	GEN.affectedLayer({affected:'yes',layer:line_tmp,clear_before:'yes'});
	GEN.selCopyOther({target_layer:line_tmp2,invert:'no'});
	GEN.affectedLayer({affected:'yes',layer:line_tmp2,clear_before:'yes'});
	GEN.selContourize();
	var size = /r(.*)/.exec(props.symbol_data)[1];
	GEN.COM('sel_resize',{size:-(size+0.05),corner_ctl:'no'});
	GEN.COM("sel_clean_surface,accuracy=0.25,clean_size=3,clean_mode=x_and_y,max_fold_len=0");
	GEN.COM('sel_resize',{size:size+0.05,corner_ctl:'no'});
	GEN.affectedLayer({affected:'yes',layer:line_tmp,clear_before:'yes'});
	GEN.selRefFeat({layers:line_tmp2,use:'filter',mode:'disjoint'});
	if ( GEN.getSelectCount() > 0 ){GEN.selMoveOther({target_layer:props.layer,invert:'no'})} ;

	if(GEN.isLayerExists({job:job,layer:touch_pad_line})){
		GEN.affectedLayer({affected:'yes',layer:touch_pad_line,clear_before:'yes'});
		var tmp_data = '+++-touch+pad+line+check';
		GEN.createLayer({job:job,layer:tmp_data,context:'misc',type:'document',delete_exists:'yes'});
		GEN.selCopyOther({target_layer:tmp_data,invert:'no',size:0});
		GEN.selContourize();
		// 不与铜皮相连与PAD相连的移回线路层
		GEN.selRefFeat({layers:line_tmp,use:'filter',mode:'disjoint'});
		if ( GEN.getSelectCount() > 0 ){
			var tmp_layer = '++++-tl++line+touch--+';
			GEN.createLayer({job:job,layer:tmp_layer,context:'misc',type:'document',delete_exists:'yes'});
			GEN.selMoveOther({target_layer:tmp_layer,invert:'no'});
			GEN.affectedLayer({affected:'yes',layer:tmp_data,clear_before:'yes'});
			GEN.selRefFeat({layers:tmp_layer,use:'filter',mode:'touch'});
			GEN.selMoveOther({target_layer:props.layer,invert:'no'});
			GEN.deleteLayer({job:job,layer:[tmp_layer]});
		}
		GEN.deleteLayer({job:job,layer:[touch_pad_line]});

		// 与铜皮和PAD相连
		var pad_tmp2 = '++pad+++tl++tmp';
		GEN.affectedLayer({affected:'yes',layer:pad_tmp,clear_before:'yes'});
		GEN.selRefFeat({layers:tmp_data,use:'filter',mode:'touch'});
		if ( GEN.getSelectCount() > 0 ){
			GEN.createLayer({job:job,layer:pad_tmp2,context:'misc',type:'document',delete_exists:'yes'});
			GEN.selMoveOther({target_layer:pad_tmp2,invert:'no'});
			GEN.COM('truncate_layer', {layer :pad_tmp});
			var size = props.symbol_data.slice[1] - 0;
			var feat = GEN.getFeatures({job:job,step:step,layer:pad_tmp2});
            var idex = 1;
            feat.forEach(function(data){
                var pad_size;
				if (/^s(\d.*)/.test(data.symbol)) {
					pad_size = RegExp.$1;
				}else if(/^r(\d.*)/.test(data.symbol)){
					pad_size = RegExp.$1;
				}else if(/^rect(\d.*)x(\d.*)/.test(data.symbol)){
					pad_size = RegExp.$1 > RegExp.$2 ? RegExp.$2 : RegExp.$1;
				}else if(/^oval(\d.*)x(\d.*)/.test(data.symbol)){
					pad_size = RegExp.$1 > RegExp.$2 ? RegExp.$2 : RegExp.$1;
				}
				GEN.affectedLayer({affected:'yes',layer:pad_tmp2,clear_before:'yes'});
				GEN.COM('sel_layer_feat',{operation:'select',layer:pad_tmp2,index:idex});
				GEN.selMoveOther({target_layer:pad_tmp,invert:'no',dx:0,dy:0,size:0});
				GEN.affectedLayer({affected:'yes',layer:$tmp_data,clear_before:'yes'});
				GEN.selRefFeat({layers:pad_tmp,use:'filter',mode:'touch'});
				var number = GEN.getSelectCount();
				if(number > 0){
					if(number > 4){
						if(number*size / pad_size > 0.5 ){
							GEN.selMoveOther({target_layer:line_tmp,invert:'no'});
						}else{
							GEN.selMoveOther({target_layer:props.line_check,invert:'no'});
						}
					}else{
						// 4根以下算单根线的宽度
						if(size / pad_size > 0.5 ){
							GEN.selMoveOther({target_layer:line_tmp,invert:'no'});
						}else{
							GEN.selMoveOther({target_layer:props.line_check,invert:'no'});
						}
					}
				}
				idex++;
            })
			
			GEN.deleteLayer({job:job,layer:[pad_tmp2]});
		}
		GEN.deleteLayer({job:job,layer:[tmp_data]});
	}
	GEN.deleteLayer({job:job,layer:[pad_tmp,line_tmp2]});
	GEN.affectedLayer({affected:'yes',layer:line_tmp,clear_before:'yes'});
	if(GEN.isLayerExists({job:job,layer:props.surface})){
		GEN.selMoveOther({target_layer:props.surface,invert:'no'});
		GEN.deleteLayer({job:job,layer:[line_tmp]});
	}
}