var fs = require('fs')
var util = require('./util.js')
var parser = require('topsin.parser');
var config = require('./config.js')
var db = require('topsin.database');
//  创建数据库连接
db.addConnection(config.dbconfig, "Scott_PMO_TRAINING");
// 表名
var tablename = 'sec_production_order_confirmation_2'
var query = db.query('Scott_PMO_TRAINING');

function init(){
    // 获取文件列表 提取出csv后缀的文件
    var list = util.readDir('../resource','csv')  
    // 对文件名md5加密 获取加密后的文件名列表
    var csvs = list.map(function(v){
        return util.crypto('md5',v.name) 
    })
    // 获取temp.json的内容
    var temp = JSON.parse(fs.readFile('./temp.json'))
    // 过滤掉已经写入的文件,更新json文件
    var newcsvs = csvs.filter(function(v){
        if(temp.csvs.indexOf(v) < 0){
            // 将它加入json的csvs
            temp.csvs.push(v)
            return v
        }
    })
    // 判断是否继续执行
    var isContinue = false
    var type = []
    if (config.keys.length !== temp.keys.length){
        type.push(0)
        isContinue = true // 字段增加的情况 要执行更新字段的操作
        temp.keys = config.keys
    }
    fs.writeFile('./temp.json',JSON.stringify(temp)) // 覆盖写入json
    // 判断是否有新增的文件 或者字段是不是没增加 没有则
    if(newcsvs.length !== 0){
        type.push(1)
        isContinue = true
    }
    if(isContinue){
        main({
            list: list,  // 所有的文件
            newcsvs: newcsvs,  // 本次新增的文件
            type: type  // 操作类型(更新字段,新增数据,同时进行)
        })
    }
}

function main(props){
    var sqldata = SqlDatas()
    if(props.type.length === 1 && props.type[0] === 0){
        console.log('只要更新字段')
    }else{
        // 获取需要加密的文件
        var list = props.list.filter(function(v){
            return props.newcsvs.indexOf(util.crypto('md5',v.name)) >= 0
        })
        var datas = []
        list.forEach(function(v){
            // 合并文件的所有数据
            datas = datas.concat(getCsvData(v.dir + '/' + v.name)) 
        });
        if(props.type.length === 1){
            console.log('新增数据')
            InsertData(datas,sqldata)
        }else{
            console.log("更新字段和新增")
        }
    }
    
}


function SqlDatas(){
    return query.selectArrayMap({
        table:tablename,
        field: '*',
        field_format:{"tags":'array', attr_data:'json'}
    });
}

function InsertData(datas,sqldata){
    
    // console.log(sqldata)
    // console.log(datas)
    console.log(query.getFieldList(tablename))
}








function getCsvData(path){
    var csvdata = parser.parseCsvStr(fs.readFile(path));   // 获取csv数组
    csvdata.shift();  // 除去第一行
    return csvdata
}




init()


db.removeConnection('Scott_PMO_TRAINING');