var _ = require('lodash');
var process = require('process');
var fs = require('fs');
var Err = require('topsin.error');
var Gen = require('topcam.gencom');
var options = require('minimist')(process.argv);
var ARGV = options['_'];
var crypto = require('topsin.crypto');
var os = require('os');
var IKM = require('topcam.ikm6')();
var GUI = require('topsin.gengui').newGui();
var logger = require('topsin.logger');
/*logger.loadConfig({
    'appender': {
        console: {
            'type': 'console',
            'typefilter': 'ERROR,WARN,FATAL,INFO', // 日志分类 *代表所有
            'categoryfilter': '*', // 模块分类
            'format': '{TIME} [{TYPE}]-({CATEGORY}):{MSG} <{THREAD}>@{FILE}:{LINE}/{FUNC}' //自定义输出样式
        }
    }
});
*/
GUI.msg = function(data){  
    var tmp = data;
    var type = {}.toString.call(data).split(" ")[1];
    if (/^(\[object Object\]|\[object Array\]|\[object Error\])$/ig.test({}.toString.call(data))) {
        data = JSON.stringify(data)
    } else if (/^\[object Function\]$/ig.test({}.toString.call(data))){
        data = data.toString()
    }
    type = type.replace("]","")
    if(tmp === undefined){type = 'undefined',data = 'undefined'}
    GUI.msgBox("数据类型："+type, "info", data);
    return this
}

var APP = IKM.getAPP();

var SCRIPT_RETURN, USER_NAME, USER_FULLNAME, USER_ID, GEN, LANG, JOB, STEP, JOB_ID, RUN_MODE, PAR, RUN_DATA, GEN_TYPE,REAL_BIN;

var CONF = JSON.parse(fs.readFile(process.argv[1]));

if (ARGV.length == 0 || _.isEmpty(ARGV[0])) {
    print("\nError: No Args passed to  prog. Exiting...\n");
    throw new Error("Error: No Args passed to  prog. Exiting...");
}
var ARGS = {};

try {
    ARGS["socket"] = ARGV[2];
    ARGS["job_id"] = ARGV[3];
    ARGS["process_id"] = ARGV[4];
    ARGS["script_id"] = ARGV[5];
    ARGS["user"] = ARGV[6];
    ARGS["gen_type"] = ARGV[7];
    ARGS["data"] = ARGV[8];
    //
    GEN = new Gen({ cam_type: ARGS["gen_type"] });
    USER_NAME = ARGS["user"];
    if (_.isEmpty(USER_NAME)) USER_NAME = GEN.getUserName();
    var userinfo = IKM.crud('selectMap',{
        table: 'sys_user',
        field: ['id', 'fullname'],
        where: { username: USER_NAME }
    })
    
    USER_ID = userinfo["id"];
    USER_FULLNAME = userinfo["fullname"];
    GEN_TYPE = ARGS["gen_type"];
    JOB = process.getEnv('JOB');
    STEP = process.getEnv('STEP');
    JOB_ID = ARGS["job_id"];
    JOB = IKM.crud('selectValue',{
        table: 'pdm_job',
        field: "jobname",
        where: { id: JOB_ID }
    })
    SCRIPT_RETURN = _do_script(IKM.get_script_by_id(ARGS["script_id"]));
}
catch (err) {
    IKM.msg(err);
    logError(err);
}
finally {
    //程序结束
    tl_end();
}

function logError(msg) {
    print("ERROR:" + _.toString(msg));//+ "\nbacktrace:" + _.join(backtrace(), "\n"));
}

function tl_end() {
    var status;
    if (_.isEmpty(SCRIPT_RETURN)) SCRIPT_RETURN = 'Error';
    if (/^done/i.test(SCRIPT_RETURN)) {
        status = 'Done';
    }
    else if (/^cancel/i.test(SCRIPT_RETURN)) {
        status = 'Cancel';
    }
    else if (/^warning/i.test(SCRIPT_RETURN)) {
        status = 'Warning';
    }
    else if (/^finish/i.test(SCRIPT_RETURN)) {
        status = 'Finish';
    }
    else if (/^critical/i.test(SCRIPT_RETURN)) {
        status = 'Critical'
    }
    else if (/^new/i.test(SCRIPT_RETURN)) {
        status = 'New'
    }
    else {
        status = 'Error';
    }

    if (ARGS["socket"]) {
        var end_time = os.getNow();
        var tmp = {
            job_id: JOB_ID,
            process_id: ARGS["process_id"],
            end_time: end_time,
            user_name: USER_NAME,
            user_id: USER_ID,
            status: status
        }
        if (ARGS["job_id"]){
            tmp.notes = ARGS["job_id"] > 0 ? USER_FULLNAME + status + " script (jobname="+JOB+",jobid="+ARGS["job_id"]+")" : ''
        };
        IKM.update_job_workflow_log(tmp);
        IKM.script_end(JOB_ID,ARGS["process_id"]);
    }
}

function doScript(argv){
    return _do_script({name:argv})
}

function _do_script(argv) {
    var script_name = argv["name"];
    var scrinfo = IKM.crud('selectMap',{
        table: 'pdm_workprocess_script',
        field: ['id', 'md5', 'type', 'encrypt', 'content', 'parameter_value'],
        where: { name: script_name, status: 'released' }
    })
    var func = '';
    var scrfile = CONF.script_dir + "/" + script_name + ".js";
    if (CONF.debug_mode == true && fs.fileExists(scrfile)) {
            func = evalfile(scrfile, { prefix: "(function(){\n", suffix: "\n})"});
    } else {
        if (_.isEmpty(scrinfo.content)) {
            print(_.toString(scrinfo))
            throw "script content is Empty!";
        }
        else {
            if (scrinfo.encrypt == 1) {
                func = evalstr(crypto.d(scrinfo.content,{ prefix: "(function(){\n", suffix: "\n})" }));
            }
            else if (scrinfo.encrypt == 2) {
                func = evalstr(crypto.d2(scrinfo.content), { prefix: "(function(){\n", suffix: "\n})"});
            }
            else if (scrinfo.encrypt == 3) {
                func = evalstr(crypto.d3(scrinfo.content, { prefix: "(function(){\n", suffix: "\n})" }));
            }
            else {
                func = evalstr(content, { prefix: "(function(){\n", suffix: "\n})" });
            }
        }
    }
    if (!_.isFunction(func) && argv.doScriptType !== 2) {
        throw "script " + script_name + " eval error!";
    }
    var jobinfo = IKM.crud('selectMap',{
        table: 'pdm_job',
        field: ['id AS job_id', 'jobname AS job_name'],
        where: { jobname: JOB }
    })
    
    var params_info = {};
    params_info.gen = GEN;
    params_info.ikm = IKM;
    params_info.conf = CONF;
    params_info.id = JOB_ID;
    params_info.script_name = script_name;
    params_info.user_name = USER_NAME
    params_info.user_id = USER_ID;
    params_info.user_full_name = USER_FULLNAME;
    params_info.job = JOB;
    params_info.gen_type = GEN_TYPE;
    params_info.gui = GUI;
    params_info.par = JSON.parse(IKM.crud('selectMap',{
        table: 'pdm_workprocess',
        field: ['script_parameter'],
        where: { id: ARGS["process_id"] }
    }).script_parameter);
    
    _.merge(params_info, jobinfo);
    var res = func.call({}, params_info);
    return res;
}

function addFlowNotes(par){
    par["user_name"] = par["user_name"] ||  USER_NAME
    par["user_id"] = par["user_id"] ||  USER_ID
    return IKM.update_job_workflow_log(par)
}

function updateFlowReport(par){
    par["job_id"] = par["job_id"] || JOB_ID
    return IKM.update_flow_report(par)
}


