define(function (require, exports, module) {
    var global = require("../../js/global");
    
    var faultDiag = {};
    faultDiag.curStatus = "init";	// init -> connecting -> connected -> collect -> diagnosis -> closing -> init
    faultDiag.diagnoseId = ''; // 同一次诊断,升级,上传文件的faultDig相同
    faultDiag.logId = ''; // 当前诊断/收集log文件夹的名字
    faultDiag.collectDevName = [];
    faultDiag.collectType = undefined;
    faultDiag.typeName = undefined;
    faultDiag.rulePath = undefined;
    faultDiag.preconditionParams = {};
    faultDiag.cpuUsedLimit = 60;
    faultDiag.startTime_collect = 0;
    faultDiag.endTime_collect = 0;
    faultDiag.startTime_diag = 0;
    faultDiag.endTime_diag = 0;
    faultDiag.startTime_repair = 0;
    faultDiag.endTime_repair = 0;
    faultDiag.diagSavePath = undefined;
    faultDiag.diagnoseResult = [];
    faultDiag.diagCount = 0;
    faultDiag.totalWarnCount = 0;      //当前诊断项诊断出问题的处理建议的个数
    faultDiag.successCount = 0;
    faultDiag.manualCount = 0;
    faultDiag.tmpCollectPercent = 0;
    faultDiag.tmpDiagPercent = 0;
    faultDiag.flag = false;            //诊断结果显示用,是否已创建过"success"/"warn"/"manual"面板,已创建过不再创建
    faultDiag.selectGroupName = undefined;
    faultDiag.portNameArray = [];
    faultDiag.autoRepairCmds = [];
    faultDiag.backRepairCmds = [];
    faultDiag.manualConfirmAdvice = [];
    faultDiag.uploadUserInfo = {};
    faultDiag.curSelectNode = {};
    
    faultDiag.isClickResolved = false;  //是否已点击过“解决”、“未解决”。若点击过，不再显示自服务率统计对话框；否则显示。（现在已无用）
    faultDiag.isLoadFromDiag = false;   //只收集，不显示自服务率对话框；先诊断后收集，显示自服务率对话框。
    faultDiag.isClickCancel = false;    //诊断时是否点击过强制取消。若点击过，不再显示自服务率统计对话框；否则显示。
    
    faultDiag.cycleNum = 0;				//自定义循环收集次数

    // 自定义收集，用来标识单次收集的状态
    // 如果从来没有执行过,默认是要设置为notReady --- 在每次点击前设置
    // 如果执行结束 --- 设置为done // 在collectEnd.js中的on("collectEnd"设置
    // 如果被用户强制取消掉 --- 设置为cancel
    // 在开始执行收集时，将该状态设置为running
    faultDiag.collectStatus = 'notReady';
    
    function changeDevStatus(cur, next) {
        console.log('[curStatus] change from ' + cur + ' to ' + next);
        return next;
    }
    function judgeDiagResultType(result) { //判断当前后台返回诊断结果是处理建议、已排查问题还是需协助判断
        if (result.level == "warn" && result.problems[0].checkIns != undefined) {
            result.level = "manual";
        }
        return result;
    }
    function showTime(startTime, endTime, span_min_time, span_sec_time) {
        var sec_time = parseInt((endTime - startTime) / 1000);
        if (sec_time >= 60) {
            var min_time = parseInt(sec_time / 60);
            sec_time = sec_time % 60;
            $(span_min_time).text(min_time);
            $(span_sec_time).text(sec_time);
        } else {
            $(span_min_time).text(0);
            $(span_sec_time).text(sec_time);
        }
    }

    exports.getCurDeviceInfo = function (deviceName, callback) {
        if (callback == undefined) {
            return;
        }

        var devInfo = global.devicesIns.getDeviceInfoByDeviceName(deviceName);
        if (devInfo == '') {
            callback(false);
            return;
        }

        global.devicesIns.queryGroupInfoById(devInfo.groupId, function (err, rows) {

            if (err == null && rows.length > 0) {
                callback(true, {
                    userName: global.userMgrIns.getUserInfo().userName,
                    customer: rows[0].customer,
                    subGroup: rows[0].subGroup,
                    deviceName: devInfo.deviceName
                });

            } else {
                callback(false);
            }
        });

    };
    
    function uploadInfoToCloud(param) {
        var uploadDiagDataAray = [];
        var uploadDiagData = {};
        var devInfo = global.devicesIns.getDeviceInfoByDeviceName(faultDiag.collectDevName[0]);
        if (devInfo == '') {
            return;
        }
        var productLine = global.tftpOperateInstance.checkProductType(faultDiag.collectDevName[0]);
        //	    var zTree = $.fn.zTree.getZTreeObj("treeDemo");
        //	    var nodeList = zTree.getNodesByParamFuzzy("name", typeName);
        if (param.diagnoseId == undefined) {
            console.log('in uploadInfoToCloud, diagnoseId is undefined');
            return;
        }
        uploadDiagData.diagnoseId = param.diagnoseId;
        uploadDiagData.deviceSn = devInfo.seriaNo;
        uploadDiagData.deviceName = devInfo.deviceName;
        uploadDiagData.deviceIp = devInfo.host;
        uploadDiagData.deviceVersion = devInfo.softVer;
        uploadDiagData.deviceType = devInfo.deviceModel;
        uploadDiagData.ruleCode = global.transliteration.slugify(faultDiag.collectType);
        uploadDiagData.ruleName = faultDiag.collectType;
        uploadDiagData.subRuleCode = global.transliteration.slugify(faultDiag.typeName);
        uploadDiagData.subRuleName = faultDiag.typeName;
        uploadDiagData.diagnoseTime = global.moment().format('YYYY-MM-DD HH:mm:ss');
        uploadDiagData.duration = param.duration;
        uploadDiagData.diagnoseResult = param.actionResult;
        uploadDiagData.productLine = productLine.deviceType;
        
        
        if (param.curAction == "diagnosis") {
            uploadDiagData.isResolved = param.isResolved;
            uploadDiagData.argument = JSON.stringify(faultDiag.preconditionParams);

            if (faultDiag.totalWarnCount != 0) {
                uploadDiagData.hasProblem = true;
            } else {
                uploadDiagData.hasProblem = false;
            }
            uploadDiagData.manualDiagnose = false;
        }

        // 这里需要写入本地数据库,照样是先不考虑时序问题
        // 认为此事本地数据库已经有数据
        // 可能升级的字段: diagResult
        // 'F', 'NA', 'U', 'Y', 'N'
        var diaResult = 'NA';
        if (param.curAction == 'diagnosis') {
            global.operDbIns.updateDiagResult(param.diagnoseId, param.isResolved);
        } else {
            global.operDbIns.updateCollectFlag(param.diagnoseId, true);
        }

        // 储存客户和子分组
        uploadDiagData.customer = devInfo.customer;
        uploadDiagData.subGroup = devInfo.subGroup;

        // 其它信息
        uploadDiagData.otherInfo = global.devicesIns.getStoreData(devInfo);
        uploadDiagDataAray.push(uploadDiagData);
        //	    console.log(uploadDiagDataAray);
        statInfoIns.sendFaultDiagnose(uploadDiagDataAray, param.dataType);
        
    }

    // 将诊断/收集信息保存到本地数据库
    // 在调用该函数前,已经有相关的文件夹了。
    exports.startSaveOperInfo = function () {
        var devInfo = global.devicesIns.getDeviceInfoByDeviceName(faultDiag.collectDevName[0]);

        var hasDiag = false;
        var hasCollect = false;

        if (faultDiag.isLoadFromDiag == true) {
            hasDiag = true;
        } else {
            hasCollect = false;
        }

        global.operDbIns.replace({
            diagnoseId: faultDiag.diagnoseId,
            logId: faultDiag.logId,
            deviceName: faultDiag.collectDevName[0],
            deviceType: devInfo.deviceModel, 
            diagTime: global.jsUtil.formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss'),
            deviceIp: devInfo.host,
            ruleName: faultDiag.collectType,
            subRuleName: faultDiag.typeName,
            hasDiag: hasDiag,
            hasCollect: hasCollect
        }, function (error) {
            });
    }
    
    exports.faultDiag = faultDiag;
    exports.changeDevStatus = changeDevStatus;
    exports.judgeDiagResultType = judgeDiagResultType;
    exports.showTime = showTime;
    exports.uploadInfoToCloud = uploadInfoToCloud;
});