/*
NAME: 
DESCRIPTION: ;
PARAMETER:
    [
		{
			name : 'step',
			title : 'step',
			type : 'LineEdit',
			property : {tool_tip : '目标step,默认是orig'},
		},
		{
            name : 'auto_save',
			title : '自动保存',
            type : 'RadioBox',
            property : {
				item_list:[
					{name:'yes',text:'YES'},
					{name:'no',text:'NO'},
				],
				tool_tip:'是否自动保存料号开关'
			}
        }
	]
	
 VERSION_HISTORY:
	V1.00 2020-09-01 Scott Sun
	    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> step信息 </p>
		<br>
		<font size="3" color="#003DB2"><p>注意事项</p></font>
		<p> 无 </p>
		<br>
	</body></html>	
*/
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
console.log("==============================>template");
// 引入模块 包
var $ = require('topcam.scriptfunc').argv();
var fs = require('fs');
var _ = require('lodash');
var mode = $.ikm ? "topcam" : "aimdfm";
var IKM = $.ikm; 
if (IKM==undefined ) { IKM = require('topcam.ikm6')($) }
var GEN = $.gen;
var GUI = $.gui || {};
var Job = $.job || $.job_name;
var JobId = $.job_id;
var db = $.db || IKM.db
var PAR = {}
if ($.par) {
	PAR = $.par
} else if ($.hasOwnProperty('script_parameter')){
	PAR = JSON.parse($.script_parameter);
}
if (mode === "aimdfm") {
	var database = require("topsin.database");
	database.addConnection($.conf.database_conf, "DFM");
	var QDfm = database.query("DFM");
	$.QDfm = QDfm;
	if ($.conf.product_type == "aimdfm") {
		QDfm.updateRow({
			table: "pdm_aimdfm_task",
			data: {
				current_process_title: $.process_title
			},
			where: { id: $.task_id }
		});
	}
}
var Status = 'ok';
var resultData = [];

try {
	var par = PAR;
	var default_par = {
		step: "unit",
		auto_save: "No",
		units: 'mm'
	}
	for(var key in default_par){  // 设置默认属性
		if (!par.hasOwnProperty(key) || par[key] == ""){
			par[key] = default_par[key]
		}
	}
	if(_.isEmpty(Job)){throw "参数Job不存在"}
	var job = Job.toLowerCase()
	if(!GEN.isJobExists({job:job})){throw "料号"+job+"不存在"}
	if(!GEN.isJobOpen({job:job})){ GEN.openJob({job:job}) }
    if(mode == "aimdfm"){
        if(GEN.checkInout({job:job,mode:"test"}) != 0){ throw "the job check" }
        GEN.checkInout({job:job,mode:"out"});
    }
	job = "1";
	var step = "cad"
	var layer= "drl"

	if(GEN.isLayerExists({job:job, layer:"pt-rou"})){GEN.deleteLayer({job:'Job',layer:["pt-rou"]})}
	if(GEN.isLayerExists({job:job, layer:"ol_tmp"})){GEN.deleteLayer({job:'Job',layer:["ol_tmp"]})}
	GEN.createLayer({job:job,layer:'pt-rou',conext:'misc',type:'rout'})
	GEN.matrixMoveRow({job:job,layer:'pt-rou',after:'---'})
	var feats = GEN.getFeatures({job:job,step:step,layer:layer, options:"feat_index", units:"mm"})
	feats.forEach(function(item) {
		if(item.type == "line") { // 槽孔
			var width = parseFloat(item.symbol.slice(1))
			var length = width + Math.sqrt((item.xe - item.xs)*(item.xe - item.xs) + (item.ye - item.ys)*(item.ye - item.ys))
			if(item.attributes && item.attributes.indexOf(".drill=non_plated") >= 0) {
				if(width >= 6050 || length>= 12000){
					GEN.selLayerFeat({layer:layer, index:index,operation:"select"});
					if(GEN.getSelectCount() > 0){GEN.selMoveOther({target_layer:'ol_tmp',invert:'no',dx:0,dy:0,size:0})}
				}
			} else if (item.attributes && item.attributes.indexOf(".drill=plated") >= 0) {
				if(width >= 6050 || length>= 12000){
					GEN.selLayerFeat({layer:layer, index:index,operation:"select"});
					if(GEN.getSelectCount() > 0){GEN.selMoveOther({target_layer:'pt-rou',invert:'no',dx:0,dy:0,size:0})}
				}
			}
		}
		if(item.type == "pad") {
			var size = parseFloat(item.symbol.slice(1));
			if(item.attributes && item.attributes.indexOf(".drill=non_plated") >= 0) {
				if(size > 6000 ){
					GEN.selLayerFeat({layer:layer, index:index,operation:"select"});
					if(GEN.getSelectCount() > 0){GEN.selMoveOther({target_layer:'ol_tmp',invert:'no',dx:0,dy:0,size:0})}
				}
			} else if (item.attributes && item.attributes.indexOf(".drill=plated") >= 0) {
				if(size > 12000 ){
					GEN.selLayerFeat({layer:layer, index:index,operation:"select"});
					if(GEN.getSelectCount() > 0){GEN.selMoveOther({target_layer:'pt-rou',invert:'no',dx:0,dy:0,size:0})} 
				}
			}
		}
	})

	// 将ol_tmp  和 pt-rou的转为非闭合图形
	GEN.clearLayers()
	GEN.affectedLayer({affected:'yes',layer:["ol_tmp", "pt-rou"], clear_before:"yes"})
	GEN.COM("sel_contourize,accuracy=0,break_to_islands=yes,clean_hole_size=0,clean_hole_mode=x_and_y")
	GEN.COM("sel_surf2outline,width=1")
	GEN.affectedLayer({affected:'no',mode:'all'})
	GEN.workLayer({name:'ol_tmp',display_number:2,clear_before:'yes'})
	GEN.selMoveOther({target_layer:'ol',invert:'no',dx:0,dy:0,size:0})






	// 保存 
	if(/yes/ig.test(par.auto_save)){
		GEN.checkInout({job:job,mode:"out"})  // 结束保存料号 关闭料号
		GEN.saveJob({ job: job });
		GEN.checkInout({job:job,mode:"in"})
		GEN.closeJob({job:job})
	} else {
		GEN.checkInout({job:job,mode:"in"})
	}

	if (mode === "aimdfm") {
		$.QDfm.updateRow({table: "pdm_aimdfm_task",data: {progress: 33.33},where: { id: $.task_id }});
		if (GEN.hasError()) {
			Status = 'error';resultData.push({ type: "error", title: "GEN错误!", detail: [{ desc: _.join(GEN.STATUS, "\n") }] });
			return {status: Status,result_data: resultData};
		} else {
			resultData.push({ type: "info", title: "操作完成, 请注意检查!" });
			return {status: Status,result_data: resultData};
		}
	}else {
		return "Done"
	}
} catch (e) {
	IKM.msg(_.join(GEN.STATUS, "\n"))
	IKM.msg(e)
    Status = 'error';
    resultData.push({type: "error", title: "脚本执行出错!", detail: [{desc: _.toString(e)}]});
    return (mode === "aimdfm") ? {status: Status, result_data: resultData} : "Error";
}

