=head
 NAME: 
 DESCRIPTION: 
 PARAMETER:
	{items => [
		{
			name=>'job',
			label=>'料号名',
			type=>'editable_enum',
			property=>{
				tl_field=>[name=>'text'],
				tl_data=>[
					{name=>'${JOB}',},
					{name=>'TL_genesis_work_jobname',},
					{name=>'TL_genesis_org_jobname',},
				]
			},
			must_field=>1,
			remark=>'程序会根据不同的选择来命名Genesis中的料号名字',
			value=>'${JOB}_chk',
		},
	]}
	
 VERSION_HISTORY:
	V1.00 2011-06-13 Janson Zhang
	   1.新版本
	V1.01 2015-11-05 Mast Pei
	   1.检查铜分布率时，先去除掉之前的值
	   
	   Ferre  -- 已经取消， 做错了，需重做
	V1.05 2016-04-14 mast
		添加 rigid_flex料号，检查内层是否存在SMD/BGA，并需要手动制作到EP层上
   	V1.06 2016-10-25 mast pei
	修改deleteLayer中的bug
	V1.07 2016-11-15 John
	Change resolution_value to 10um
		
	V1.09 2017-05-09 mast
	系统编号：867
			2171 料号触发后台服务
		计算每层原稿 PCB的 6X6 /9X9/12X12 区域的 铜分布率分布情况。

		1. If the left area less than total area 50% ,can skip the small area .
		
		2.offset as 0.5 times by X , Y and X &Y .
		
		3.The calculate area can set 6*6, 9*9 ,12*12mm
		
	V1.09 2017-12-25 mast	
	添加ATS_org_pcb_area pcb面积计算	
				
				
					
	V1.10 2019-05-14 mast					
		按照SSS添加3x3计算模式
				
	V1.11 2019-08-30 mast
	系统需求：2364
		consider the rout area to calculate the copper density 
	V1.12 2020-09-07 John
	系统需求：3132
		Cancel RF PN 	
		
 HELP:
 
	<html><body bgcolor="#DDECFE">
		<font size="3" color="#003DB2"><p>功能简介</p></font>
		  <p> Create PRE prepare step.</p>
		  <br>
		<font size="3" color="#003DB2"><p>参数配置</p></font>
		<font color="#008000"><p> ● 料号名</p></font>
		  <p> 设置genesis中料号的名字，${JOB}表示跟TopCAM中的料号名字一样，TL_genesis_work_jobname表示用这个料号属性定义的名字</p>
		<font color="#008000"><p> ● step过滤</p></font>
		  <p> 选择step时候的过滤器</p>
		<font size="3" color="#003DB2"><p>注意事项</p></font>
		  <p> ● </p>
		  <br>
	</body></html>
  
=cut

#use strict;
#my ($JOB,$GEN,$GUI,$DB,$JOB_ID,$PAR,%ARGS);
use utf8;
use Encode;
use Data::Dump 'dump';
my ($Job,$Step);
my $Return = 'Done';

###确定料号名;
# if (defined $PAR->{job} and ($PAR->{job} eq 'TL_genesis_org_jobname' or $PAR->{job} eq 'TL_genesis_work_jobname')){
	# $Job = $DB->get_jobinfo(-jobid=>$JOB_ID,-jobcategory=>'work',-jobinfo=>$PAR->{job});
# }
# elsif(defined $PAR->{job}){
	# $Job = $PAR->{job};
	# $Job =~ s/\$\{JOB\}/$JOB/g;
	# $Job = lc($Job);
# }
# if ( ! defined $Job or $Job =~ /^\s*$/) {
	# $GUI->msgbox(-icon=>'error',-text=>'未定义料号名');
	# return 'Error';
# }
###处理step过滤

my $customer = 	$ARGS{CUSTOMER};
$Job=$JOB.'_chk';
my $incam = 'no';
if ($GEN->{GEN_TYPE} eq 'incam') {
	$incam = 'yes';
}
my @parameter=('3x3','6x6','9x9','12x12');
my $ORG_job= $JOB.'_org';
my $genesisid = `ps -p $$ -o ppid=`;
$genesisid =~ s/\s//g;
$genesisid = `ps -p $genesisid -o ppid=`;
$genesisid =~ s/\s//g;
try{
	###检查Genesis料号是否存在并打开
	if (! $GEN->isJobExists(job=>$Job) ){
		$GUI->msgbox(-icon=>'error',-text=>"料号 $Job 在Genesis中不存在, 请检查!");
		return 'Error';
	}

	
	
	my $user_name =$GEN->getUserName();
	if ( $user_name=~/^(cam|check|qm|pe|imp|cam\d+|genesis)$/i){
		$GUI->msgbox(-icon=>'error',-text=>"[$user_name]账号不能保存资料,请用可以保存的Genesis账号放行资料");
		return 'Error';
	}	
	my $genusername =$GEN->getUserName();

	my $check = $GEN->checkInout(job=>$ORG_job,mode=>'test');
	if ($genusername ne $check and $check!=0) {
		$GUI->msgbox(-icon=>'error',-text=>"$ORG_job 被其他用户锁定,请解锁[$check]");
		return 'Error';
	}
	if ($check ==0) {
		$GEN->checkInout(job=>$ORG_job,mode=>'out');
	}
	
	$GEN->openJob(job=>$ORG_job);
	if ($GEN->{STATUS}){
		$GUI->msgbox(-icon=>'error',-text=>"$ORG_job 被[$genusername]打开,请[$genusername]关闭料号");
		return 'Error';		
	}
 #$GEN->PAUSE("1111111111111  ");
	
	$GEN->openJob(job=>$Job);
	my %matrix=$GEN->getMatrix(job=>$Job,type=>'hash');
#$GUI->debug("$customer  $Job");

	my @tmp_array1 = {
		name=>'add_array_copper',
		label=>"Array copper",
		type=>'enum',
		must_field=>1,
		property=>{
			tl_field=>['name'=>'text',tl_name=>'scalar'],
			tl_value_field=>'tl_name',
			tl_data=>[
				{name=>'YES',tl_name=>'Yes'},
				{name=>'NO',tl_name=>'No'},
			]
		}
	};

	my %tmp_array = $GUI->show_form(-title=>'请确认Array边是否有铜',-items=>\@tmp_array1,-defaultsize=>[300,300],-showcheck => 1,-gen => $GEN);
	return 'Cancel' unless %tmp_array;
	$DB->save_jobinfo(
		-jobid=>$JOB_ID,
		-jobcategory=>'org',
		-jobinfohash=>{'ATS_array_frame_with_copper'=>$tmp_array{add_array_copper}});

	
    my $LAYER_COUNT = $DB->get_jobinfo(-jobid=>$JOB_ID,-jobcategory=>'org',-jobinfo=>'TL_layer_count');
    my $ans_array;
	my @mode=('card');
	if($tmp_array{add_array_copper} eq 'Yes'){
		@mode=('card','array');
	}
	# $GUI->debug("@mode $tmp_array{add_array_copper}");
	my @steps  =  $GEN->getStepList(job=>$Job);
	my @step_list;
	foreach my $step (@steps){
		if ($step!~ /^(.*)(\d{8})\-(\d{6})$/){
			push @step_list,$step;
		}
	}	
	my @items_step_list;
	my (@Probfr,@Probba);

	foreach my $layer (sort {$matrix{$a}{row} <=> $matrix{$b}{row}}  keys %matrix) {
		push(@Probfr,{name=>$layer})  if($matrix{$layer}{side} eq 'top' and $matrix{$layer}{layer_type} eq 'solder_mask');
		push(@Probba,{name=>$layer})  if($matrix{$layer}{side} eq 'bottom' and $matrix{$layer}{layer_type} eq 'solder_mask');
	}
	push(@Probfr,{name=>'NA'});
	push(@Probba,{name=>'NA'});	
	foreach my $mode (@mode){
		push @items_step_list,{
			name => $mode,
			label => $mode.' Step',
			type => 'step',
			must_field=>1,
			value=>@step_list==1?$step_list[0]:'',
			property=>{
				tl_steplist=>[@step_list],
			},
		};
	}
	
	my @sminfo;
	push @sminfo,
		{
			name=>'Probfr',
			label=>'Probfr Layer',
			type=>'enum',
			property=>{
				tl_field=>[name=>'text'],
				tl_value_field=>'name',
				tl_data=>\@Probfr,
			},
			# must_field=>1,
			value => $Probfr[0]->{name} ? $Probfr[0]->{name} : 'NA',
		},
		{
			name=>'Probba',
			label=>'Probba Layer',
			type=>'enum',
			property=>{
				tl_field=>[name=>'text'],
				tl_value_field=>'name',
				tl_data=>\@Probba,
			},
			# must_field=>1,
			value => $Probba[0]->{name} ? $Probba[0]->{name}  : 'NA',
		};
	

	my %info = $GUI->show_form(
		-title => "确认[@mode]step/SM ",
		-showcheck => 1,
		-gen => $GEN,
		-items=>[
			{type=>'title',property=>{title=>'1.根据您当前step，请匹配step信息'}},
			@items_step_list,
			{type=>'title',property=>{title=>'2.Please select solder mask layer'}},
			@sminfo,
		]
	);
	return 'Cancel' unless %info;



	#my $rf_mark= $GUI ->confirm("是否是RF料号");
	my $rf_mark= "no";
	my $mark_rout_area;
	if ($info{card} eq $info{array}) {
		@mode=('array','card');
		$mark_rout_area='yes';
	}
	my $rout_copper_array='rout_copper_array';
	my $base_copper='base_copper_script';
	my $rout_copper='rout_copper_script';
	
	$GEN->openStep(job=>$Job,name=>$steps[0]);
	_deleteLayer(step=>$steps[0],layer=>[$rout_copper_array,$base_copper,$rout_copper]);
	my %sync_base_copper;
	my $pcb_step_tmp;
	
	
	foreach my $layer (sort {$matrix{$a}{row} <=> $matrix{$b}{row}}  keys %matrix) {
		if(defined($matrix{$layer}{tl_name}) and $matrix{$layer}{tl_name} =~ /^(top|bottom|l\d+)$/ ){
			my $tl = $matrix{$layer}{tl_name};
			foreach my $att ('TL_array_copper_distribution','TL_card_copper_distribution'){
				$DB->save_layerinfo(-jobid=>$JOB_ID,
					-tlname=>$tl,
					-jobcategory=>'org',
					-layerinfohash=>{$att=>''}
				);				
			}
			foreach my $att ('TL_array_copper_distribution_add_rout_area','TL_card_copper_distribution_add_rout_area'){
				$DB->save_layerinfo(-jobid=>$JOB_ID,
					-tlname=>$tl,
					-jobcategory=>'org',
					-layerinfohash=>{$att=>''}
				);				
			}			
		}
	}
	
	
	foreach my $checkstep (@mode) {
		my $copper_distribution;
		my ($area_all,$area_tmp);
        if ( $checkstep eq 'array' ) {
           $ans_array = $GUI ->confirm('Have array data exists for the copper distribution?');
             if ($ans_array eq 'no'){
				$mark_rout_area='yes';
				next;
			 }
        }
		my $step = $info{$checkstep};
		
		$GEN->openStep(job=>$Job,name=>$step);
		$GEN->closeStep();
		
		$GEN->openStep(job=>$Job,name=>$step);
		$GEN->clearLayers();
		$GEN->affectedLayer(mode=>'all',affected=>'no');
		$GEN->units(type=>'mm');
		$GEN->zoomHome();
		#$GEN->closeJob(job=>$ORG_job);
		return unless($GEN->PAUSE("Please change the[$Job] [$checkstep] profile to get the copper area for Step [${step}]!"));
		
	
		#my $ans = $GEN->PAUSE("Please change the [$checkstep] profile to get the copper area for Step [${step}]!");
		#unless (defined $ans and $ans eq 'OK' ) {
		#	return 'Cancel';
		#}
		
		# if ($customer eq 'APP' and $checkstep eq 'card' and $incam eq 'no'){
		if (
			## Open For All PNs at 2018-01-02
			#$customer eq 'APP' and
			$checkstep eq 'card'){
			
			
			if ($mark_rout_area ne 'yes') {
				my $profile_limits = $GEN->getProfileLimits(job=>$Job,step=>$step,units=>'mm');
				my $profile_x=$profile_limits->{xsize};
				my $profile_y=$profile_limits->{ysize};

				$GEN->createLayer(job=>$Job,layer=>$base_copper,conext=>'misc',type=>'signal')if (!$GEN->isLayerExists(job=>$Job,layer=>$base_copper));
				$GEN->units(type=>'inch');
				$GEN->srFill(dest=>'layer_name',layer=>$base_copper);
				$GEN->units(type=>'mm');
				$GEN->workLayer(name=>$base_copper,number=>1);
				
				$GUI->msgbox(-text=>"请给${checkstep}[$step]制作铜面区域;去除Routing区域废铜\n用来计算'3x3','6x6','9x9','12x12' area,不需考虑Routing/Npth避铜问题");
				return unless($GEN->PAUSE("Pls delete the dummy copper on routing area of layer [ $base_copper ] by manually"));
				$GEN->checkInout(job=>$Job,mode=>'out');
				 
				$GEN->units(type=>'mm');
				$GEN->clearLayers();
				$GEN->affectedLayer(mode=>'all',affected=>'no');
				$GEN->workLayer(name=>$base_copper,number=>1);
				$GEN->selContourize();
				#$sync_base_copper{$step}=$base_copper;
				push @{$sync_base_copper{$step}},$base_copper if(!grep /@{$sync_base_copper{$step}}/,$base_copper);
				$GEN->createLayer(job=>$Job,layer=>$rout_copper,conext=>'misc',type=>'signal')if (!$GEN->isLayerExists(job=>$Job,layer=>$rout_copper));
				$GEN->units(type=>'inch');
				$GEN->workLayer(name=>$rout_copper,number=>1);
				$GEN->srFill(dest=>'layer_name',layer=>$rout_copper);
				$GEN->units(type=>'mm');
				if ($GEN->isLayerExists(job=>$Job,layer=>$base_copper)) {
					#$GEN->COM('sel_resize',size=>-4000,corner_ctl=>'no');
					$GEN->copyLayer(source_job=>$Job,
									source_step=>$step,
									source_layer=>$base_copper,
									dest_layer=>$rout_copper,
									invert=>'yes',
									mode=>'append', 
									);
	
					$GEN->selContourize();
					$GEN->COM('sel_resize',size=>-4000,corner_ctl=>'no');
				}
			}
			else{
				$GEN->affectedLayer(affected=>'yes',mode=>'single',layer=>[$base_copper,$rout_copper],clear_before=>'yes');
				$GEN->COM('clip_area_strt');
				$GEN->COM('clip_area_end,layers_mode=affected_layers,layer=,area=profile,area_type=rectangle,inout=outside,contour_cut=no,margin=0');

			}
			
			
			my $copper_area = $GEN->copperArea(layer1=>$base_copper,resolution_value=>10);
			my $area =sprintf ('%.4f',$copper_area->{area} / 10000);  ###  units: dm2
			$DB->save_jobinfo(
				-jobid=>$JOB_ID,
				-jobcategory=>'org',
				-jobinfohash=>{'ATS_org_pcb_area'=>$copper_area->{area}/0.00001});			
			
			$GEN->saveJob(job=>$Job);
			if ($incam ne 'no') {
				$GEN->checkInout(job=>$Job,mode=>'in');
				$GEN->checkInout(job=>$Job,mode=>'out');
			}		
			unless ($GEN->{STATUS}){
				$pcb_step_tmp = $step;
			}
	
		}
		elsif ($mark_rout_area eq 'yes') {
			my $profile_limits = $GEN->getProfileLimits(job=>$Job,step=>$step,units=>'mm');
			my $profile_x=$profile_limits->{xsize};
			my $profile_y=$profile_limits->{ysize};
			my $base_copper='base_copper_script';
			$GEN->createLayer(job=>$Job,layer=>$base_copper,conext=>'misc',type=>'signal')if (!$GEN->isLayerExists(job=>$Job,layer=>$base_copper));
			$GEN->units(type=>'inch');
			$GEN->srFill(dest=>'layer_name',layer=>$base_copper);
			$GEN->units(type=>'mm');
			$GEN->workLayer(name=>$base_copper,number=>1);
			
			$GUI->msgbox(-text=>"请给${checkstep}[$step]制作铜面区域;去除Routing区域废铜\n用来计算'3x3','6x6','9x9','12x12' area,不需考虑Routing/Npth避铜问题");
			return unless($GEN->PAUSE("Pls make copper on [$base_copper],use cal '3x3','6x6','9x9','12x12' area"));
			$GEN->checkInout(job=>$Job,mode=>'out');
			
			$GEN->units(type=>'mm');
			$GEN->clearLayers();
			$GEN->affectedLayer(mode=>'all',affected=>'no');
			$GEN->workLayer(name=>$base_copper,number=>1);
			$GEN->selContourize();
			
			
			$GEN->createLayer(job=>$Job,layer=>$rout_copper,conext=>'misc',type=>'signal')if (!$GEN->isLayerExists(job=>$Job,layer=>$rout_copper));
			$GEN->units(type=>'inch');
			$GEN->workLayer(name=>$rout_copper,number=>1);
			$GEN->srFill(dest=>'layer_name',layer=>$rout_copper);
			$GEN->units(type=>'mm');
			if ($GEN->isLayerExists(job=>$Job,layer=>$base_copper)) {
				$GEN->COM('sel_resize',size=>-4000,corner_ctl=>'no');
				$GEN->copyLayer(source_job=>$Job,
								source_step=>$step,
								source_layer=>$base_copper,
								dest_layer=>$rout_copper,
								invert=>'yes',
								mode=>'append', 
								);

				$GEN->selContourize();
				$GEN->COM('sel_resize',size=>-4000,corner_ctl=>'no');
				#$sync_base_copper{$step}=$rout_copper;
				push @{$sync_base_copper{$step}},$rout_copper if(!grep /@{$sync_base_copper{$step}}/,$rout_copper);
			}
			push @{$sync_base_copper{$step}},$base_copper if(!grep /@{$sync_base_copper{$step}}/,$base_copper);
			$GEN->openJob(job=>$ORG_job);
			my @org_steps = $GEN->getStepList(job=>$ORG_job);
			foreach my $step (keys %sync_base_copper){
				if ($GEN->isStepExists(job=>$ORG_job,step=>$step) ) {		
					$GEN->openStep(job=>$ORG_job,name=>$step);
					foreach my $f (@{$sync_base_copper{$step}}){
						my $f1 ='ats_rout_copper_ref' if ($f=~/rout_copper/);
						$f1 ='ats_base_copper_ref' if ($f=~/base_copper/);
						$GEN->copyLayer(source_job=>$Job,
										source_step=>$step,
										source_layer=>$f,
										dest_layer=>$f1,
										);					
						
						
					}
					$GEN->closeStep();
				}
				else{
					my $step1 = $GUI->select_step(
					-title      => "[$step]所对应的${ORG_job}中的Step",
					-steplist   => [@org_steps],
					);			
					return 'Cancel' unless ( $step1);   
					$GEN->openStep(job=>$ORG_job,name=>$step1);
					foreach my $f (@{$sync_base_copper{$step}}){
						my $f1 ='ats_rout_copper_ref' if ($f=~/rout_copper/);
						$f1 ='ats_base_copper_ref' if ($f=~/base_copper/);
						$GEN->copyLayer(source_job=>$Job,
										source_step=>$step,
										source_layer=>$f,
										dest_layer=>$f1,
										);					
						
						
					}
					$GEN->closeStep();
				}
				
			}
			$GEN->closeJob(job=>$ORG_job)
		}
		
		my (%copper_distribution,%copper_distribution_add_rout);

		$GEN->openStep(job=>$Job,name=>$step);
		$GEN->units(type=>'mm');
		$GEN->clearLayers();
		$GEN->affectedLayer(mode=>'all',affected=>'no');
		my $tmp_copper='ats_script_copper';

		my ($layer_profile,@have_sel_line);
		while(1){
			my $mm;
			foreach my $layer (sort {$matrix{$a}{row} <=> $matrix{$b}{row}}  keys %matrix) {
				if(defined($matrix{$layer}{tl_name}) and $matrix{$layer}{tl_name} =~ /^(top|bottom|l\d+)$/ ){
					$mm++;
					_deleteLayer(step=>$step,layer=>[$tmp_copper]);
					if ($rf_mark =~/yes/i and $checkstep eq 'card' and $mm==1){
						if (!$layer_profile){

							$GUI->msgbox(-icon=>'info',-text=>"RF JOB:请确认硬板区域out层的线宽不一样.");
							my $ans = $GEN->PAUSE("RF job:Pls change.");
							unless (defined $ans and $ans eq 'OK' ) {
								return 'Cancel';
							}
							$layer_profile = $GUI->select_layer(-title=>'选择硬板区域out层',
									-layermatrix=>{$GEN->getMatrix(job=>$Job,type=>'hash')},
									-selectmode => 'single');
							return 'Cancel' if(!$layer_profile);
							my %symlist = $GEN->getLayerSymsHist(job=>$Job,step=>$step,layer=>$layer_profile,units=>"mm");
							foreach my $symbol (keys %symlist) {
								if ( $symlist{$symbol}{line} > 0 or  $symlist{$symbol}{arc} > 0 ) {
									push @have_sel_line,$symbol if (!grep /$symbol$/,@have_sel_line);
								}
							}
						}
						$GEN->affectedLayer(affected=>'yes',mode=>'single',layer=>[$layer_profile],clear_before=>'yes');
						$GEN->selectByFilter(
							feat_types=>'line\;arc',
							include_syms=>$have_sel_line[0],
						);
					
						@have_sel_line=grep{$_ ne $have_sel_line[0]}@have_sel_line;  
						
						if ($GEN->getSelectCount()>0){
							$GEN->COM('sel_create_profile');
							$GEN->affectedLayer(mode=>'all',affected=>'no');
						}
						else{
							$GUI->msgbox(-icon=>'error',-text=>"profile没有定义成功");
							return 'Error';
						}
			# $GEN->PAUSE("11111111111111");			
						_deleteLayer(step=>$step,layer=>['rf_ats_script_copper']);
						$GEN->COM('create_layer',layer=>'rf_ats_script_copper') if (!$GEN->isLayerExists(job=>$Job,layer=>'rf_ats_script_copper'));
						_copperFill('rf_ats_script_copper','solid','',0.0254,0.0254,'positive',0,0,0,0,'no');
						$GEN->units(type=>'mm');
						my $copper_area = $GEN->copperArea(layer1=>'rf_ats_script_copper',resolution_value=>10);
						$copper_distribution{$matrix{$layer}->{tl_name}}{area_all}+=$copper_area->{area} if ($rf_mark =~/yes/i);
						

						

					}
					
			# $GUI->debug(dump \%copper_distribution);					
					$GEN->flattenLayer(source_layer=>$layer,target_layer=>$tmp_copper);
					$GEN->workLayer(name=>$tmp_copper,number=>1);
					$GEN->COM('clip_area_strt');
							# $GEN->PAUSE("$copper_area->{area}  $layer ");	
					$GEN->COM('clip_area_end',layers_mode=>'affected_layers',
								# layer=>'',
								area=>'profile',									
								area_type=>'rectangle',
								inout=>'outside',
								contour_cut=>'yes',
								margin=>0);	
								
			# $GUI->debug(dump \%copper_distribution);
					$GEN->units(type=>'mm');
					my $copper_area = $GEN->copperArea(layer1=>$tmp_copper,resolution_value=>10);
					$copper_distribution{$matrix{$layer}->{tl_name}}{area_tmp}+=$copper_area->{area} if ($rf_mark =~/yes/i);
					$copper_distribution{$matrix{$layer}->{tl_name}}{area_all}=$copper_distribution{'top'}{area_all} if ($rf_mark =~/yes/i);
					$copper_distribution{$matrix{$layer}->{tl_name}}{percent}=$copper_area->{percent};
					if (grep /^card$/,@mode and $checkstep eq 'array') {
						if (!$GEN->isLayerExists(job=>$Job,layer=>$rout_copper_array)) {
							if ($GEN->isLayerExists(job=>$Job,layer=>$rout_copper)) {
								$GEN->flattenLayer(source_layer=>$rout_copper,target_layer=>$rout_copper_array);
							}							
						}
						
						if (!$GEN->isLayerEmpty(job=>$Job,step=>$step,layer=>$rout_copper_array)){
							push @{$sync_base_copper{$step}},$rout_copper_array if(!grep /@{$sync_base_copper{$step}}/,$rout_copper_array);
							$GEN->copyLayer(source_job=>$Job,
											source_step=>$step,
											source_layer=>$rout_copper_array,
											dest_layer=>$tmp_copper,
											mode=>'append');
							my $copper_area1 = $GEN->copperArea(layer1=>$tmp_copper,resolution_value=>10);
							$copper_distribution_add_rout{$matrix{$layer}->{tl_name}}{percent}+=$copper_area1->{percent};
						}
					}
					elsif ($GEN->isLayerExists(job=>$Job,layer=>$rout_copper)) {
						if (!$GEN->isLayerEmpty(job=>$Job,step=>$step,layer=>$rout_copper)){
							push @{$sync_base_copper{$step}},$rout_copper if(!grep /@{$sync_base_copper{$step}}/,$rout_copper);
							$GEN->copyLayer(source_job=>$Job,
											source_step=>$step,
											source_layer=>$rout_copper,
											dest_layer=>$tmp_copper,
											#invert=>'yes',
											mode=>'append', 
											);
							my $copper_area1 = $GEN->copperArea(layer1=>$tmp_copper,resolution_value=>10);
							$copper_distribution_add_rout{$matrix{$layer}->{tl_name}}{percent}+=$copper_area1->{percent};
						}
					}					
				}
			}
			if ($rf_mark !~/yes/i ){
				last;
			}
			elsif ($rf_mark =~/yes/i){
				last if (!@have_sel_line);
			}
		}
# $GUI->debug(dump \%copper_distribution);

		foreach my $tl(keys %copper_distribution){		
			if (defined $copper_distribution{$tl}{area_tmp} and  defined $copper_distribution{$tl}{area_all}){
				my$rr=sprintf("%.3f",($copper_distribution{$tl}{area_tmp}/$copper_distribution{$tl}{area_all})*100);
				$DB->save_layerinfo(-jobid=>$JOB_ID,
					-tlname=>$tl,
					-jobcategory=>'org',
					-layerinfohash=>{'TL_'.$checkstep.'_copper_distribution'=>$rr}
				);	
			}
			else{
				$DB->save_layerinfo(-jobid=>$JOB_ID,
					-tlname=>$tl,
					-jobcategory=>'org',
					-layerinfohash=>{'TL_'.$checkstep.'_copper_distribution'=>$copper_distribution{$tl}{percent}}
				);
				
				$DB->save_layerinfo(-jobid=>$JOB_ID,
					-tlname=>$tl,
					-jobcategory=>'org',
					-layerinfohash=>{'TL_'.$checkstep.'_copper_distribution_add_rout_area'=>$copper_distribution_add_rout{$tl}{percent}}
				) if ($copper_distribution_add_rout{$tl}{percent});				
				
				
				
			}
		}
	
		
		_deleteLayer(step=>$step,layer=>['script_tmp']);
		if ( $checkstep eq 'card' ) {
			if ($rf_mark =~/yes/i){
				my $ans = $GEN->PAUSE("RF job:Please change the [$checkstep] profile to get the SM point for Step [${step}] all !");
				unless (defined $ans and $ans eq 'OK' ) {
					return 'Cancel';
				}				
			}

			next if ($info{Probfr} eq 'NA' and $info{Probba} eq 'NA');
			foreach my $layer ($info{Probfr},$info{Probba}) {
				next if ($layer eq 'NA');
				#转标准层名 存入数据库
				my $standard_layer_name=$matrix{$layer}->{tl_name};
				
				$GEN->copyLayer(source_job=>$Job,
								source_step=>$step,
								source_layer=>$layer,
								dest_layer=>$layer.'1',
								mode=>'replace');
	
				$GEN->zoomHome();
				$GEN->workLayer(name=>$layer.'1',number=>1);
				$GEN->selBreak();
	
				$GEN->selContourize();
				$GEN->COM('sel_decompose',overlap=>'yes');
				$GEN->COM('clip_area_strt');
				$GEN->COM('clip_area_end,layers_mode=affected_layers,layer=,area=profile,area_type=rectangle,inout=outside,contour_cut=no,margin=0');
				$GEN->selectByFilter(
					feat_types=>'surface',
					profile=>'in',
				);
				
		#$GEN->PAUSE("opop fffff  55555");		 
				my $num = $GEN->getSelectCount();
		#$GEN->PAUSE("opop fffff  55555  $num");		 
				#$GEN->COM('reread_layer',layer=>$layer);
		
				$DB->save_layerinfo(-jobid=>$JOB_ID,
					-tlname=>$standard_layer_name,
					-jobcategory=>'org',
					-layerinfohash=>{'ATS_sm_opening_num'=>$num,}
				);
			}
		}
		
	}
	
    $GEN->clearLayers();
    $GEN->affectedLayer(mode=>'all',affected=>'no');
	my @org_steps = $GEN->getStepList(job=>$ORG_job);
	if ($mark_rout_area ne 'yes'){
		
		$GEN->openJob(job=>$ORG_job);
		
		foreach my $step (keys %sync_base_copper){
			if ($GEN->isStepExists(job=>$ORG_job,step=>$step) ) {		
				$GEN->openStep(job=>$ORG_job,name=>$step);
				foreach my $f (@{$sync_base_copper{$step}}){
					my $f1 ='ats_rout_copper_ref' if ($f=~/rout_copper/);
					$f1 ='ats_base_copper_ref' if ($f=~/base_copper/);
					$GEN->copyLayer(source_job=>$Job,
									source_step=>$step,
									source_layer=>$f,
									dest_layer=>$f1,
									);					
					
					
				}
	
			}
			else{
				my $step1 = $GUI->select_step(
				-title      => "[$step]所对应的${ORG_job}中的Step",
				-steplist   => [@org_steps],
				);			
				return 'Cancel' unless ( $step1);   
				$GEN->openStep(job=>$ORG_job,name=>$step1);
				foreach my $f (@{$sync_base_copper{$step}}){
					my $f1 ='ats_rout_copper_ref' if ($f=~/rout_copper/);
					$f1 ='ats_base_copper_ref' if ($f=~/base_copper/);
					$GEN->copyLayer(source_job=>$Job,
									source_step=>$step,
									source_layer=>$f,
									dest_layer=>$f1,
									);					
					
					
				}			
			}
		}		
		$GEN->closeStep();
	}

	$GEN->openStep(job=>$ORG_job,name=>$org_steps[0]);
	$GEN->saveJob(job=>$ORG_job);
	$GEN->checkInout(job=>$ORG_job,mode=>'in');
	$GEN->closeJob(job=>$ORG_job);
	if ($GEN->{STATUS}){
		$GUI->msgbox(-icon=>'error',-text=>join("\n",@{$GEN->{STATUS}}));
		return 'Error';				
	}		
	###output and return status, if genesis error, it will output genesis error command
	unless ($GEN->{STATUS}){
		
		if ($pcb_step_tmp) {
			my $return1 = $DB->insert(
				-table=>'ats_genesis_background_server',
				-data=>{
					job_name=>$Job,
					step_name=>$pcb_step_tmp,
					status=> 'Active',
					use_mode => 'check_pcb_copper_density',
					try_times=>1,
					layer_name => '',
					job_id=>$JOB_ID,
					cam_user=>$APP->{USER_NAME},
					process_id=>$ARGS{process_id},
					parameter=>(dump @parameter),
				},
				-return=>['id'],
			);
			if (!$return1->{id}){
				$GUI->msgbox(-icon=>'error',-text=>"Update database error,请重新申请");
				return 'Error';		
			}
			
			if ($GEN->{STATUS}){
				$GUI->msgbox(-icon=>'error',-text=>join("\n",@{$GEN->{STATUS}}));
				return 'Error';	
			}
		}		
		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 _deleteLayer{
    my %par = @_;
    foreach my $layer(@{$par{layer}}){
        $GEN->deleteLayer(layer=>$layer) if ($GEN->isLayerExists(job=>$Job,layer=>$layer));
    }
	$GEN->openStep(job=>$Job,name=>$par{step}) if ($par{step});
}

sub _copperFill {

  my $layer = shift;
  my $type = shift;
  my $symbol = shift;
  my $dx = shift; 
  my $dy = shift;
  my $polarity = shift;
  my $step_x = shift;
  my $step_y = shift;
  my $sr_x = shift;
  my $sr_y = shift;
  my $consider_feat = (shift or 'yes');
  my $feat_margin = (shift or 0.03);
 
  $GEN->COM('fill_params',
                type=>$type,
                origin_type=>"datum",
                solid_type=>"surface",
                min_brush=>1,
                use_arcs=>"yes",
                symbol=>$symbol,
                dx=>$dx,
                dy=>$dy,
                break_partial=>"yes",
                cut_prims=>"no",
                outline_draw=>"no",
                outline_width=>0,
                outline_invert=>"no");
  $GEN->COM('sr_fill',
                polarity=>$polarity,
                step_margin_x=>$step_x,
                step_margin_y=>$step_y,
                step_max_dist_x=>100,
                step_max_dist_y=>100,
                sr_margin_x=>$sr_x,
                sr_margin_y=>$sr_y,
                sr_max_dist_x=>0,
                sr_max_dist_y=>0,
                nest_sr=>"no",
                consider_feat=>$consider_feat,
                feat_margin=>$feat_margin,
                consider_drill=>"no",
                drill_margin=>0,
                consider_rout=>"no",
                dest=>'layer_name',
                layer=>$layer,
                attributes=>"no");
}

