define(function (require, exports, module) {
    var global = require("../../js/global");
    var jGlobal = require("./faultDiagGlobal");
    
    var curFileInfo = [];
    var curUploadIndex = 0;				//一次只能上传一个文件，该变量指当前上传到第几个文件
    var uploadFileNum = undefined;		//总共需要上传的文件数
    var selectedFiles = [];
    var uploadState = 'init'; 			//* init -> connect -> upload -> init
    var uploadParams = {};
    
    function fileNameStyle(value) {
//    	console.log(value);
    	if (typeof value == "string") {
    		var fileNameArray = value.split('\\');
            var fileName = fileNameArray[fileNameArray.length - 1]
            return fileName;
    	}
    }
    
    function uploadStateChange(uploadState, next) {
        console.log('[UploadFile] change from', uploadState, 'to', next);
        uploadState = next;
        return uploadState;
    }
    
    function refreshFileTable() {
        $('#upload_file_table').bootstrapTable('load', curFileInfo);
    }
    
    function upload_resize() {
//		$('#upload_file_table').bootstrapTable('resetView', {height:150});
    }
    
    function uploadFiles() {
        console.error(uploadState);
        if (uploadState != 'init') {
            alert(undefined, '正在上传，请稍候！');
            return;
        }
        
        saveUploadUserInfo();
        
        selectedFiles = [];
        selectedFiles = $("#upload_file_table").bootstrapTable('getData');
        if (selectedFiles.length == 0) {
            alert(undefined, "请选择要上传的文件");
            return;
        }
        uploadFileNum = selectedFiles.length;
        
        if ($("#upl_name").val() == "") {
            alert(undefined, "请输入姓名/组织");
            return;
        }
        
        uploadState = uploadStateChange(uploadState, 'upload');
        
        var fileDir = getUploadParam(selectedFiles);
        global.tftpOperateInstance.uploadFileToCloud(
            fileDir.origFileDir, 
            fileDir.destFileDir, 
            uploadParams.deviceName, 
            {
                uploader: $("#upl_name").val(),
                clientName: $("#upl_local").val(),
                deviceName: uploadParams.deviceName,
                role: $("#upl_identity").val(),
                phone: $("#upl_phone").val(),
                email: $("#upl_email").val(),
                note: $("#upl_des").val()
            },
            uploadParams.logParams
        );
        
        curFileInfo[0].status = "上传中,请耐心等待...";
        refreshFileTable();
    }
    
    function saveUploadUserInfo() {
        jGlobal.faultDiag.uploadUserInfo.upl_name = $("#upl_name").val();
        jGlobal.faultDiag.uploadUserInfo.upl_phone = $("#upl_phone").val();
        jGlobal.faultDiag.uploadUserInfo.upl_email = $("#upl_email").val();
        jGlobal.faultDiag.uploadUserInfo.upl_local = $("#upl_local").val();
        jGlobal.faultDiag.uploadUserInfo.upl_identity = $("#upl_identity").val();
        jGlobal.faultDiag.uploadUserInfo.upl_des = $("#upl_des").val();
    }
    
    function getUploadParam(selectedFiles) {
        //	console.error(curUploadIndex);
        
        var fileDir = {};
        var origFileDir = selectedFiles[curUploadIndex].fileName;
        var destFileDir = origFileDir + ".tar.gz";
        
        fileDir.origFileDir = origFileDir;
        fileDir.destFileDir = destFileDir;
        return fileDir;
    }
    
    function uploadNextFile() {
        //	console.error(curUploadIndex);
        //	console.error(uploadFileNum - 1);
        
        if (curUploadIndex <= (uploadFileNum - 1)) {
            var fileDir = getUploadParam(selectedFiles);
            // 如果有可能的话，获取到diagnoseId
            
            global.tftpOperateInstance.uploadFileToCloud(
                fileDir.origFileDir, 
                fileDir.destFileDir, 
                uploadParams.deviceName, 
                {
                    uploader: $("#upl_name").val(),
                    clientName: $("#upl_local").val(),
                    deviceName: uploadParams.deviceName,
                    role: $("#upl_identity").val(),
                    phone: $("#upl_phone").val(),
                    email: $("#upl_email").val(),
                    note: $("#upl_des").val()
                }, 
                uploadParams.logParams
            );
            curFileInfo[curUploadIndex].status = "上传中,请耐心等待...";
        } else {
            curUploadIndex = 0;
            uploadState = uploadStateChange(uploadState, 'init');
        }
    }
    
    function setEmailSubject(emailSubject) {
        //$("#emailSubject").text(emailSubject);
    }
    exports.setEmailSubject = setEmailSubject;
    
    function setUploadParams(curUploadParams) {
        uploadParams = curUploadParams;

        jGlobal.getCurDeviceInfo(uploadParams.deviceName, function (success, deviceInfo) {

            if (!success) {
                console.error('jGlobal.getCurDeviceInfo error!');
                return;
            }
            // 修改表单上面的用户名和客户名
            $("#upl_name").val(deviceInfo.userName);
            $("#upl_local").val(deviceInfo.customer);
        });
    }
    exports.setUploadParams = setUploadParams;
    
    function init() {
        initWindowEvent();
        initPageStatistic();
        initVariable();
        initTable();
        initDom();
        removeGlobalEvent();
        initEvent();
        
        function initWindowEvent() {
            window.fileNameStyle = fileNameStyle;
        }
        function initPageStatistic() {
            statRecordEle("faultDiag#upload");
        }
        function initVariable() {
            curFileInfo = [];
            curUploadIndex = 0;
            uploadFileNum = undefined;
            selectedFiles = [];
            uploadState = 'init';
            uploadParams = {};
        }
        function initDom() {
            //加载上次的用户信息
            $("#upl_name").val(jGlobal.faultDiag.uploadUserInfo.upl_name);
            $("#upl_phone").val(jGlobal.faultDiag.uploadUserInfo.upl_phone);
            $("#upl_email").val(jGlobal.faultDiag.uploadUserInfo.upl_email);
            $("#upl_local").val(jGlobal.faultDiag.uploadUserInfo.upl_local);
            $("#upl_identity").val(jGlobal.faultDiag.uploadUserInfo.upl_identity);
            $("#upl_des").val(jGlobal.faultDiag.uploadUserInfo.upl_des);
            
            //提示用户上传文件和发送邮件
            var uploadFaultId = curFileInfo[0].fileName;
            uploadFaultId = uploadFaultId.split('\\');
            uploadFaultId = uploadFaultId[uploadFaultId.length - 1];
            //$("#uploadFaultId").text(uploadFaultId);
        }
        function initTable() {
            //加载本次诊断或收集的log目录
            var tmp_curFileInfo = {};
            tmp_curFileInfo.fileName = jGlobal.faultDiag.diagSavePath;
            tmp_curFileInfo.fileSize = "目录";
            tmp_curFileInfo.status = "等待上传";
            curFileInfo = [];
            curFileInfo.push(tmp_curFileInfo);
            
            $('#upload_file_table').bootstrapTable({
                data: []
            });
            $("#uploadModal .fixed-table-toolbar>.search").hide(); //为什么data-search="flase"无效？
            $("#upload_file_table thead").css("background", "#d7e0f5"); //为什么原先的样式无效？
            $(".fixed-table-body").addClass('custom-scroll');
            
            refreshFileTable();
            upload_resize();
        }
        function removeGlobalEvent() {
            global.tftpOperateInstance.removeAllListeners("uploadOk");
            global.tftpOperateInstance.removeAllListeners("uploadError");
            $("#uploadModal .btn-confirm").unbind('click');
        }
        function initEvent() {
            console.log("---------------------------upload--------------------------");

            global.tftpOperateInstance.on('uploadOk', function (diagnoseId, cloudId) {
                console.log("------------------上传成功---------------------");
                $("#uploadModal .close").show();
                
                // 写入数据库,证明上传成功
                console.log('diagnoseId', diagnoseId, ' cloudId:', cloudId);
                global.operDbIns.updateLoadFlag(diagnoseId, true, cloudId);

                try {
                    var clipboard = window.require('nw.gui').Clipboard.get();
                    clipboard.clear();
                    clipboard.set(cloudId.toString(), 'text');
                } catch (e) {
                    console.error('in clipboard error:', e);
                }



                alert(undefined, "上传成功！<br>故障ID: <b>" + cloudId + '</b> 已复制!<br>您可直接将此ID粘贴至CSOS系统!相关人员即可下载故障信息');
                uploadState = uploadStateChange(uploadState, 'init');
                curFileInfo[curUploadIndex].status = "上传成功";
                curUploadIndex++;
                uploadNextFile();
                refreshFileTable();
            });

            global.tftpOperateInstance.on('uploadError', function (errStatusCode) {
                console.log("------------------上传失败---------------------");
                $("#uploadModal .close").show();
                
                alert(undefined, "上传失败！");
                uploadState = uploadStateChange(uploadState, 'init');
                curFileInfo[curUploadIndex].status = "上传失败";
                curUploadIndex++;
                uploadNextFile();
                refreshFileTable();
            });

            $("#uploadModal .btn-confirm").click(function () {
            	$("#uploadModal .close").hide();
                uploadFiles();
            });
        }
    }
    exports.init = init;
});
