=head
 NAME: 
 DESCRIPTION: 
 PARAMETER:
	[
		{
			name : 'step_filter',
			title : '工作step',
			type : 'LineEdit',
			property : {tool_tip : '过滤Step名称'},
		},
		{
			name : 'units',
			title : '单位',
			type : 'RadioBox',
			property : {
				size_policy:'Expanding,Fixed',
				item_list:[
					{name:'inch',text:'INCH'},
					{name:'mm',text:'MM'},
				],
				tool_tip:'工作单位，未设定，默认为INCH'
			},
			pack : {row:1,column:1},
		},
		{
			name : 'cover_layer_suffix',
			title : '文字套层后缀',
			type : 'LineEdit',
			property : {tool_tip : ''},
		},
		{
			name : 'ss_to_sm',
			title : '文字距离阻焊',
			type : 'LineEdit',
			property : {tool_tip : ''},
		},
		{
			name : 'ss_to_smd',
			title : '文字距离SMD',
			type : 'LineEdit',
			property : {tool_tip : ''},
		},
		{
			name : 'ss_to_bga',
			title : '文字距离bga',
			type : 'LineEdit',
			property : {tool_tip : ''},
		},
		{
			name : 'select_lyr',
			title : '选择层别',
			type : 'RadioBox',
			property : {
				size_policy:'Expanding,Fixed',
				item_list:[
					{name:'yes',text:'Yes'},
					{name:'no',text:'No'},
				],
				tool_tip:'未设定，默认为Yes'
			},
			pack : {row:1,column:1},
		},
		{
			name : 'save_job',
			title : '保存料号',
			type : 'RadioBox',
			property : {
				size_policy:'Expanding,Fixed',
				item_list:[
					{name:'yes',text:'Yes'},
					{name:'no',text:'No'},
				],
				tool_tip:'脚本结束后自动保存料号，未设定，默认为No'
			},
			pack : {row:1,column:1},
		}
	]
 VERSION_HISTORY:
	V1.00 2019-05-24 Shyer
		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>
		<font color="#008000"><p> ● </p></font>
		<p> </p>
		
		<br>
  </body></html>
=cut

use strict;
#my ($JOB,$GEN,$GUI,$DB,$JOB_ID,$PAR,$APP,$MW);
use utf8;
use Encode;
use Data::Dump 'dump';
my $Return = 'done';
my ($Job,$Step) = ($JOB,undef);
$PAR->{units} = 'inch' unless $PAR->{units};
$PAR->{del_backup} = 'no' unless $PAR->{del_backup};
$PAR->{save_job} = 'no' unless $PAR->{save_job};
$PAR->{select_lyr} = 'yes'  unless($PAR->{select_lyr});
$PAR->{cover_layer_suffix} = '_cover_tl+'  unless($PAR->{cover_layer_suffix});
unless($PAR->{outline_size}){
    $PAR->{outline_size}  =  $PAR->{units} eq 'inch' ? 16 : 200;
}
my $outline = 'gko';
my %matrix;

try {
	show_loading("判断是否选择料号..",0,position=>'n');
	unless( $Job){
		$GUI->msgbox(-icon=>'error',-text=>"请先选择料号后再执行脚本!");
        return 'Cancel';
	}
	
	##
	update_loading("检查料号${Job}是否存在 ，请稍候..",0,position=>'n');
	unless ( $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));
	
	##
	update_loading("过滤工作step...",0,position=>'n');
	my $ans_step = get_work_step();
	return 'Cancel' if $ans_step eq 'Cancel';
	
	##
	update_loading("过滤层别...",0,position=>'n');
	my @work_layers = get_work_layer();
	return 'Cancel' if $work_layers[0] eq 'Cancel';
    
    my %info = $GUI->show_form(
		-title => '请手动匹配以下信息',
		-showcheck => 1,-gen=>$GEN,
		-defaultsize=>[500,250],
		-items=>[
			{
				name => 'ss_to_sm',
				label => '文字距离阻焊(单边)',
				type => 'number',
				value=>$PAR->{ss_to_sm},
                units=>$PAR->{units} eq 'inch' ? 'mil' : 'um',
			},
			{
				name => 'ss_to_smd',
				label => '文字距离SMD(单边)',
				type => 'number',
				value=>$PAR->{ss_to_smd},
                units=>$PAR->{units} eq 'inch' ? 'mil' : 'um',
			},
			{
				name => 'ss_to_bga',
				label => '文字距离BGA(单边)',
				type => 'number',
				value=>$PAR->{ss_to_bga},
                units=>$PAR->{units} eq 'inch' ? 'mil' : 'um',
			},
		]
	);
	return 'Cancel' unless %info;
	#
	###
	update_loading("打开${Step} ，请稍候..",0,position=>'n');
	$GEN->openStep(job=>$Job,name=>$Step);
	$GEN->clearLayers();
	$GEN->affectedLayer( mode=>'all',affected=>'no' );
	$GEN->units( type=>$PAR->{units} );
	$GEN->zoomHome();
	update_loading("正在制作文字套层 ，请稍候..",0,position=>'n');
    foreach my $layer (@work_layers) {
        my $cover_lyr = $layer.$PAR->{cover_layer_suffix} ;
        my ($sm,$outer) ;
        if ($matrix{$layer}{side} eq 'top') {
            $sm = 'gts';
            $outer = 'gtl';
            $GEN->createLayer(job=>$Job,layer=>$cover_lyr,context=>'board',type=>'document',before=>$layer,delete_exists=>'yes');
        }else{
            $sm = 'gbs';
            $outer = 'gbl';
            $GEN->createLayer(job=>$Job,layer=>$cover_lyr,context=>'board',type=>'document',after=>$layer,delete_exists=>'yes');
        }
        if ( $GEN->isLayerExists(job=>$Job,layer=>$sm) ) {
            $GEN->affectedLayer(affected=>'yes',layer=>[$sm],clear_before=>'yes');
            $GEN->selectByFilter(
                       polarity=>'positive',
                       profile=>'all',
            );
            $GEN->selCopyOther(dest=>'layer_name',target_layer=>$cover_lyr,invert=>'no',size=>2*$info{ss_to_sm});
        }
        if ( $GEN->isLayerExists(job=>$Job,layer=>$outer) ) {
            $GEN->affectedLayer(affected=>'yes',layer=>[$outer],clear_before=>'yes');
            $GEN->selectByFilter(
                       attribute=>['.smd'],
                       profile=>'all',
            );
            if ( $GEN->getSelectCount() > 0 ){
                $GEN->selCopyOther(dest=>'layer_name',target_layer=>$cover_lyr,invert=>'no',size=>2*$info{ss_to_smd});
            }
            $GEN->selectByFilter(
                       attribute=>['.bga'],
                       profile=>'all',
            );
            if ( $GEN->getSelectCount() > 0 ){
                $GEN->selCopyOther(dest=>'layer_name',target_layer=>$cover_lyr,invert=>'no',size=>2*$info{ss_to_bga});
            }
        }
        if ( $GEN->isLayerExists(job=>$Job,layer=>$outline) ) {
            my $outline_tmp = $outline.'_tmp_tl';
            $GEN->copyLayer(source_job=>$Job,
                            source_step=>$Step,
                            source_layer=>$outline,
                            dest_layer=>$outline_tmp,
                            mode=>'replace', #append/replace
                            invert=>'no') ;#|'yes'
            
            $GEN->affectedLayer(affected=>'yes',layer=>[$outline_tmp],clear_before=>'yes');
            $GEN->selectByFilter(
                        feat_types=>'line\;arc',
                        polarity=>'positive',
                        profile=>'all',
            );
            $GEN->selChangeSym(symbol=>'r'.$PAR->{outline_size})  if ( $GEN->getSelectCount() > 0 );
            $GEN->copyLayer(source_job=>$Job,
                            source_step=>$Step,
                            source_layer=>$outline_tmp,
                            dest_layer=>$cover_lyr,
                            mode=>'append', #append/replace
                            invert=>'no') ;#|'yes'      
            $GEN->deleteLayer(job=>$Job,layer=>[$outline_tmp],step=>$Step);
        }
    }
	
	$GEN->clearLayers();
	$GEN->affectedLayer( mode=>'all',affected=>'no' );
	update_loading("程序运行完成，请检查运行结果..",0,position=>'n');
	sleep(2);
	hide_loading();
	
	##保存料号
	if( $PAR->{save_job} =~ /yes/i ){
		show_loading("$Job 正在保存料号，请稍候...",0,position=>'n');
		$GEN->checkInout(job=>$Job,mode=>'out');
		$GEN->saveJob(job=>$Job);
		hide_loading();
	}
	

	unless ($GEN->{STATUS}){
		return $Return;
	}
	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 = encode("utf8",shift);
	$GUI->msgbox(-icon=>'error',-text=>$error);
	return 'Error';
}
finally{
	
};

######################################################################################
sub get_work_step {
    my @steps =  $GEN->getStepList(job=>$Job);
	if ( @steps == 0 ) {
		$GUI->msgbox(-icon=>'error',-text=>'在料号中没有Step存在,你将退出!');
		return 'Cancel';
	}
	elsif (@steps != 0){
		my @tmp_steps = grep(/$PAR->{step_filter}/,@steps);
		if ( @tmp_steps == 0 ) {
		   $GUI->msgbox(-icon=>'warning',-text=>'根据脚本参数过滤出来的step不存在，请检查资料或者脚本参数配置！');
		   return 'Cancel';
		}
		elsif (@tmp_steps == 1) {
			$Step = $tmp_steps[0];
		}
        else {
            $Step = $GUI->select_step(-title=>'请选择工作 Step',
                                      -steplist=>[@tmp_steps],
									  -default=>[$tmp_steps[0]],
									  -gen=>$GEN,
                                      -selectmode=>'single');
            return 'Cancel' unless ($Step);            
        }
	}
	return undef;
}

sub isChecklistExist{
    my %par = @_ ;
    my @chklists = $GEN->getChecklist(job=>$par{job},step=>$par{step});
    if(grep /^$par{checkklist}$/,@chklists){
        return 1;
    }
    else{
        return 0;
    }
}
sub get_work_layer{
	my @work_layers;
	# 获取工作层
	%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 'silk_screen' ){
				push @work_layers,$layer;
			}
		}
	}
	
	#
	my %tmp_matrix;
	foreach my $layer (@work_layers) {
		$tmp_matrix{$layer} = $matrix{$layer};
	}	
	##
	
	if (@work_layers > 1 and $PAR->{select_lyr} eq 'yes') {
		@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;
}


__END__
