=head
 NAME: ZWZ_Merge_Layer
 DESCRIPTION: 复合层铜皮整理
 PARAMETER:
	[
		{
			name : 'step_filter',
			type : 'LineEdit',
			title : 'step过滤',
			pack : {row:0,column:1},
			property:{tool_tip:'选择step时候的过滤器'},
		},
		{
			name : 'bak_layer_suf',
			type : 'LineEdit',
			title : '备份层后缀',
			pack : {row:0,column:1},
			property:{tool_tip:'去铜丝参数'},
		}
	]
 VERSION_HISTORY:
	V1.00 2020-10-30 Super
	   1.新版本
 HELP:
	<html><body bgcolor="#DDECFE">
		<font size="3" color="#003DB2"><p>功能简介</p></font>
		  <p> DFM优化 </p>
		  <br>
		<font size="3" color="#003DB2"><p>参数配置</p></font>
		<font color="#008000"><p> ● 无</p></font>
		<font size="3" color="#003DB2"><p>注意事项</p></font>
		  <p> ● 无 </p>
		  <br>
	</body></html>
  
=cut

use strict;
use utf8;
use Data::Dump 'dump';
my ($Job,$Step)=($JOB,undef);
my $Report = 'done';
my @work_layers;

$PAR->{bak_layer_suf} = $PAR->{bak_layer_suf} ? $PAR->{bak_layer_suf} : '++--merge+layer++';

try {
	###检查Genesis料号是否存在并打开
	show_loading("检查${Job}是否存在..",0,position=>'n');
	if (! $GEN->isJobExists(job=>$Job) ){
        $GUI->msgbox(-icon=>'error',-text=>"料号 $Job 在Genesis中不存在, 请检查!");
        return 'Error';
    }

	update_loading("正在打开料号 ${Job} ...",0,position=>'n');
	$GEN->openJob(job=>$Job) unless ($GEN->isJobOpen(job=>$Job));

	my @steps =  $GEN->getStepList(job=>$Job);
	if ( @steps == 0 ) {
		$GUI->msgbox(-icon=>'error',-text=>'在料号中没有Step存在,你将退出!');
		return 'Error';
	}
	elsif (@steps != 1){
		my $srep_filter = $PAR->{step_filter} ? $PAR->{step_filter} : '.*';
        my @tmp_steps = grep(/$srep_filter/,@steps);
		if ( @tmp_steps == 0 ) {
			$GUI->msgbox(-icon=>'error',-text=>'在料号中没有过滤器中的step存在,你将退出!');
			return 'Error';
		}
        elsif ( @tmp_steps == 1 ) {
            $Step = $tmp_steps[0];
        }
        else {
            $Step = $GUI->select_step(-title=>'请选择工作Step',
                                      -steplist=>\@tmp_steps,
                                      -selectmode=>'single');
            return 'Cancel' unless ($Step);            
        }
	}
    else {
        $Step = $steps[0];
    }

	##
	update_loading("过滤层别...",0,position=>'n');
	@work_layers = get_work_layer();
	return 'Cancel' if grep /^Cancel$/,@work_layers;

	###打开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->COM("disp_off");
	foreach my $layer (@work_layers){
		update_loading("$layer 复合层整理中...",0,position=>'n');
		next if ($GEN->isLayerEmpty(job=>$Job,step=>$Step,layer=>$layer));
		my $bak_layer = $layer.$PAR->{bak_layer_suf};
		my $dest_suffix = '__tl__';
		$GEN->createLayer(job=>$Job,layer=>$bak_layer,context=>'misc',type=>'document',delete_exists=>'yes');
		$GEN->affectedLayer(affected=>'yes',layer=>$layer,clear_before=>'yes');
		#1.分解复合层
		$GEN->COM('unmerge_layer',layer=>$layer,dest_suffix=>$dest_suffix,dest_max_layers=>1000);
		$GEN->selMoveOther(target_layer=>$bak_layer,invert=>'no');
		#2.获取复合层名
		my %matrix = $GEN->getMatrix(job=>$Job,type=>'hash');
		my $exp = $layer.$dest_suffix;
		my @merge_layer = grep(/($exp)/,sort {$matrix{$a}{row} <=> $matrix{$b}{row}}  keys %matrix);
		if(@merge_layer){
			foreach my $tmp_layer (@merge_layer){
				$GEN->affectedLayer(affected=>'yes',layer=>$tmp_layer,clear_before=>'yes');
				my $check = substr($tmp_layer,-1);
				if($check =~ /^p$/){
					$GEN->selMoveOther(target_layer=>$layer,invert=>'no');
					$GEN->affectedLayer(affected=>'yes',layer=>$layer,clear_before=>'yes');
					$GEN->selectByFilter(polarity=>'negative',profile=>'all');
					next unless ($GEN->getSelectCount());
					$GEN->selClearFeature();
					$GEN->selectByFilter(feat_types=>'surface',polarity=>'positive',profile=>'all');
					next unless ($GEN->getSelectCount());
					$GEN->selectByFilter(polarity=>'negative',profile=>'all');
					$GEN->selContourize() if ( $GEN->getSelectCount() > 0 );
				}else{
					$GEN->selMoveOther(target_layer=>$layer,invert=>'yes');
					$GEN->affectedLayer(affected=>'yes',layer=>$layer,clear_before=>'yes');
					$GEN->selectByFilter(feat_types=>'surface',polarity=>'positive',profile=>'all');
					next unless ($GEN->getSelectCount());
					$GEN->selectByFilter(polarity=>'negative',profile=>'all');
					$GEN->selContourize() if ( $GEN->getSelectCount() > 0 );
				}
			}
			$GEN->deleteLayer(job=>$Job,layer=>[@merge_layer]);
		}else{
			next;
		}
	}

	$GUI->msgbox(-icon=>'info',-text=>'脚本运行完成请仔细检查！');

    ###output and return status, if genesis error, it will output genesis error command
	unless ($GEN->{STATUS}){
		return $Report;
	}
	else{
		$GUI->msgbox(-icon=>'error',-text=>join("\n",@{$GEN->{STATUS}}));
		addFlowNotes(-notes=>"   Genesis Error:\n ".join("\n   ",@{$GEN->{STATUS}}));
		return 'Error';
	}
}

catch Error::Simple with {
	my $error = shift;
	$GUI->msgbox(-icon=>'error',-text=>$error);
	return 'Error';
}

finally{
	$GEN->clearLayers();
	$GEN->affectedLayer( mode=>'all',affected=>'no' );
	$GEN->COM("disp_on");
};



=head
	选择线路层
=cut
sub get_work_layer{	
	# 获取工作层
	my %matrix = $GEN->getMatrix(job=>$Job,type=>'hash');
	foreach my $layer (sort {$matrix{$a}{row} <=> $matrix{$b}{row}}  keys %matrix) {
		if(defined($matrix{$layer}{context}) and $matrix{$layer}{context} eq 'board' ){
			if(defined($matrix{$layer}{tl_type}) and ($matrix{$layer}{tl_type} eq 'outer'  or $matrix{$layer}{tl_type} eq 'inner')){
				push @work_layers,$layer;
			}			
		}
	}	
	
	my %tmp_matrix;
	foreach my $layer (@work_layers) {
		$tmp_matrix{$layer} = $matrix{$layer};
	}	
	
	if (@work_layers > 1) {
		@work_layers = $GUI->select_layer(
			-title=>'请选择工作层别',
			-layermatrix=>\%tmp_matrix,
			-selectmode => 'multiple');#single
		return 'Cancel' unless(@work_layers);
	}
	else {
		@work_layers = @work_layers;
	}
	return @work_layers;
}
