=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 : 'silk_suffix',
			title : '分离的文字层后缀',
			type : 'LineEdit',
			property : {tool_tip : ''},
		},
		{
			name : 'text_height',
			title : '文字最大高度',
			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 : 'bk_suffix',
			title : '备份层后缀',
			type : 'LineEdit',
			property : {tool_tip : ''},
		},
		{
			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;
}
unless($PAR->{text_height}){
    $PAR->{text_height}  =  $PAR->{units} eq 'inch' ? 0.06 : 1.524;
}

$PAR->{cover_layer_suffix} = '_cover_tl+'  unless($PAR->{cover_layer_suffix});


doScript("SHT_FUC");


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=>'type',
                type=>'radio',
                label=>'类型',
                value=>'separate',
                property=>{
                    tl_columns => 2,  
                    tl_list => [separate => '字框分离', change=>'字框切换'],   
                },
                validate_func=>sub{
                    my %par = @_;
                    return {} if($par{mode} eq 'save');
                    if ($par{value} eq 'separate') {
                        $par{formpanel}->set_item_visible(text_height=>1);
                    }else{
                        $par{formpanel}->set_item_visible(text_height=>0);
                    }
                    return {};
                }
            },
			{
				name => 'text_height',
				label => '文字最大高度',
				type => 'number',
				value=>$PAR->{text_height}*1000,
                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();
    my $layer_count = $IKM->get_jobinfo(-jobname=>$Job,
                                 -jobcategory=>'work',
                                 -jobinfo=>'layer_count');
    $GEN->COM('disp_off');
    if ($info{type} eq 'separate') {
        foreach my $layer (@work_layers) {
            update_loading("正在$layer 制作分离文字 ，请稍候..",0,position=>'n');
            ##备份文字层
            my $bk = $layer.$PAR->{bk_suffix};
            $GEN->copyLayer(source_job=>$Job,
                            source_step=>$Step,
                            source_layer=>$layer,
                            dest_layer=>$bk,
                            mode=>'replace', #append/replace
                            invert=>'no') ;#|'yes'
            
            ##分离出的文字层
            my $ss_text = $layer.$PAR->{silk_suffix};
            if ($matrix{$layer}{side} eq 'top') {
                $GEN->createLayer(job=>$Job,layer=>$ss_text,context=>'board',type=>'document',before=>$layer,delete_exists=>'yes');
            }else{
                $GEN->createLayer(job=>$Job,layer=>$ss_text,context=>'board',type=>'document',after=>$layer,delete_exists=>'yes');
            }
            
            ##开始分离文字
            $GEN->affectedLayer(affected=>'yes',layer=>[$layer],clear_before=>'yes');
            #$GEN->COM("filter_reset,filter_name=popup");
            #$GEN->COM("reset_filter_criteria,filter_name=,criteria=all");
            $GEN->COM("filter_reset,filter_name=popup");
    
            $GEN->selectByFilter(
                       feat_types=>'line\;arc',
                       polarity=>'positive',
                       profile=>'all',
            );
            if ( $GEN->getSelectCount() > 0 ){
                my $ss_line_arc = $layer.'_line_arc_tl_script';
                $GEN->createLayer(job=>$Job,layer=>$ss_line_arc,delete_exists=>'yes');
                $GEN->selCopyOther(target_layer=>$ss_line_arc,invert=>'no');
                
                $GEN->affectedLayer(affected=>'yes',layer=>[$ss_line_arc],clear_before=>'yes');
                $GEN->selChangeSym(symbol=>'r0.2');
                #$GEN->COM('filter_reset',filter_name=>'popup');
                #$GEN->COM("reset_filter_criteria,filter_name=,criteria=all");
                $GEN->COM("filter_reset,filter_name=popup");
                $GEN->selectByFilter(
                           feat_types=>'line',
                           polarity=>'positive',
                           profile=>'all',
                );
    
                ##将直线固定角度分离去除
                my $ss_line = $layer.'_line_tl_script';
                if ( $GEN->getSelectCount() > 0 ){
                    $GEN->createLayer(job=>$Job,layer=>$ss_line,delete_exists=>'yes');
                    $GEN->selCopyOther(target_layer=>$ss_line,invert=>'no');
                    $GEN->affectedLayer(affected=>'yes',layer=>[$ss_line],clear_before=>'yes');
                    $GEN->COM("filter_reset,filter_name=popup");
    
                    my @angle;
                    my $tol = 0.2;
					if($GEN->{GEN_TYPE} eq 'genesis'){
						@angle = (-180,-135,-90,-45,0,45,90,135);
					}else{
						@angle = (0,45,90,135,180,225,270,315);
					}
					
                    foreach my $angle (@angle) {
						if($GEN->{GEN_TYPE} eq 'genesis'){
							my $min_angle = ($angle-$tol < -180) ? -180 : $angle-$tol;
							my $max_angle = ($angle+$tol > 180) ? 180 : $angle+$tol;
                            $GEN->COM('filter_set',filter_name=>'popup',update_popup=>'yes',slot=>'line',slot_by=>'angle',min_angle=>$min_angle,max_angle=>$max_angle);
						}else{
                            $GEN->COM('set_filter_angle',direction=>'ccw',max_angle=>$angle+$tol,min_angle=>$angle-$tol,slot=>'lines');
                            $GEN->COM("adv_filter_set,ccw_rotations=,filter_name=popup,mirror=any,bound_box=no,active=yes,srf_values=no,srf_area=no,limit_box=no");
						}
                        $GEN->COM("filter_area_strt");
                        $GEN->COM("filter_area_end,filter_name=popup,operation=select");    
                    }
                    $GEN->selDelete() if ( $GEN->getSelectCount() > 0 );
                }

                next if(!($GEN->isLayerExists(job=>$Job,layer=>$ss_line) and (!$GEN->isLayerEmpty( job=>$Job,step=>$Step,layer=>$ss_line))));
               
                ###利用制作的套层
                my $cover_lyr = $layer.$PAR->{cover_layer_suffix};
                $GEN->affectedLayer(affected=>'yes',layer=>[$cover_lyr],clear_before=>'yes');
                $GEN->COM("filter_reset,filter_name=popup");
                $GEN->COM("filter_set,filter_name=popup,update_popup=no,include_syms=r*");
                $GEN->COM("filter_set,filter_name=popup,update_popup=no,exclude_syms=rect*");
                $GEN->COM("filter_area_strt");
                $GEN->COM("filter_area_end,filter_name=popup,layer=,operation=select,inside_area=no,intersect_area=no,area_type=none");
                $GEN->COM("filter_reset,filter_name=popup");
                $GEN->COM("sel_reverse");
                my $cover_lyr_2 = $cover_lyr.'_tmp_tl';
				
                if ( $GEN->getSelectCount() > 0 ){
                    $GEN->createLayer(job=>$Job,layer=>$cover_lyr_2,delete_exists=>'yes');
                    $GEN->selCopyOther(target_layer=>$cover_lyr_2,invert=>'no');
    
                }
                $GEN->affectedLayer(affected=>'yes',layer=>[$ss_line_arc],clear_before=>'yes');
                $GEN->selContourize();
				
				
                if($GEN->{GEN_TYPE} eq 'incam'){
                    $GEN->COM("reset_filter_criteria,filter_name=,criteria=all");
                }else{
                    $GEN->COM("filter_atr_reset,filter_name=ref_select");
                }
                $GEN->COM("sel_ref_feat,pads_as=shape,mode=touch,exclude_syms=,include_syms=,use=filter,f_types=line\;pad\;surface\;arc\;text,polarity=positive\;negative,layers=$ss_line");
                my $layer_tmp1 = $layer.'_tmp1_tl';

                if ( $GEN->getSelectCount() > 0 ){
                    $GEN->createLayer(job=>$Job,layer=>$layer_tmp1,delete_exists=>'yes');
                    $GEN->selMoveOther(target_layer=>$layer_tmp1,invert=>'no');
                }
				
                if($GEN->{GEN_TYPE} eq 'incam'){
                    $GEN->COM("reset_filter_criteria,filter_name=,criteria=all");
                }else{
                    $GEN->COM("filter_atr_reset,filter_name=ref_select");
                }
                $GEN->COM("sel_ref_feat,pads_as=shape,mode=touch,exclude_syms=,include_syms=,use=filter,f_types=line\;pad\;surface\;arc\;text,polarity=positive\;negative,layers=$cover_lyr_2");
    
                my $layer_tmp2 = $layer.'_tmp2_tl';
                if ( $GEN->getSelectCount() > 0 ){
                    $GEN->createLayer(job=>$Job,layer=>$layer_tmp2,delete_exists=>'yes');
                    $GEN->selCopyOther(target_layer=>$layer_tmp2,invert=>'no');
                }
                
                $GEN->COM("sel_clean_surface,max_fold_len=0,clean_size=$info{text_height},clean_mode=x_and_y,accuracy=0");
				if ($GEN->isLayerExists(job=>$Job,layer=>"$layer_tmp2")) {
					$GEN->affectedLayer(affected=>'yes',layer=>[$layer_tmp2],clear_before=>'yes');
					if($GEN->{GEN_TYPE} eq 'incam'){
						$GEN->COM("reset_filter_criteria,filter_name=,criteria=all");
					}else{
						$GEN->COM("filter_atr_reset,filter_name=ref_select");
					}
					$GEN->COM("sel_ref_feat,pads_as=shape,mode=disjoint,exclude_syms=,include_syms=,use=filter,f_types=line\;pad\;surface\;arc\;text,polarity=positive\;negative,layers=$ss_line_arc");
					
		
					if ( $GEN->getSelectCount() > 0 ){
						$GEN->selMoveOther(target_layer=>$layer_tmp1,invert=>'no');
					}	
				}

				if ($GEN->isLayerExists(job=>$Job,layer=>"$layer_tmp1")) {
					$GEN->affectedLayer(affected=>'yes',layer=>[$layer_tmp1],clear_before=>'yes');
					if($GEN->{GEN_TYPE} eq 'incam'){
						$GEN->COM("reset_filter_criteria,filter_name=,criteria=all");
					}else{
						$GEN->COM("filter_atr_reset,filter_name=ref_select");
					}
					$GEN->COM("sel_ref_feat,pads_as=shape,mode=touch,exclude_syms=,include_syms=,use=filter,f_types=line\;pad\;surface\;arc\;text,polarity=negative,layers=$layer");
					$GEN->selDelete() if ( $GEN->getSelectCount() > 0 );
					
					$GEN->affectedLayer(affected=>'yes',layer=>[$layer],clear_before=>'yes');
					if($GEN->{GEN_TYPE} eq 'incam'){
						$GEN->COM("reset_filter_criteria,filter_name=,criteria=all");
					}else{
						$GEN->COM("filter_atr_reset,filter_name=ref_select");
					}
					$GEN->COM("sel_ref_feat,pads_as=shape,mode=touch,exclude_syms=,include_syms=,use=filter,f_types=line\;pad\;surface\;arc\;text,polarity=positive\;negative,layers=$layer_tmp1");
				   
		
					if ( $GEN->getSelectCount() > 0 ){
						$GEN->selMoveOther(target_layer=>$ss_text,invert=>'no');
					}
					
				}

                ##将文字属性挑选
                $GEN->COM("filter_reset,filter_name=popup");
                $GEN->selectByFilter(
                    feat_types=>'text',
                );
                if ( $GEN->getSelectCount() > 0 ){
                    $GEN->selMoveOther(target_layer=>$ss_text,invert=>'no');
                }
                _deleteLayer(layer=>[$ss_line_arc,$ss_line,$cover_lyr_2,$layer_tmp1,$layer_tmp2]);
            }
        }   
    }
    $GEN->COM('disp_on');
    ##字框切换  ## @work_layers
    my $work_layer;
    my $ref_layer;
    my $flag = 0;
    foreach my $layer (@work_layers) {
        $work_layer = $layer;
        $ref_layer = $layer.$PAR->{silk_suffix};
        if ( $GEN->isLayerExists(job=>$Job,layer=>$ref_layer) ){
            $flag = 1;
            last;
        }
    }
    if ($flag) {
        $GEN->workLayer(name=>$work_layer,display_number=>1,clear_before=>'yes');
        while (1) {
			LOOP:
            $GEN->COM('disp_on');

            while(1){
				$work_layer = $GEN->getWorkLayer();
				last  if (grep($_ eq $work_layer ,@work_layers) or grep($_.$PAR->{silk_suffix} eq $work_layer ,@work_layers));
				update_loading("请选择一个文字层或者文字框层设为工作层",0,position=>'n');
				my $ans = $GEN->PAUSE('Please Set Work Layer');
				return 'Cancel' unless $ans eq 'OK';
			}
            
            ##给出默认移动层
            if (grep($_ eq $work_layer ,@work_layers)) {
               $ref_layer = $work_layer.$PAR->{silk_suffix};
            }elsif(grep($_.$PAR->{silk_suffix} eq $work_layer ,@work_layers)){
                $ref_layer = $work_layer;
                $ref_layer =~ s/\Q$PAR->{silk_suffix}\E$//;
            }
            
            if (! $GEN->isLayerExists(job=>$Job,layer=>$ref_layer) ){
                $GUI->msgbox(-icon=>'warning',-text=>"没有找到对应层$ref_layer ，请重新选择工作层！");
                goto LOOP;
            }
            $GEN->workLayer(name=>$work_layer,display_number=>1,clear_before=>'yes');
            $GEN->displayLayer(name=>$ref_layer,number=>2);

            update_loading("请选择需移动的文字或者的文字框，不需制作了请【左键框选空白处】",0,position=>'n');
            my %tmp_con;
            %tmp_con = $GEN->MOUSE(type=>'r',text=>"Please Select");
			$work_layer = $GEN->getWorkLayer();
            $GEN->COM('disp_off');

            ##允许人员手动换工作层，重新判断移动层
            if (grep($_ eq $work_layer ,@work_layers)) {
               $ref_layer = $work_layer.$PAR->{silk_suffix};
            }elsif(grep($_.$PAR->{silk_suffix} eq $work_layer ,@work_layers)){
                $ref_layer = $work_layer;
                $ref_layer =~ s/\Q$PAR->{silk_suffix}\E$//;
            }
            if (! $GEN->isLayerExists(job=>$Job,layer=>$ref_layer) ){
                $GUI->msgbox(-icon=>'warning',-text=>"没有找到对应层$ref_layer ，请重新选择工作层！");
                goto LOOP;
            }
            #$GEN->workLayer(name=>$work_layer,display_number=>1,clear_before=>'yes');
            $GEN->displayLayer(name=>$ref_layer,number=>2);

            if ( $GEN->getSelectCount() > 0 ){
                $GEN->selSubstitute(tol=>1,mode=>'select');
                $GEN->selMoveOther(target_layer=>$ref_layer,invert=>'no');
            }else{
                $GEN->workLayer(name=>$work_layer,display_number=>1,clear_before=>'yes');
                $GEN->COM("filter_reset,filter_name=popup");
                $GEN->selectByFilter(area_rect=>\%tmp_con);
                
                if ( $GEN->getSelectCount() > 0 ){
                    $GEN->selSubstitute(tol=>1,mode=>'select');
                    $GEN->selMoveOther(target_layer=>$ref_layer,invert=>'no');
                }
                else{
                    $GEN->COM('disp_on');
                    last;
                }
            }
        }
    }else{
        $GUI->msgbox(-icon=>'info',-title=>'标题',-text=>"没有找到文字框和对应的文字层，程序将退出。");
        return 'Cancel';
    }
    $GEN->workLayer(name=>$work_layers[0],display_number=>1,clear_before=>'yes');
    $GEN->displayLayer(name=>$work_layers[0].$PAR->{silk_suffix},number=>2)if ( $GEN->isLayerExists(job=>$Job,layer=>$work_layers[0].$PAR->{silk_suffix}) );
	$GEN->COM('sel_clear_feat');

	#$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;
}

sub _deleteLayer{
    my %par = @_;
    foreach my $layer(@{$par{layer}}){
        $GEN->deleteLayer(layer=>$layer) if ($GEN->isLayerExists(job=>$Job,layer=>$layer));
    }
}

__END__
