
var $ = require('topcam.scriptfunc').argv();
var ikm = $.ikm;
var gen = $.gen;
var gui = $.gui;
var fs = require('fs');
var _ = require('lodash');
var Job = 'demo1', step = 'orig';
try {
    var sortRule = [  // 排序规则
        {name:'past_top',context:'board',type:'solder_paste',polarity:'positive'},
        {name:'silk_top',context:'board',type:'silk_screen',polarity:'positive'},
        {name:'sm_top',context:'board',type:'solder_mask',polarity:'positive'},
        {name:'top',context:'board',type:'signal',polarity:'positive'},
        {name:'layer_(\\d+)',context:'board',type:'signal',polarity:'positive'},
        {name:'bottom',context:'board',type:'signal',polarity:'positive'},
         {name:'sm_botm',context:'board',type:'solder_mask',polarity:'positive'},
         {name:'silk_bot',context:'board',type:'silk_screen',polarity:'positive'},
        {name:'past_botm',context:'board',type:'solder_paste',polarity:'positive'},
         {name:'array',context:'board',type:'drill',polarity:'positive'},
         {name:'l(\\d+)-\\d+',context:'board',type:'drill',polarity:'positive'},
         {name:'b(\\d+)-\\d+',context:'board',type:'drill',polarity:'positive'},
        {name:'outline',context:'board',type:'rout',polarity:'positive'},
        {name:'fab.art',context:'board',type:'rout',polarity:'positive'},
        {name:'top-enig',context:'board',type:'rout',polarity:'positive'},
        {name:'bot-enig',context:'board',type:'rout',polarity:'positive'},
        {name:'fab_page2',context:'board',type:'rout',polarity:'positive'}
    ];

    var matrix = gen.getMatrix({job:Job});
    var matriName = _.keys(matrix).sort(function(a,b){return matrix[a].row - matrix[b].row})

    var matrixFirst = matriName[0];  // 记录matrix中第一位
    var sortNames = [];
    var miscName = matriName.filter(function(name){  // 找出需要排序的名称列表 过滤出不用排序的名称 将其属性设置为misc
        var flag = true;
        sortRule.forEach(function(item,i){
            var evalReg = "/^"+item.name+"$/ig.test(name)";
            if(eval(evalReg)){
                flag = false;
                if(name === item.name){
                    var _item = JSON.parse(JSON.stringify(item));
                    _item.value = i;
                    sortNames.push(_item)
                } else {
                    var _item = JSON.parse(JSON.stringify(item));
                    _item.value = i;
                    var str = "/^"+ item.name +"$/ig.exec(name)"
                    _item.value2 = eval(str)[1] - 0;
                    _item.name = name;
                    sortNames.push(_item)
                }
            } 
        })
        return flag;
    })
    miscName.forEach(function(n){ 
        if(matrix[n].context == 'board'){
            gen.matrixLayerAttr({job:Job,layer:n,context:'misc'}) 
        }
    })
    sortNames = sortNames.sort(function(a,b){
        return a.value - b.value || a.value2 - b.value2
    })
    // 排序
    if(sortNames.length){
        if(sortNames[0].name !== matrixFirst) {  // 如果第一位和matrix中第一位不同，先把第一位插入到最前面
            gen.matrixMoveRow({ job:Job,layer:sortNames[0].name,before:matrixFirst })
        }
        // 排序
        sortNames.forEach(function (v,i,arr){
            var layer = matrix[v.name];
            if(i !== 0){
                // 判断是否需要排序
                if(layer.row-0 !== i+1){
                    gui.msg({name:v.name,row:layer.row,index:i,msg:"需要排序"})
                    gen.matrixMoveRow({ job:Job,layer:v.name,after:arr[i-1].name })             
                }
            }
            // 判断是否要设置属性
            if(v.context !== layer.context || v.type !== layer.layer_type || v.polarity !== layer.polarity){
                gen.matrixLayerAttr({job:Job,layer:v.name,context:v.context,type:v.type,polarity:v.polarity});
            }
        })
    }

    // 设置钻孔层的开始与结束
    var martrix = gen.getMatrix({job:Job});
    // 获取所有的钻孔层
    var drillLayer = Object.keys(martrix).filter(function(v){
        return martrix[v].layer_type == "drill" && martrix[v].context == "board"
    })
    // 获取所有single层
    var signalLayer = Object.keys(martrix).filter(function(v){
        return martrix[v].layer_type == "signal" && martrix[v].context == "board"
    })
    var layerCount = gen.getLayerCount({job:Job})
    function findSignal(num){
        var res = signalLayer.filter(function(v){
            var vnum;
            if(/\d/.test(v)){
                vnum = /(\d+)/ig.exec(v)[1] - 0;
            }
            return num === vnum
        })
        return res[0];
    }
    function doDrill(drills){  // 分析钻孔层
        return drills.map(function(v){
            var tmp = /(\d+).(\d+)/ig.exec(v);
            var start = tmp[1] == 1? 'top':findSignal(tmp[1]-0); 
            var end = tmp[2] == layerCount? 'bottom': findSignal(tmp[2]-0);
            return {start:start, end:end, layer:v}
        })
    }
    var drillSetList = doDrill(drillLayer);   // 分析得到钻孔设置结果
    drillSetList.forEach(function(v){
        gen.matrixLayerDrill({job:Job,layer:v.layer,start:v.start ,end:v.end})
    })

    return 'done';
}
catch (error) {
    gui.msg(error);
    return 'error';
}
