/*
    NAME: 
    DESCRIPTION: 导入gerber数据
    PARAMETER:
	[
		{
			name : 'customer',
			title : 'CUSTOMER 名',
			type : 'LineEdit',
			property : {tool_tip : '客户名称'}
        },
        {
            name : 'job_name',
			title : '料号名',
			type : 'LineEdit',
			property : {tool_tip : '料号名'}
        },
        {
            name : 'path',
			title : '资料路径',
			type : 'LineEdit',
			property : {tool_tip : '客户资料所在路径'}
        }
    ]

    VERSION_HISTORY:
	V1.00 2020 3-30 Scott
	
    HELP:
	<html><body bgcolor="#DDECFE">
		<font size="3" color="#003DB2"><p>功能简介</p></font>
		  <p> 导入gerber数据</p>
		  <br>
		<font size="3" color="#003DB2"><p>参数配置</p></font>
		 <p> 导入gerber数据的规则 </p>
		<font size="3" color="#003DB2"><p>注意事项</p></font>
		  <p> ● 无 </p>
		  <br>
	</body></html>	
*/

// 引入模块 包
var $ = require('topcam.scriptfunc').argv();
var fs = require('fs');
var _ = require('lodash');
var IKM = $.ikm;
var GEN = $.gen;
var GUI = $.gui;
var Job = $.job;
    
try {
    // 获取脚本参数
	var par = $.par;

	// !!! tmp
	par = {
		customer: "ats",
		job_name: "1",
		path: "C:/Users/Alan/Desktop/Customer_1"
	}
	
    var parParams = ["customer", "job_name", "path"]; // par应该有的属性
    var isParExist = parParams.reduce(function (a, b) {
        if (!par.hasOwnProperty(b)) {
            a = false;
        }
        else if (par[b] == "") {
            switch (b) {
                case "job_name":
                    par.job_name = Job;
                    break;
            }
        }
        return a;
    }, true);
    if(!isParExist){throw "par error"} // 如果par没有parParams里的属性 就退出

	var cfg = JSON.parse(IKM.select_value({table:'pub_conf',field:'json_data',where:{path : 'cam/input_data'}}));  // 读取配置文件
	var customer = par.customer.split("_")[0].toLowerCase()
	var useCfg = cfg[customer];
	addDefaultCfg(cfg.def, useCfg) // 添加默认配置
	if(customer != par.customer.toLowerCase()){
		var cfgType =  cfg[par.customer.toLowerCase()]
		if(cfgType){ changeCfg(useCfg, cfgType) }
	}
    var job = par.job_name, path = par.path || useCfg.path, step = useCfg.step, err
    err = delSameJob({job:job, delSame:useCfg.delSameJob});  if(err){throw err}
	// 判断导入方式 处理path
	var jobPath = path + "/" + job
	if(!fs.exists(jobPath)){throw "path error"}
	var pathInfo = getPathInfo({path:jobPath, cfg: useCfg})  // 分析path下的文件
	if(!pathInfo.type){throw "file error"}   // pathInfo.type    "ODB"  or  "Gerber"
	var input_ok = false   // 判断是不是导入成功
	// 分支  导入ODB
	if(pathInfo.type == "ODB"){
		var odb = useCfg.ODB
		var fileInfo = getFileInfo({inputConfig:odb, path:jobPath, files:pathInfo.files}) // 获取导入文件信息
		if(/^yes$/ig.test(odb.isMerge) && fileInfo.length > 1){
            var err = mergeJob({odb:odb,job:job,fileInfo:fileInfo,delSameJob:useCfg.delSameJob})
            if(err){throw err}
        } else {
            var jobInfo = fileInfo.filter(function(v){return v.baseName == job})[0]
            if(jobInfo.length==0){throw "file error"}
            var err = importJob({name:job,db:odb.db,path:jobInfo.path},useCfg.delSameJob)
            if(err){throw err}
		}
		input_ok = true
	}
	// 分支  导入Gerber
	if(pathInfo.type == "Gerber"){
		var gerber = useCfg.Gerber
		// 如果要修改文件
		if(gerber.editFile && gerber.editFile.length){
			// 将文件拷贝一份到_tmp
			var tmpDir = path + "/" + job + "_tmp"
			if(!fs.exists(tmpDir)){fs.mkdir(tmpDir)}
			var srcFiles = []
			pathInfo.files.forEach(function(v){
				srcFiles.push(v)
				fs.copyFile(v.path,tmpDir + "/" + v.name,true)
			})
			jobPath = tmpDir
			pathInfo.files = fs.listDir(tmpDir,1)
			// 配置操作
			gerber.editFile.forEach(function(item){
				var filter = item.filter
				var fn = eval(item.callback)
				pathInfo.files.forEach(function(file){
					var reg = new RegExp(file.suffix, "ig")
					if(reg.test(filter)){
						fn.call({},{fs: fs, nowFile: file, srcFiles: srcFiles})
					}
				})
			})
		}
		var fileInfo = getFileInfo({inputConfig:gerber, path:jobPath, files:pathInfo.files}) // 获取导入文件信息
		// 导入gerber数据
		importGerber({job:job,step:step,gerber:gerber,fileInfo:fileInfo})
		input_ok = true
	}

	if(!input_ok){throw "input failed"}
	// end
	if(/^yes$/ig.test(useCfg.isDelComp)){  // 删除comp层
		var matrix = GEN.getMatrix({job:job}); 
		comp = Object.keys(matrix).filter(function(v){
			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()
		}
	}
	if(/^yes$/ig.test(useCfg.autoSave)){  // 自动保存
		GEN.checkInout({job:job,mode:"out"})
		GEN.saveJob({ job: job });
	}
	GEN.checkInout({job:job,mode:"in"})
	GEN.closeJob({job:job})
	
    return 'Done';
}
catch (error) {
	IKM.msg(error)
    return 'Error';
}

function addDefaultCfg(def, use) {
    for (var key in def) {
        var val = def[key]
        if (typeof val == "string" && !use.hasOwnProperty(key)) {
            use[key] = val
        } else if (typeof val == "object" && use.hasOwnProperty(key)) {
            if (!use[key].hasOwnProperty("db")) {
                use[key].db = val.db
            }
            if (!use[key].hasOwnProperty("files")) {
                use[key].files = val.files
            }
        }
        if (key == "Gerber" && use.hasOwnProperty(key)) {
            for (var gkey in val.format) {
                if (!use[key].hasOwnProperty("format")) {
                    use[key].format = val.format
                } else if (!use[key].format.hasOwnProperty(gkey)) {
                    use[key].format[gkey] = val.format[gkey]
                }
            }
		}
		if (key == "ODB" && !use.hasOwnProperty(key)){ use.ODB = val }
    }
}
function changeCfg(useCfg,cfgType){
	for(var key in cfgType){
		var value = cfgType[key]
		if(key == "Gerber"){
			changeCfg(useCfg.Gerber, cfgType.Gerber)
		} else {
			useCfg[key] = value
		}
	}
}
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 getPathInfo(props){
	var path = props.path
	var cfg = props.cfg
	var res = {}
	res.files = fs.listDir(path)
	res.fileSuffix = res.files.reduce(function(a,b){
		if(b.isFile && a.indexOf(b.suffix)<0){
			a.push(b.suffix)
		}
		return a
	},[])
	if(cfg.Gerber){
		res.type = cfg.Gerber.files.reduce(function(a,b){
			if(res.fileSuffix.indexOf(b) >= 0){
				a = true
			}
			return a 
		}, false)? "Gerber" : undefined
	}
	if(cfg.ODB){
		res.type = cfg.ODB.files.reduce(function(a,b){
			if(res.fileSuffix.indexOf(b) < 0){
				a = false
			}
			return a 
		}, true)? "ODB" : res.type
	}
	return res
}
function getFileInfo(props){
	var inputConfig = props.inputConfig, path = props.path, files = props.files
	var fileInfo = files.reduce(function(a,b){
		if(inputConfig.files.indexOf(b.suffix)>=0){
			a.push({
				name:b.name,
				baseName: b.baseName,
				completeBaseName: b.completeBaseName,
				completeSuffix: b.completeSuffix,
				path: b.path,
				suffix: b.suffix
			})
		}
		return a
	},[])
	return fileInfo
}

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);
}

function mergeJob(props){
    var odb = props.odb
    var job = props.job
    var fileInfo = props.fileInfo
    var arrJobName = odb.jobNameRule.replace("(job)", job)
    var jobInfo = fileInfo.filter(function(v){return v.baseName == job})[0]
    var arrJobInfo = fileInfo.filter(function(v){return v.baseName == arrJobName})[0]
    if(!jobInfo){ return "file error" }
    if(!arrJobInfo){ return "file error" }
    var jobInfos = [jobInfo, arrJobInfo]
    for(var i = 0;i<jobInfos.length;i++){
        var err = importJob({name:jobInfos[i].baseName,db:odb.db,path:jobInfos[i].path},props.delSameJob)
        if(err){return err}
    }
    // 合并操作
    jobInfos.forEach(function(v){GEN.openJob({job:v.baseName})})
    GEN.copyStep({
        source_job:arrJobInfo.baseName,
        source_name:odb.arrStep,
        dest_job:jobInfo.baseName,
        dest_name:odb.arrStep,
    });
    GEN.closeJob({ job: arrJobInfo.baseName });
    GEN.deleteJob({ job: arrJobInfo.baseName });
}
function importGerber(props){
	var fileInfo = props.fileInfo
	var gerber = props.gerber
	var job = props.job
	var step = props.step
	var gerberFiles = fileInfo.filter(function(file){return gerber.gerberConfig.hasOwnProperty(file.suffix)})
	var gerberInfo = gerberFiles.map(function(item){
		var gerberConfig = gerber.gerberConfig[item.suffix] || {}
		var gerberItem = {
			layer: item.name.toLowerCase(), path: item.path,
			format: gerber.format[item.suffix] || "Excellon2",
			job:job,step:step
		}
		for (var key in gerberConfig) {
			gerberItem[key] = gerberConfig[key]
		}
		return gerberItem
	})
	// 创建料号和step
	GEN.createJob({name:job,db:gerber.db})
	GEN.createStep({job:job,name:step})
	// 分析geber配置
	GEN.COM("input_manual_reset")
	gerberInfo.forEach(function(v){
	    GEN.COM("input_manual_set",v)
	})
	GEN.COM("input_manual")
}

