=head
 NAME:ZWZ_output_rou
 DESCRIPTION: 锣带输出
 PARAMETER:
	[
		{
			name : 'Outpath',
			type : 'LineEdit',
			title : 'path',
			pack : {row:0,column:1},
			property:{tool_tip:''},
		},
	]
	
 VERSION_HISTORY:
	V1.01 2020-12-03 Super
		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> ● 无</p>
		<font size="3" color="#003DB2"><p>注意事项</p></font>
		  <p> ● 无 </p>
		  <br>
	</body></html>
  
=cut

use strict;
use utf8;
use Encode;
use Data::Dump 'dump';
use Number::Format 'round';
use File::Path 'make_path';
use File::Copy;
use Win32::OLE::Const ;
my $EX_OB = Win32::OLE->new('Excel.Application', 'Quit');
my $const = Win32::OLE::Const->Load($EX_OB);
use_module('TL_GenMath');
use_module('TL_OLE_Excel');
my $json = new JSON;
my $obj = TL::GenMath->new();
my $Job = $JOB;
my $Step = $PAR->{step_filter} = $PAR->{step_filter} ? $PAR->{step_filter} : '.*';
my $Return = 'done';
my $tmp_layer = 'tl_tmp_layer';
my @rou_layer;

try{
	if (! $GEN->isJobExists(job=>$Job) ){
        $GUI->msgbox(-icon=>'error',-text=>"料号 $Job 在Genesis中不存在, 请检查!");
        return 'Error';
    }

    $GEN->openJob(job=>$Job) unless ($GEN->isJobOpen(job=>$Job));
	update_loading("过滤工作step...",0,position=>'n');
	my $return = get_work_step();
	return 'Cancel' if $return eq 'Cancel';
	
	$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=>'mm' );
	$GEN->zoomHome();
	
	update_loading("确认输出参数...",0,position=>'n');
	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($matrix{$layer}{layer_type} eq 'rout'){
				push @rou_layer,$layer;
			}			
		}
	}
	my $info = confirm_gui(layers=>[@rou_layer]);
	return unless ($info);

	update_loading("rou输出中...",0,position=>'n');
	output_rou(job=>$Job,step=>$Step,info=>$info);

	update_loading("资料回读中...",0,position=>'n');
	input_layers(job=>$Job,step=>$Step,info=>$info);

	###output and return status, if genesis error, it will output genesis error command
	unless ($GEN->{STATUS}){
		show_loading("资料输出完成....!",0,position=>'center');
		sleep(1);
		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{
	
};



=head
	rou输出
=cut
sub output_rou {
	my %par = @_;
	my $info = $par{info};
	my $PL = $GEN->getProfileLimits(job=>$Job,step=>$Step,units=>'mm');
	my $nc_set = 'zwz';
	my $machine = 'sintai_excellon';
	foreach my $layer (values %{$info->{layer_info}}) {
		next if ($layer->{output_flag} !~ /^yes$/i);
		$GEN->DO_INFO("-t layer -e $Job/$Step/$layer->{layer_name} -d NCRSETS_LIST");
		if( @{$GEN->{doinfo}{gNCRSETS_LIST}} ){
			if (grep (/^($nc_set)$/,@{$GEN->{doinfo}{gNCRSETS_LIST}})) {
				$GEN->COM('ncrset_delete',name=>$nc_set);
			}
		}
		$GEN->COM('ncrset_cur',job=>$Job,step=>$Step,layer=>$layer->{layer_name},ncset=>$nc_set);
		$GEN->COM('ncr_set_machine',machine=>$machine,thickness=>0);
		$GEN->COM('ncr_register',angle=>0,mirror=>$layer->{is_mirror},xoff=>0,yoff=>0,version=>1,xorigin=>0,yorigin=>0,xscale=>$layer->{scale_x},yscale=>$layer->{scale_y},xscale_o=>0,yscale_o=>0);
		$GEN->COM('ncr_cre_rout');
		$GEN->COM('ncr_ncf_export',dir=>$info->{output_path},name=>$info->{prefix}.'.'.$layer->{layer_name});
		$GEN->COM('ncrset_delete',name=>$nc_set);
	}
	unless ($GEN->{STATUS}){
		return ;
	}
}

=head
	用户配置参数
=cut
sub confirm_gui {
	my %par = @_;
	my ($rows,$n);
	my $cam = $IKM->get_jobinfo(-jobname=>$Job,-jobid=>$JOB_ID,-jobcategory=>'work',-jobinfo=>'cam_serial_number',-withspec=>1);
	my $folder = 'rou';
	my $path = $PAR->{Outpath}."$cam/$folder";
	make_path($path);
	foreach my $layer (@{$par{layers}}) {
		$n ++;
		$rows->{$n}{sequence} = $n;
		$rows->{$n}{layer_name} = $layer;
		$rows->{$n}{scale_x} = 1;
		$rows->{$n}{scale_y} = 1;
		$rows->{$n}{output_flag} = 'Yes';
		$rows->{$n}{is_mirror} = 'no';
	}
	my $v_data = $GUI->show_form(
		-title=>"Rou输出参数确认单",
		-defaultsize=>[520,500],
		-items=> [
			{
				type => 'title',
				property=>{
					title=>'输出料号和名称',
				},	
				n_columns=>2,
			},
			{
				name => 'prefix',
				label => '输出档名:',
				type => 'string',
				value=>$cam,
				width=>100,
				must_field=>1,
			},
			{
				type => 'title',
				property=>{
					title=>'参数确认',
				},	
				n_columns=>8,
			},
			{
				name => 'layer_info',
				label =>'参数确认',
				label_position => 'no',
				class => 'TL::Gtk2::TableFormPanel',
				expand => 1,
				property => {
					tl_columns =>[
						{
							column_name=>'layer_name',
							label=>'层别名称',
							width=>100,
							type=>'label',
						},
						{
							column_name=>'scale_x',
							label=>'涨缩值X',
							width=>80,
							type=>'number',
							must_field=>1,
						},
						{
							column_name=>'scale_y',
							label=>'涨缩值Y',
							width=>80,
							type=>'number',
							must_field=>1,
						},
						{
							column_name=>'output_flag',
							label=>'是否输出',
							width=>80,
							type=>'radio',
							property=>{
								tl_columns => 2,  
								tl_list => ['Yes' => '是', 'No'=>'否'],   
							},
						},
						{
							column_name=>'is_mirror',
							label=>'是否镜像',
							width=>80,
							type=>'radio',
							property=>{
								tl_columns => 2,  
								tl_list => ['yes' => '是', 'no'=>'否'],   
							},
						}
					],
					tl_rows=>$rows,
				},
				set_value_func => sub{
					my %par = @_;
					my $data = $par{value};
					foreach my $row_name (%$data){
						foreach my $col_name (%{$data->{$row_name}}){
							$par{widget}->set_value($row_name,$col_name,$data->{$row_name}{$col_name});
						}
					}
				},
				get_value_func => sub{my %par = @_;return $par{widget}->get_all_value();},
			},
			{
				type => 'title',
				property=>{
					title=>'输出设置',
				},	
				n_columns=>1,
			},
			{
				name => 'username',
				label => '输出者:',
				type => 'string',
				value=>$GEN->getUserName(),
				width=>100,
				must_field=>1,
			},
			{
				name => 'output_path',
				label => '输出路径:',
				type => 'string',
				value=>$path,
				width=>100,
				must_field=>1,
				property => {
					editable=>0,
				},
				buttons => [
					{   
						name=>'btn1',label=>'选择路径',stock=>'gtk-add',
						command=>sub{
							my %p = @_;
							my $folder = $GUI->select_file(-title=>'选择路径',-type=>'select-folder',-defaultdir=>$PAR->{Outpath});
							return unless($folder);
							$p{formpanel}->set_value('output_path', $folder);
						}
					},
				],
			},
		]
	);
	return $v_data;
}





=head
	文件导入设置
=cut
sub input_layers {
	my %par = @_;
	my $info = $par{info};
	my @layers = values %{$info->{layer_info}};
	foreach my $lyr (@layers) {
		next unless ($lyr->{output_flag} =~ /yes/i);
		my $name = $info->{output_path}.'/'.$info->{prefix}.'.'.$lyr->{layer_name};
		my $layer= lc($info->{prefix}.'.'.$lyr->{layer_name});
		$GEN->COM("input_manual_reset");
		$GEN->COM("input_manual_set,path=$name,job=$par{job},step=$par{step},format=Excellon2,data_type=ascii,units=mm,coordinates=absolute,zeroes=none,nf1=3,nf2=3,decimal=no,separator=nl,tool_units=mm,layer=$layer,wheel=,wheel_template=,nf_comp=0,multiplier=1,text_line_width=0.0024,signed_coords=no,break_sr=yes,drill_only=no,merge_by_rule=no,threshold=200,resolution=3");
		$GEN->COM("input_manual,script_path=");
		$GEN->COM("matrix_layer_context,job=$Job,matrix=matrix,layer=$layer,context=misc");
	}
}

=head
	获取工作step
=cut
sub get_work_step {
	update_loading("选择工作step...",0,position=>'n');
    my @steps =  $GEN->getStepList(job=>$Job);
	if ( @steps == 0 ) {
		$GUI->msgbox(-icon=>'error',-text=>'在料号中没有Step存在,你将退出!');
		return 'Cancel';
	}
	elsif (@steps != 0){
		my @tmp_steps = grep(/$Step/,@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);            
        }
	}
}



__END__
