/*
NAME: 
DESCRIPTION: 锣带输出;
PARAMETER:
    [
		{
			name : 'Outpath',
			title : '导出路径',
			type : 'LineEdit',
			property : {tool_tip : '导出路径'},
		},
		{
			name : 'step',
			title : '工作step',
			type : 'LineEdit',
			property : {tool_tip : '工作step'},
		},
		{
            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 } });
	}
}
require("topsin.genmath")
var genMath = new GenMath();
var gui = new NewGUI(GUI);
var Status = 'ok';
var resultData = [];
var par = PAR;
var default_par = {
    Outpath:"C:/Users/Administrator/Desktop/jobs/demo",
	auto_save: "No",
	step:"step",
	units:"mm"
}
for(var key in default_par){ if (!par.hasOwnProperty(key) || par[key] == ""){ par[key] = default_par[key] }}
var job = Job;
var Step;
var rou_layer = [];

try {
	if(_.isEmpty(job)){throw "参数job不存在"} else { job = job.toLowerCase() }
	if(!GEN.isJobExists({job:job})){throw "料号"+job+"不存在"}
	
	// 选择工作step
	var workstep = getWorkStep()
	if(workstep.length == 0){throw "未找到工作step"}
	
	workstep.forEach(function(step){
		Step = step;
		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();


		var matrix = GEN.getMatrix({job:Job});
		Object.keys(matrix).forEach(function(layer){
			if(matrix[layer].context && matrix[layer].context == 'board' ){
				if(matrix[layer].layer_type == 'rout'){
					rou_layer.push(layer)
				}			
			}
		})
		
		if(rou_layer.length) {
			var info = confirm_gui({layers:rou_layer});
			
			output_rou({job:Job,step:step,info:info});
			
			input_layers({job:Job,step:step,info:info});
		}
	})
	



	// 保存 
	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 NewGUI (gui) {
    this.msgBox = function(props){ // title  type  content  button
        props = props || {}
        return gui.msgBox(props.title || "title",props.type || "info",props.content || "content",props.button || ["ok", "cancel"]);
    }
    this.selectFromTreeview = gui.selectFromTreeview
    this.selectFile = function(props){ // "choose something", "*", true, "file", "/home/abby/fast_io"
        props = props || {}
        return gui.selectFile(props.title || "choose something",props.filter || "*",props.multiple || false, "file","");
    }
    this.selectSingle = function(props) {
        props = props || {}
        return gui.selectSingle({
            "title": props.title || "select",
            "list": props.list || [],
            "default": props["default"] || "",
            "columns": props.columns || 2,
            "gen":props.gen || GEN
        });
    }
    this.selectMultiple = function(props) {
        props = props || {}
        return gui.selectMultiple({
            "title": props.title || "select",
            "list": props.list || [],
            "defaultvalue": props["defaultvalue"] || [""],
            "defaultsize": props["defaultsize"] || [200, 100],
            "columns": props.columns || 2,
            "gen":props.gen || GEN
        });
    }
    this.selectFromTable = gui.selectFromTable
    this.snapScreen = gui.snapScreen
    this.imageViewer = gui.imageViewer
    this.inputBox = gui.inputBox
    this.showForm = gui.showForm
    this.lockUnlockLayer = function(props){
        props = props || {}
        var tmp = {}
        if (props.matrix) {
            for (var key in props.matrix) {
                var item = props.matrix[key]
                tmp[key] = {
                    row : item.row,
                    name : item.name
                }
            }
        }
        return gui.lockUnlockLayer({
            title: props.title || "lockUnlockLayer",
            layermatrix:props.layermatrix || tmp 
        })
    } 
    this.passwordBox = function(props){
        props = props || {}
        return gui.passwordBox({title:props.title || "password", password:props.password || "1212"})
    } 
    this.selectJobLayer = function (props) {
        props = props || {}
        return gui.selectJobLayer({
            layertypelist: props.layertypelist || [
                {name: "all", display_name: "all", filter: function(x) { return x }},
                {name: "signal", display_name: "signal", filter: function(x) { return x["layer_type"] === "signal"; }},
                {name: "power_ground", display_name: "power_ground", filter: function(x) { return x["layer_type"] === "power_ground"; }},
                {name: "mixed", display_name: "mixed", filter: function(x) { return x["layer_type"] === "mixed"; }},
                {name: "solder_mask", display_name: "solder_mask", filter: function(x) { return x["layer_type"] === "solder_mask"; }},
                {name: "silk_screen", display_name: "silk_screen", filter: function(x) { return x["layer_type"] === "silk_screen"; }},
                {name: "solder_paste", display_name: "solder_paste", filter: function(x) { return x["layer_type"] === "solder_paste"; }},
                {name: "drill", display_name: "drill", filter: function(x) { return x["layer_type"] === "drill"; }},
                {name: "rout", display_name: "rout", filter: function(x) { return x["layer_type"] === "rout"; }},
                {name: "document", display_name: "document", filter: function(x) { return x["layer_type"] === "document"; }}
            ],
            //defaultlayertype: "ha",
            joblist: props.joblist || [],
            defaultJob: props.defaultJob || [], // select by default
            steplist: props.steplist || [],
            // defaultstep: "step3",
            showstep: props.showstep || true,
            selectmode: props.selectmode || "multiple", // single/multiple
            layermatrix: props.layermatrix || {  },
            defaultlayer: props.defaultlayer || []
        })
    }
}

function getWorkStep(props){
	var steplists = GEN.getStepList({job:job});
	if(steplists.length == 0){return "该料号没有step"}
	var steps_tmp = steplists.filter(function(name){
		var reg = new RegExp(par.step, "ig")
		return reg.test(name)
	})
	if(steplists.length == 0){return "根据脚本参数过滤出来的step不存在，请检查资料或者脚本参数配置！"}
	var workstep = gui.selectMultiple({
		title: "请先择工作step",
		size:[200,100],
		defaultsize:[200,100],
		list: steplists.map(function(v){ var tmp = {}; tmp[v] = v ;return tmp}),
		defaultvalue: steps_tmp,
		columns: 1,
		gen: GEN
	})
	if(workstep.length == 0 ) {return "没有先择step"}
	return workstep
}

// rou输出
function output_rou(par) {
	var info = par.info;
	// var PL = GEN.getProfileLimits({job:Job,step:Step,units:'mm'});
	var nc_set = 'zda';
	var machine = 'sintai_excellon';
	var layers = [];
	for (var key in info.layer_info) {
		layers.push(info.layer_info[key])
	}
	layers.forEach(function(layer){
		if(/^yes$/i.test(layer.output_flag)){
			if(GEN.getNcsetsList({job:Job,step:Step,layer:layer.layer_name}).indexOf(nc_set) >= 0) {
				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:layer.layer_name});
			GEN.COM('ncrset_delete',{name:nc_set});
		}
	})
}

// 用户配置参数
function confirm_gui(par) {
	var rows={},n=0;
	// var cam = IKM.get_jobinfo({jobname:Job,jobid:JobId,jobcategory:'work',jobinfo:'cam_serial_number',withspec:1});
	var folder = 'rou';
	var path = PAR.Outpath+"/"+folder;
	fs.mkdir(path)
	par.layers.forEach(function(layer){
		n++;
		rows[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';
	})
	rows.output_path = path;
	// var v_data = GUI.showForm({
	// 	title:"Rou输出参数确认单",
	// 	defaultsize:[520,500],
	// 	items: [
	// 		{
	// 			type : 'title',
	// 			property:{
	// 				title:'输出料号和名称',
	// 			},	
	// 			n_columns:2,
	// 		},
	// 		{
	// 			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 : function(par){
	// 				var data = par.value;
	// 				Object.keys(data).forEach(function(row_name){
	// 					Object.keys(data[row_name]).forEach(function(col_name){
	// 						par.widget.set_value(row_name,col_name,data[row_name][col_name]);
	// 					})
	// 				})
	// 			},
	// 			get_value_func : function(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:function(par){
	// 						var folder = GUI.select_file({title:'选择路径',type:'select-folder',defaultdir:PAR.Outpath});
	// 						if(!folder){return}
	// 						p.formpanel.set_value('output_path', folder);
	// 					}
	// 				},
	// 			],
	// 		},
	// 	]
	// });
	return rows;
}

// 文件导入设置
function input_layers(par) {
	var info = par.info;
	var layers = [];
	for (var key in info.layer_info) {
		layers.push(info.layer_info[key])
	}
	layers.forEach(function(lyr){
		if(/yes/i.test(lyr.output_flag)){
			var name = info.output_path+'/'+lyr.layer_name;
			var layer= lyr.layer_name.toLowerCase();
			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="+par.job+",matrix=matrix,layer="+layer+",context=misc");
		}
	})
}