/*
NAME: 
DESCRIPTION: ;
PARAMETER:
    [
		{
			name : 'ref_outline',
			title : '参考层',
			type : 'LineEdit',
			property : {tool_tip : '参考层,默认是gm1'},
		},
		{
			name : 'outline',
			title : '外形层',
			type : 'LineEdit',
			property : {tool_tip : '外形层,默认是gko'},
		},
		{
			name : 'outline_width',
			title : '外形线宽',
			type : 'LineEdit',
			property : {tool_tip : '外形线宽,默认是0.2mm'},
		},
		{
            name : 'auto_save',
			title : '自动保存',
            type : 'RadioBox',
            property : {
				item_list:[
					{name:'yes',text:'YES'},
					{name:'no',text:'NO'},
				],
				tool_tip:'是否自动保存料号开关'
			}
        }
	]
	
 VERSION_HISTORY:
	V1.00 2020-04-20 Scott Sun
	    1.新版本
		
 HELP:
 	<html><body bgcolor="#DDECFE">
		<font size="3" color="#003DB2"><p>功能简介</p></font>
		<p> 创建GKO </p>
		<br>
		<font size="3" color="#003DB2"><p>参数配置</p></font>
		<p> 客户配置 </p>
		<br>
		<font size="3" color="#003DB2"><p>注意事项</p></font>
		<p> 无 </p>
		<br>
	</body></html>	
*/
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
console.log("==============================>create_outline");
// 引入模块 包
var $ = require('topcam.scriptfunc').argv();
var fs = require('fs');
var _ = require('lodash');
var database = require("topsin.database");
database.addConnection($.conf.database_conf, "DFM");
var QDfm = database.query("DFM");
if ($.conf.product_type == "aimdfm") {
	QDfm.updateRow({
		table: "pdm_aimdfm_task",
		data: {
			current_process_title: $.process_title
		},
		where: { id: $.task_id }
	});
}
var GEN = $.gen;
var Job = $.job_name;
var db = $.db
var Status = 'ok';
var resultData = [];
var PAR = {};
if ($.hasOwnProperty('script_parameter')){
	PAR = JSON.parse($.script_parameter);
}

try {
    var par = PAR;
	var default_par = {
		ref_outline: "gm1",
		outline: "gko",
		outline_width: "0.2mm",
		auto_save: "No",
	}
	for(var key in default_par){  // 设置默认属性
		if (!par.hasOwnProperty(key) || par[key] == ""){
			par[key] = default_par[key]
		}
	}
	var outline_symbol;
	if(par.outline == "" || par.outline == undefined || par.outline == null || par.outline == "null"){
		outline_symbol = "null";
	} else {
		par.outline_width = parseFloat(par.outline_width)
		outline_symbol = "r" + String(par.outline_width * 1000);
	}
	
	var ref_outline = par.ref_outline;
	var outline = par.outline;
	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}) }
	// 检查料号是否能够check out
	if(GEN.checkInout({job:job,mode:"test"}) != 0){ throw "the job check" }
    GEN.checkInout({job:job,mode:"out"});
	// 判断参考层（ref_outline）是否存在并不为空
	var is_outline_exist = GEN.isLayerExists({job:job,layer:outline})
	if(!GEN.isLayerExists({job:job,layer:ref_outline})){
		if(!is_outline_exist){
			throw "外形层不存在"
		}
	}
	var steplist = GEN.getStepList({job:job})
	if(!is_outline_exist){
		steplist.forEach(function(step){
			if(!GEN.isLayerEmpty({job:job,step:step,layer:ref_outline})){
				// 创建新的外形层（outline）
				GEN.openStep({job:job,name:step})
				GEN.createLayer({job:job,layer:outline,conext:"board",type:"rout"})
				// 将参考层copy到外形层中
				GEN.selClearFeature()
				GEN.workLayer({name:ref_outline,display_number:2,clear_before:'yes'})
				GEN.selAllFeat()
				GEN.selCopyOther({dest:"layer_name", target_layer:outline})
				GEN.closeStep()
			}
		})
	}
	
	steplist.forEach(function(step){
		// 修改外形层
		GEN.openStep({job:job,name:step})
		GEN.affectedLayer({affected:'no',mode:'all'})
		GEN.selClearFeature()
		GEN.workLayer({name:outline,display_number:2,clear_before:'yes'})
		if(outline_symbol != "null"){
			GEN.selChangeSym({symbol: outline_symbol})
		}
		GEN.selCreateProfile()
		GEN.clearLayers()
		GEN.closeStep()
	})


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


    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
		};
	}
} catch (e) {
    Status = 'error';
    resultData.push({type: "error", title: "脚本执行出错!", detail: [{desc: _.toString(e)}]});
    return {status: Status, result_data: resultData};
}