var requestUrl;
var returnUrl;

function IsSupportMultipartUpload()
{
    var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
    var isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1 && !isOpera; //判断是否IE浏览器
    return !isIE;
}

function IsSupportH5()
{
    var userAgent = navigator.userAgent;
    var isEdge = userAgent.indexOf("Edge") > -1;
    if(isEdge)
        return true;
    var reIE = new RegExp("MSIE (\\d+\\.\\d+);");
    reIE.test(userAgent);
    var fIEVersion = parseFloat(RegExp["$1"]);
    if(fIEVersion >= 10)
        return true;
    else
        return false;
}
// var accessid= 'LTAIzG5m63BhoGa7';
// var accesskey= 'J0mEs8AYtgGWrfC54cSGgUXHCOOjvS';
// var host = 'http://cdn.gangwaninfo.com';
// var now = timestamp = Date.parse(new Date()) / 1000;
// var policyText = {
//     "expiration": "2020-01-01T12:00:00.000Z", //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
//     "conditions": [
//         ["content-length-range", 0, 1048576000] // 设置上传文件的大小限制
//     ]
// };
//
// var policyBase64 = Base64.encode(JSON.stringify(policyText))
// message = policyBase64
// var bytes = Crypto.HMAC(Crypto.SHA1, message, accesskey, { asBytes: true }) ;
// var signature = Crypto.util.bytesToBase64(bytes);

var accessid ="";
var exdate = null;
var host = "";
var signature = "";
var policyBase64 = "";


function multipartUploadWithSts(storeAs, file,attachmentId,attachmentFlag,uploadPath,divId,size, cpt) {
    console.log("-----------------------start");


        if(IsSupportH5())
        {
            var cur = new Date();
            if(exdate != null && cur < exdate)
                uploadDirect(storeAs,file,attachmentId,attachmentFlag,uploadPath.replace('http://gangwan-app.oss-cn-hangzhou.aliyuncs.com', host),divId,size);
            else
            {
                $.ajax({
                    type:'get',
                    url: realPath+"/a/previewController/getDirectAccess",
                    dataType: 'JSON',
                    success: function(result){
                        console.log(result.accessid);

                        accessid = result.accessid;
                        var tDate = new Date();
                        tDate.setTime(result.expire);
                        exdate = tDate;
                        host=result.host;
                        signature=result.signature;
                        policyBase64=result.policy;

                        uploadDirect(storeAs,file,attachmentId,attachmentFlag,uploadPath.replace('http://gangwan-app.oss-cn-hangzhou.aliyuncs.com', host),divId,size);
                    },
                    error: function(){
                        alert("获取密钥信息失败");
                    }
                });
            }

        }
        else
        {
            alert("当前版本浏览器不支持文件上传，请使用IE10及以上版本或其他浏览器！");
        }
};

function uploadDirect(storeAs,file,attachmentId,attachmentFlag,uploadPath,divId,size)
{
    var request = new FormData();
    request.append("OSSAccessKeyId",accessid);
    request.append("policy",policyBase64);
    request.append("Signature",signature);

    request.append("key",storeAs);
    request.append("success_action_status",'200');
    request.append('file', file,file.name);

    $.ajax({
        url : host,
        data : request,
        processData: false,
//cache: false,
//async: false,
        contentType: false,
        type : 'POST',
        xhr: function() { //用以显示上传进度
            var xhr = $.ajaxSettings.xhr();
            if (xhr.upload) {
                xhr.upload.addEventListener('progress', function(evt) {
                    uploadProgress(evt, divId, file.name);
                }, false);
            }
            return xhr;
        },
        success : function(data, status, request) {
            returnUrl = realPath+"/a/sys/workattachment/saveAttachment";
            $.ajax({
                type:'post',
                url:returnUrl,
                data:{
                    "attachmentName":file['name'],
                    "attachmentId":attachmentId,
                    "attachmentFlag":attachmentFlag,
                    "url":uploadPath
                },
                success:function(data){
                    console.log('ajax requst : ' + data.status);
                    if(data.status=="Success"){
                        parent.layer.msg("上传成功！",{icon:1});
                        var lenght =$(".trIdAdds").length+size;
                        var addFile = "addFile"+divId;
                        var str = '<tr class="trIdAdds">'+
                            '<td class="text-center">' ;
                        if (isContains("jpg,png,gif,bmp,jpeg",data.type)){
                            str = str +'<img src="'+data.url+'" width="50" height="50" onclick="openDialogView(\'预览\',\''+realPath+ '/a/sys/picturepreview/picturePreview?url=' +data.url+ '\',\'90%\',\'90%\')" alt="'+data.attachmentName+'"/>';
                        }else if(isContains("pdf",data.type)){
                            str = str + '<a class="attention-info" href="javascript:void(0)" onclick="preview(\'预览\',\''+data.url+'\',\'90%\',\'90%\',\'1\')">'+data.attachmentName+'</a>';
                        }else {
                            str = str + '<a class="attention-info" href="javascript:void(0)" onclick="preview(\'预览\',\''+data.url+'\',\'90%\',\'90%\')">'+data.attachmentName+'</a>';
                        }
                        str = str +'</td>'+
                            '<td >'+data.createByName+'</td>'+
                            '<td >'+data.createDate+
                            '<input name="workAttachments['+lenght+'].id" type="hidden" readonly="readonly" maxlength="20" style="width:140px;" class="form-control" value=""/>'+
                            '<input name="workAttachments['+lenght+'].attachmentId" type="hidden" readonly="readonly" maxlength="20" style="width:140px;" class="form-control" value="'+data.attachmentId+'"/>'+
                            '<input name="workAttachments['+lenght+'].url" type="hidden" readonly="readonly" maxlength="20" style="width:140px;" class="form-control" value="'+data.url+'"/>'+
                            '<input name="workAttachments['+lenght+'].attachmentName" type="hidden" readonly="readonly" maxlength="20" style="width:140px;" class="form-control" value="'+data.attachmentName+'"/>'+
                            '<input name="workAttachments['+lenght+'].createBy.id" type="hidden" readonly="readonly" maxlength="20" style="width:140px;" class="form-control" value="'+data.createBy+'"/>'+
                            '<input name="workAttachments['+lenght+'].type" type="hidden" readonly="readonly" maxlength="20" style="width:140px;" class="form-control" value="'+data.type+'"/>'+
                            '<input name="workAttachments['+lenght+'].attachmentFlag" type="hidden" readonly="readonly" maxlength="20" style="width:140px;" class="form-control" value="'+data.attachmentFlag+'"/>'+
                            '</td>'+
                            '<td class="op-td">'+
                            '<div class="op-btn-box">' +
                            '<a href="javascript:location.href=\''+realPath+'/a/workfullmanage/workFullManage/downLoadAttach?file=\'+encodeURIComponent(\''+data.url+'\');" class="op-btn op-btn-download"><i class="fa fa-download"></i>&nbsp;下载</a>'+
                            '<a href="javascript:void(0)" onclick="deleteFileFromAliyun(this,\''+realPath+'/a/sys/workattachment/deleteFileFromAliyun?url='+encodeURIComponent(data.url)+'&id='+data.id+'&type=2\',\''+addFile+'\',\''+divId+'\')" class="op-btn op-btn-delete" ><i class="fa fa-trash"></i>&nbsp;删除</a>'+
                            '</div>' +
                            '</td>'+
                            '</tr>';
                        console.log("file:"+divId);
                        console.log("str="+str);
                        $("#file"+divId).append(str);
                        // $("img").not(".upload_ico").each(function () {
                        //     var num = 1 ;
                        //     $(this).live("click",function () {
                        //         var flag = num%2;
                        //         if(flag == 1){
                        //             $(this).css("width","90%");
                        //             $(this).css("height","90%");
                        //             num++;
                        //         }else if(flag ==0){
                        //             $(this).css("width","50px");
                        //             $(this).css("height","50px");
                        //             num++;
                        //         }
                        //     })
                        // });
                    }else {
                        parent.layer.msg("上传失败！",{icon:2});
                    }
                }
            })

        },
        error : function(returndata) {
            alert("文件上传失败！");
        }
    });
}

function uploadProgress(e, divId, name) {
    var percent = e.loaded / e.total;
    var p = Math.floor(percent*100);
    $("#jindutiao"+divId).attr("style","width: "+p+"%");
    $("#jindutiao"+divId).attr("aria-valuenow",p+"%");
    $("#baifenbi"+divId).html(p+"%");
    $("#fileName"+divId).html(name);
}

function multitest (ossClient, storeAs, file,attachmentId,attachmentFlag,uploadPath,divId, size,cpt) {

};

// function multipartUploadWithSts(storeAs, file,attachmentId,attachmentFlag,uploadPath,divId,size, cpt) {
//     console.log("-----------------------start");
//     requestUrl = realPath+"/a/previewController/getAccess";
//     OSS.urllib.request(requestUrl, {method: 'GET'}, function (err, response) {
//         if (err) {
//             return alert(err);
//         }
//         try {
//             result = JSON.parse(response);
//         } catch (e) {
//             errmsg = 'parse sts response info error: ' + e.message;
//             return alert(errmsg);
//         }
//         console.log("---------result"+result);
//         client = new OSS.Wrapper({
//             accessKeyId: result.AccessKeyId,
//             accessKeySecret: result.AccessKeySecret,
//             stsToken: result.SecurityToken,
//             bucket: result.Bucket,
//             endpoint: result.Endpoint,
//             timeout:'30000'
//         });
//         multitest(client, storeAs, file,attachmentId,attachmentFlag,uploadPath.replace('http://gangwan-app.oss-cn-hangzhou.aliyuncs.com', result.AliyunUrl),divId,size, cpt);
//     })
// };
//
// function multitest (ossClient, storeAs, file,attachmentId,attachmentFlag,uploadPath,divId, size,cpt) {
//     var names =  storeAs.split("/");
//     var name = names[names.length-1];
//     ossClient.multipartUpload(storeAs, file,{
//         partSize: 1 * 1024 * 1024,
//         parallel: 5,
//         progress: function* (percent, cpt) {
//             console.log(cpt);
//             console.log('Progress: ' + percent);
//             var p = Math.floor(percent*100);
//             $("#jindutiao"+divId).attr("style","width: "+p+"%");
//             $("#jindutiao"+divId).attr("aria-valuenow",p+"%");
//             $("#baifenbi"+divId).html(p+"%");
//             $("#fileName"+divId).html(name);
//             checkpoint_temp = cpt;
//         }
//     }).then(function (result) {
//         console.log("uploadPath:"+uploadPath);
//         console.log("rusult:"+result);
//         console.log("end-------result:");
//         returnUrl = realPath+"/a/sys/workattachment/saveAttachment";
//         $.ajax({
//             type:'post',
//             url:returnUrl,
//             data:{
//                 "attachmentName":file['name'],
//                 "attachmentId":attachmentId,
//                 "attachmentFlag":attachmentFlag,
//                 "url":uploadPath
//             },
//             success:function(data){
//                 console.log('ajax requst : ' + data.status);
//                 if(data.status=="Success"){
//                     parent.layer.msg("上传成功！",{icon:1});
//                     var lenght =$(".trIdAdds").length+size;
//                     var addFile = "addFile"+divId;
//                     var str = '<tr class="trIdAdds">'+
//                         '<td>' ;
//                     if (isContains("jpg,png,gif,bmp,jpeg",data.type)){
//                         str = str +'<img src="'+data.url+'" width="50" height="50" alt="'+data.attachmentName+'"/>';
//                     }else if(isContains("pdf",data.type)){
//                         str = str + '<a href="javascript:void(0)" onclick="preview(\'预览\',\''+data.url+'\',\'800px\',\'500px\',\'1\')">'+data.attachmentName+'</a>';
//                     }else {
//                         str = str + '<a href="javascript:void(0)" onclick="preview(\'预览\',\''+data.url+'\',\'800px\',\'500px\')">'+data.attachmentName+'</a>';
//                     }
//                     str = str +'</td>'+
//                         '<td>'+data.createByName+'</td>'+
//                         '<td>'+data.createDate+
//                         '<input name="workAttachments['+lenght+'].id" type="hidden" readonly="readonly" maxlength="20" style="width:140px;" class="form-control" value=""/>'+
//                         '<input name="workAttachments['+lenght+'].attachmentId" type="hidden" readonly="readonly" maxlength="20" style="width:140px;" class="form-control" value="'+data.attachmentId+'"/>'+
//                         '<input name="workAttachments['+lenght+'].url" type="hidden" readonly="readonly" maxlength="20" style="width:140px;" class="form-control" value="'+data.url+'"/>'+
//                         '<input name="workAttachments['+lenght+'].attachmentName" type="hidden" readonly="readonly" maxlength="20" style="width:140px;" class="form-control" value="'+data.attachmentName+'"/>'+
//                         '<input name="workAttachments['+lenght+'].createBy.id" type="hidden" readonly="readonly" maxlength="20" style="width:140px;" class="form-control" value="'+data.createBy+'"/>'+
//                         '<input name="workAttachments['+lenght+'].type" type="hidden" readonly="readonly" maxlength="20" style="width:140px;" class="form-control" value="'+data.type+'"/>'+
//                         '<input name="workAttachments['+lenght+'].attachmentFlag" type="hidden" readonly="readonly" maxlength="20" style="width:140px;" class="form-control" value="'+data.attachmentFlag+'"/>'+
//                         '</td>'+
//                         '<td>'+
//                         '<a href="'+realPath+'/a/workfullmanage/workFullManage/downLoadAttach?file='+data.url+'" class="btn btn-success btn-xs">下载</a>'+
//                         '    <a href="javascript:void(0)" onclick="deleteFileFromAliyun(this,\''+realPath+'/a/sys/workattachment/deleteFileFromAliyun?url='+data.url+'&id='+data.id+'&type=2\','+addFile+')" class="btn btn-danger btn-xs" >删除</a>'+
//                         '    </td>'+
//                         '</tr>';
//                     console.log("file:"+divId);
//                     console.log("str="+str);
//                     $("#file"+divId).append(str);
//                     $("img").not(".upload_ico").each(function () {
//                         var num = 1 ;
//                         $(this).live("click",function () {
//                             var flag = num%2;
//                             if(flag == 1){
//                                 $(this).css("width","90%");
//                                 $(this).css("height","90%");
//                                 num++;
//                             }else if(flag ==0){
//                                 $(this).css("width","50px");
//                                 $(this).css("height","50px");
//                                 num++;
//                             }
//                         })
//                     });
//                 }else {
//                     parent.layer.msg("上传失败！",{icon:2});
//                 }
//             }
//         })
//     }).catch(function (err) {
//         console.log("err------ err:");
//         console.log(err);
//         multipartUploadWithSts(storeAs, file,attachmentId,attachmentFlag,uploadPath, size,checkpoint_temp);
//     });
// };
function isContains(str, substr) {
    return str.indexOf(substr) >= 0;
}

function deleteFileFromAliyun(obj,deleteUrl,addFile,divId){
    if (divId!=null && divId!= undefined && divId != ''){
        divId = "_attachment";
    }
    var fileDiv = divId.substr(1,divId.length)+"_file";
    $("#"+fileDiv).val("");
    $.ajax({
        type:"post",
        url:deleteUrl,
        success:function(data){
            if(data.str){
                parent.layer.msg('删除成功',{icon:1});
                $(obj).parent().parent().parent().remove();
                $("#"+addFile).hide();
                $("#jindutiao"+divId).hide();
            }else {
                parent.layer.msg('删除失败',{icon:2});
            }
        }
    });
}