
// 引入模块 包
var $ = require('topcam.scriptfunc').argv();
var fs = require('fs');
var _ = require('lodash');
var IKM = $.ikm;
var GEN = $.gen;
var GUI = $.gui;
var Job = $.job;
var JobId = $.job_id;
var Status = 'ok';
var resultData = [];
try {
	// var config = require("../config.js")   // 读取配置文件 config
	var cfg = IKM.select_value({table:'pub_conf',field:'text_data',where:{path : 'cam/input_data'}})  // 拿到框架中的系统配置
	if (!cfg || cfg == ""){throw "cfg can not find"}  
	var par = {    // ??? 通过某种方式拿到料号和客户名
		job:"i4",
		customer: "Customer_2"   // Customer_1 || Customer_2 || New_data
	}
	var config = eval(cfg)
	var job = par.job || Job;
    if(_.isEmpty(job)) throw "没有传入料号名!";
	job = job.toLowerCase()
	// 如果genesis已经存在这个料号
	err = delSameJob({job:job,delSame:config.delSameJob}); if(err){throw err};
	var custCfg = config.customer[par.customer]
	if(!custCfg){throw "config error"}
	var step = custCfg.step.toLowerCase()
	// 获取路径下文件信息
	var path = par.path || custCfg.path
	var pathInfo = fs.listDir(path, 1)
	// 判断存不存在料号文件
	var jobFile = pathInfo.filter(function(v){return v.baseName.toLowerCase() == job})
	if(jobFile.length == 0){throw "job file is not exist"}
	var jobFiles = []  // 记录要分析的文件
	if (!jobFile[0].isDir) {
		jobFiles.push(jobFile[0])
	} else {
		jobFiles = fs.listDir(jobFile[0].path)
	}
	// 分析料号文件 得到料号导入信息 导入类型
	var jobInfo = analyJobFiles({jobFiles:jobFiles.filter(function(v){return v.isFile}),custCfg:custCfg,config:config,job:job })
	// IKM.msg(jobInfo.data.map(function(v){return v.format}))
	if(jobInfo.data.length == 0){throw "file error"}
	var importOk = false;  // 是否成功导入
	if(/odb/ig.test(jobInfo.type)){  // odb导入
		if(jobInfo.data.length == 1){  // 只分析到一个tgz文件 直接导入
			var err = importJob({name:job,db:custCfg.db,path:jobInfo.data[0].file.path},config.delSameJob)
			if(err){throw err}
		} else {  // 多个tgz文件 说明需要合并
			var mergeFiles = jobInfo.data.filter(function(item){
				var err = importJob({name:item.file.baseName,db:custCfg.db,path:item.file.path},config.delSameJob)
				if(err){throw err}
				return /yes/ig.test(item.format.isMerge)
			})
			var arr_job = mergeFiles[0]
			var arr_step;
			var steplist = GEN.getStepList({job:arr_job.file.baseName})
			if(steplist.indexOf(arr_job.format.arrStep) < 0){
				arr_step = steplist[0]
			}else{arr_step = arr_job.format.arrStep}
			GEN.openJob({job:job});
			GEN.openJob({job:arr_job.file.baseName});
			GEN.copyStep({  // 合并
				source_job:arr_job.file.baseName,
				source_name:arr_step,
				dest_job:job,
				dest_name:arr_step,
			});
			GEN.closeJob({ job: arr_job.file.baseName });
			GEN.deleteJob({ job: arr_job.file.baseName });  // 合并后 删除array的料号
		}
		importOk = true
	}

	if(/gerber/ig.test(jobInfo.type)){  // gerber导入
		GEN.createJob({name:job,db:custCfg.db})
		GEN.createStep({job:job,name:step})
		var gerberInfo = jobInfo.data.map(function(item){
			var gerberCfg = JSON.parse(JSON.stringify(item.format));
			var file = item.file
			gerberCfg.layer = file.name.toLowerCase()
			gerberCfg.path = file.path
			gerberCfg.format = item.type
			gerberCfg.job = job
			gerberCfg.step = step
			return gerberCfg
		})
		GEN.COM("input_manual_reset")
		gerberInfo.forEach(function(v){
			GEN.COM("input_manual_set",v)
		})
		GEN.COM("input_manual")
		importOk = true
	}

	if(!importOk){throw "import error"}

	// 导入结束
	var matrix = GEN.getMatrix({job:job}); 
	comp = Object.keys(matrix).filter(function(v){  // 如果有comp层 删除
		return /^comp_\+_/ig.test(v)
	})
	if (comp.length > 0){
		var tmp = GEN.getStepList({job:job})
		GEN.openStep({job:job,name:tmp[0]})
		GEN.COM("delete_comp")
		GEN.closeStep()
	}

	// !!!! tmp
	// GEN.checkInout({job:job,mode:"out"})  // 结束保存料号 关闭料号
	// GEN.saveJob({ job: job });
	// GEN.checkInout({job:job,mode:"in"})
	// GEN.closeJob({job:job})

    return 'Done';
}
catch (error) {
	GUI.msg(error)
    return 'Error';
}
function delSameJob(props){
    var job = props.job
    var delSame = props.delSame
    if(GEN.isJobExists({job:job})){   
        if(/^yes$/ig.test(delSame)){
            if(GEN.isJobOpen({job:job})){ GEN.closeJob({job:job}) }
            GEN.deleteJob({job:job})
        } else {
            return "job "+ job+ " exist"
        }
    }
}
function analyJobFiles(props){
	var files = props.jobFiles;
	var config = props.config;
	var job = props.job;
	var custCfg = props.custCfg;
	var rules = custCfg.rules;
	var paramsFile = files.filter(function(file){return /param/ig.test(file.baseName)})
	var tmp_hash = {}
	paramsFile.forEach(function(file){
		tmp_hash[file.baseName] = (function(){
			var tmparr = fs.readFile(file.path).split("\n")
			var tmp = {}
			tmparr.map(function(v){
				var arr = v.split(/\b\s+\b/)
				tmp[arr[0].replace(/-/ig,"_")] = arr[1]
			})
			return tmp
		})() 
	})
	
	var fileInfo = files.reduce(function(a,file){
		try {
			rules.forEach(function(item){
				if(item.valid({file:file, job:job})){
					var format = config.formats[item.format]
					var format1;
					if(item.format_params){
						format1 = item.format_params({params:tmp_hash})
					}
					if(format1){
						throw {file:file,type:item.type,format:format1}
					}else{
						throw {file:file,type:item.type,format:format}
					}
				}
			})
		} catch (info) { 
			a.push(info)
		}
		return a
	},[])
	var odbfiles = fileInfo.filter(function(item){return /odb/ig.test(item.type)})
	if(odbfiles.length == 0){
		return {
			type: "Gerber",
			data: fileInfo
		}
	} else {
		return {
			type: "ODB",
			data: odbfiles
		}
	}
}
function importJob(props,delSameJob){
    var name = props.name
    if (GEN.isJobExists({ job: name })) {
        if (/^yes$/ig.test(delSameJob)) {
            if(GEN.isJobOpen({ job: name })){ GEN.closeJob({ job: name }); }
            GEN.deleteJob({ job: name });
        }
        else {
            return "job "+name+" exist";
        }
    }
    GEN.importJob(props);
}


