/*
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> ol转孔 </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;
require("topsin.genmath")
var zip = require('topsin.zip');
var GUI = $.gui || {};
var Job = $.job || $.job_name;
var JobId = $.job_id;
var db = $.db || IKM.db
var genMath = new GenMath();
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",
		rout: "ol"
	}
	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"});
    }
	var step = "unit"
	// var layer = "gto_font"
	// GEN.workLayer({name:layer,display_number:2,clear_before:'yes'})
	// var tmp_con = GEN.MOUSE({type:'r',text:"Please Select"});
	// GEN.COM("filter_area_strt")
	// GEN.COM("filter_area_xy,x="+tmp_con.x1+",y="+tmp_con.y1)
	// GEN.COM("filter_area_xy,x="+tmp_con.x2+",y="+tmp_con.y2)
	// GEN.COM("filter_area_end,layer=,filter_name=popup,operation=select,area_type=rectangle,inside_area=yes,intersect_area=no")
	// if(GEN.getSelectCount() > 0) {
	// 	var tmp_layer = layer + '_temp'
	// 	// 倾斜文字处理
	// 	// 1. 拷贝到辅助层 
	// 	if(GEN.isLayerExists({job:job, layer:tmp_layer})){GEN.deleteLayer({job:job, layer:[tmp_layer]})}
	// 	GEN.selCopyOther({dest:'layer_name',target_layer:tmp_layer}) 
	// 	GEN.workLayer({name:tmp_layer,display_number:2,clear_before:'yes'})
	// 	GEN.selCopyOther({dest:'layer_name',target_layer:"_ok"}) 
	// 	var limits = GEN.getLayerLimits({job:job,step:step,layer:tmp_layer, units:"mm"})
	// 	for (var key in limits) {
	// 		limits[key] = limits[key] - 0;
	// 	}
	// 	limits.xc = limits.xmin + limits.xsize/2
	// 	limits.yc = limits.ymin + limits.ysize/2

	// 	// 获取里面有几个字母 每一个字母的limits信息
	// 	GEN.selChangeSym({symbol:"r1"})
	// 	GEN.selContourize()
	// 	var feas = GEN.getFeatures({job:job,step:"unit",layer:tmp_layer,options:"feat_index",units:"mm"})
	// 	var limits_info = [];
	// 	feas.forEach(function(item) {
	// 		var index = item.index;
	// 		GEN.selLayerFeat({layer:tmp_layer, index:index,operation:"select"});
	// 		if(GEN.getSelectCount() > 0) {
	// 			var tmp_l = GEN.getLayerLimits({job:job,step:step,layer:tmp_layer, units:"mm", options:"select"})
	// 			for (var key in tmp_l) {
	// 				tmp_l[key] = tmp_l[key] - 0;
	// 			}
	// 			tmp_l.xc = tmp_l.xmin + tmp_l.xsize/2
	// 			tmp_l.yc = tmp_l.ymin + tmp_l.ysize/2
	// 			limits_info.push({index:index, limits:tmp_l })
	// 			GEN.selClearFeature()
	// 		}
	// 	})
	// 	var rodata = []
	// 	limits_info.forEach(function (item, i) {
	// 		if(limits_info[i+1]){
	// 			rodata.push(getRodate({
	// 				xs : item.limits.xc,
	// 				ys : item.limits.yc,
	// 				xe : limits_info[i+1].limits.xc,
	// 				ye : limits_info[i+1].limits.yc
	// 			}))
	// 		}
	// 	})
	// 	var angle = rodata.reduce(function(a,b) {return a + b}) / rodata.length;
	// 	if (Math.abs(angle) < 10) { angle = 0 }
	// 	GEN.workLayer({name:"_ok",display_number:2,clear_before:'yes'});
	// 	GEN.selTransform({mode:'anchor',oper:"rotate",x_anchor:limits.xc,y_anchor:limits.yc,angle:angle})
	// 	// 按照中心放大
	// 	var limits2 = GEN.getLayerLimits({job:job,step:step,layer:tmp_layer, units:"mm"})
	// 	for (var key in limits) {
	// 		limits2[key] = limits2[key] - 0;
	// 	}
	// 	limits2.xc = limits2.xmin + limits2.xsize/2
	// 	limits2.yc = limits2.ymin + limits2.ysize/2
	// 	GEN.selTransform({mode:'anchor',oper:'scale',x_anchor:limits2.xc,y_anchor:limits2.yc,x_scale:1.2,y_scale:1}) 
	// 	GEN.selTransform({mode:'anchor',oper:"rotate",x_anchor:limits.xc,y_anchor:limits.yc,angle:360 - angle})
	// }
	
	// IKM.msg(feas[0].feats)

    // var ret = genMath.profile2Polygon(feas[0].feats)
	// COM tools_tab_reset
	// COM tools_tab_add,num=1,shape=hole,type=via,min_tol=0,max_tol=1,bit=,drill_size=300
	// COM tools_tab_add,num=2,shape=hole,type=via,min_tol=0,max_tol=0,bit=,drill_size=500
	// COM tools_tab_add,num=3,shape=hole,type=plate,min_tol=0,max_tol=0,bit=,drill_size=700
	// COM tools_tab_add,num=4,shape=hole,type=plate,min_tol=0,max_tol=0,bit=,drill_size=800
	// COM tools_tab_add,num=5,shape=hole,type=plate,min_tol=0,max_tol=0,bit=,drill_size=900
	// COM tools_tab_add,num=6,shape=hole,type=plate,min_tol=0,max_tol=0,bit=,drill_size=1000
	// COM tools_tab_add,num=7,shape=hole,type=nplate,min_tol=0,max_tol=0,bit=,drill_size=1600
	// COM tools_tab_add,num=8,shape=hole,type=plate,min_tol=0,max_tol=0,bit=,drill_size=3000
	// COM tools_tab_add,num=9,shape=hole,type=nplate,min_tol=0,max_tol=0,bit=,drill_size=3300
	// COM tools_set,layer=drl,thickness=3235.96,user_params=,slots=no
	
	
	setTool({
		job:job, 
		step:step,
		layer:"drl_tmp",
		callback: function (toolinfo) {
			IKM.msg(toolinfo)
		}
	})
	
	

	// 保存 
	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";
}

function selCopyLayer(props){  // 拷贝选择的到辅助层
    var layer = props.layer
    var job = props.job
    if(GEN.isLayerExists({job:job,layer:layer})){
        GEN.deleteLayer({job:job,layer:layer})
    }
    GEN.selCopyOther({dest:'layer_name',target_layer:layer})
}

function getMinSym(sym) {
	var min_size;
	for (var key in sym) {
		var info = sym[key]
		if(info.size){info.size = Number(info.size)}
		if(!info.size) {
			var width = Number(info.width)
			var height = Number(info.height)
			info.size = width > height ? height : width;
		}
		if(info.size) {
			if(!min_size){min_size = info.size}
			else if (info.size < min_size) {
				min_size = info.size
			}
		}
	}
	return min_size
}

function getRodate(props){
    var xs = props.xs;
    var ys = props.ys;
    var xe = props.xe;
    var ye = props.ye;
    var y = ye - ys;
    var x = xe - xs;
    var r = Math.atan(y / x)
    return r*180/Math.PI
}

function setTool(props) {
	var job = props.job;
	var step = props.step;
	var layer = props.layer;
	var tool_info = GEN.getTool({job:job, step: step , layer:layer, units:"mm"})

	// 操作tool_info
	props.callback(tool_info)

	GEN.COM("tools_show,layer="+layer)
	GEN.COM("tools_tab_reset")
	var typehash = {
		non_plated:"nplate",
		plated:"plate",
		via:"via",
		laser:"via"
	}
	Object.keys(tool_info).forEach(function(key){
		var item = tool_info[key]
		if (item.shape == "hole") {
			GEN.COM("tools_tab_add,num="+key
			+",shape="+item.shape+",type="+typehash[item.type]+",min_tol="+item.min_tol+
			",max_tol="+item.max_tol+",bit=,finish_size="+item.finish_size+
			",drill_size="+item.drill_size+",combined=yes,orig_size=0")
		} else if (item.shape == "slot") {
			GEN.COM("tools_tab_add,num="+key+",shape=slot,type="+typehash[item.type]+",min_tol="+item.min_tol+",max_tol="+item.max_tol+",finish_size="+item.finish_size+
			",bit=,drill_size="+item.drill_size+",slot_len="+item.slot_len)
		}
	
	})
	GEN.COM("tools_set,layer="+layer+",slots=by_length")
}