
// 在附件元素的data上存放选择的附件数据,初始为空
function initDepositListData(depositDataDom, parent = '') {
    if(parent) {
        parent.find(depositDataDom).data('filearray',[])
        parent.find(depositDataDom).data('deletefileid',[])

        // 额度支用
        parent.find(depositDataDom).data('filearrayOriginal',[])
        parent.find(depositDataDom).data('filearrayDeletes',[])
    } else {
        $(depositDataDom).each(function(i,ele){
            $(ele).data('filearray',[]);
            $(ele).data('deletefileid',[]);
            // 额度支用
            $(ele).data('filearrayOriginal',[])
            $(ele).data('filearrayDeletes',[]);
        });
    }

}

// 查看历史回显附件
function seeHistoryGetFile(dom, fileList) {
    let filesHtm='';
    if( fileList.length>0 ){
        //contractMakingViewBox.find(".uploadFile").removeClass("hide");
        for(var ii=0;ii<fileList.length;ii++){
            filesHtm+='<div class="uploaderFile oldFile">'+
                '<input type="hidden" class="fileid" value="'+fileList[ii].id+'">'+
                '<div class="fileContent"><div class="file-wrapper">';
            var fileType=fileList[ii].fileType;
            if(fileType=='.jpg' || fileType=='.jpeg' || fileType=='.png' || fileType=='.bmp'){
                filesHtm+='<div class="file-icon" style="color: rgb(119, 31, 173);"><div  class="file-icon-image"'+
                    'style="background-image:url('+ fileList[ii].path +');"></div></div>';
            }else {
                filesHtm+='<div class="file-icon" style="color:#5AC4FC;"><div class="file-icon-image"><i class="icon icon-file-pdf"></i></div></div>';
            }
            filesHtm+='<div class="content">'+
                '<div class="file-name">'+fileList[ii].originalName+'</div>'+
                '<div class="file-size small text-muted">'+(fileList[ii].size/1024/1024).toFixed(2)+'MB</div>'+
                '</div>'+
                '<div class="actions" style="width: 1.032rem;">'+
                '<a class="btn btn-link btn-preview-file" target="_blank" href="/fileStorage/preview?fileId='+fileList[ii].id+'">'+
                '<em style="display:none">预览</em>'+
                '<i class="operateIconfont operateIcon-yulan"></i>'+
                '</a>'+
                '<a class="btn btn-link btn-download-file" style="float:right" href="/fileStorage/downloadFile?fileId='+fileList[ii].id+'">'+
                '<em style="display:none">下载</em>'+
                '<i class="operateIconfont operateIcon-xiazai"></i>'+
                '</a></div></div>';
        }
        dom.append(filesHtm);
    }
}


// 删除
var fileWrapperbasic = `
    <div class="file-wrapper">
        <div class="file-icon" style="color: #5AC4FC;">
            <div class="file-icon-image"></div>
        </div>
        <div class="content">
            <div class="file-name"></div>
            <div class="file-size small text-muted"></div>
        </div>
        <div class="actions" style="width:0.5rem">
            <a class="btn btn-link btn-delete-file">
            <em>删除</em>
            <i class="operateIconfont operateIcon-shanchu"></i>
            </a>
        </div>
    </div>
`

//  预览和下载
var oldFileWrapperbasic = `<div class="file-wrapper" style="display: flex;">
    <div class="file-icon" style="color: #5AC4FC;">
        <div class="file-icon-image"></div>
    </div>
    <div class="content" style="width: 80%">
        <div class="file-name"></div>
        <div class="file-size small text-muted"></div>
    </div>
    <div class="actions" style="width:0.5rem">
        <a target="_blank" class="btn-yulan-file">
            <em style="font-style:normal">预览</em>
            <i class="operateIconfont operateIcon-yulan"></i>
        </a>
    </div>
    <div class="actions" style="width:0.5rem">
        <a class="btn-xiazai-file">
            <em style="font-style:normal">下载</em>
            <i class="operateIconfont operateIcon-xiazai"></i>
        </a>
    </div>
</div>`;

 //  预览、删除、下载
var oldFileWrapperbasicDelete = '<div class="file-wrapper" style="display: flex;"><div class="file-icon" style="color: #5AC4FC;"><div class="file-icon-image"></div></div>' +
 '<div class="content"  style="width: 80%"><div class="file-name"></div><div class="file-size small text-muted"></div></div>' +
 '<div class="actions" style="width:0.5rem"><a target="_blank" class="btn-yulan-file">' +
 '<em style="font-style:normal">预览</em><i class="operateIconfont operateIcon-yulan"></i></a></div>' +
 '<div class="actions" style="width:0.5rem"><a class="btn-xiazai-file">' +
 '<em style="font-style:normal">下载</em><i class="operateIconfont operateIcon-xiazai"></i></a></div>' +
 '<div class="actions" style="width:0.5rem"><a class="btn btn-link btn-delete-file">'+
 '<em>删除</em><i class="operateIconfont operateIcon-shanchu"></i></a></div></div>'

// 附件相关dom
// 下载
var onlyDownloadFileWrapperbasic = '<div class="file-wrapper" style="display: flex;"><div class="file-icon" style="color: #5AC4FC;"><div class="file-icon-image"></div></div>' +
'<div class="content" style="width: 80%"><div class="file-name"></div><div class="file-size small text-muted"></div></div>' +
'<div class="actions" style="width:0.5rem"><a class="btn-xiazai-file">' +
'<em style="font-style:normal">下载</em><i class="operateIconfont operateIcon-xiazai"></i></a></div>'+
'</div>';

// 预览
var onlyViewFileWrapperbasic = '<div class="file-wrapper" style="display: flex;"><div class="file-icon" style="color: #5AC4FC;"><div class="file-icon-image"></div></div>' +
'<div class="content" style="width: 80%"><div class="file-name"></div><div class="file-size small text-muted"></div></div>' +
'<div class="actions" style="width:0.5rem"><a target="_blank" class="btn-yulan-file">' +
'<em style="font-style:normal">预览</em><i class="operateIconfont operateIcon-yulan"></i></a></div>' +
'</div>';

// 删除和预览
var deleteAndView = '<div class="file-wrapper" style="display: flex;"><div class="file-icon" style="color: #5AC4FC;"><div class="file-icon-image"></div></div>' +
 '<div class="content"  style="width: 80%"><div class="file-name"></div><div class="file-size small text-muted"></div></div>' +
 '<div class="actions" style="width:0.5rem"><a target="_blank" class="btn-yulan-file">' +
 '<em style="font-style:normal">预览</em><i class="operateIconfont operateIcon-yulan"></i></a></div>' +
 '<div class="actions" style="width:0.5rem"><a class="btn btn-link btn-delete-file">'+
 '<em>删除</em><i class="operateIconfont operateIcon-shanchu"></i></a></div></div>'

// 展示原先有的附件
function showOriginalFile(source, insert, type) {
    for (var j = 0; j < $(source).length; j++) {
        var originalFileWrapper = ''
        if(type === 'delete') {
            originalFileWrapper = $(oldFileWrapperbasicDelete).clone();
        }else if(type === 'onlyDelete') {
            originalFileWrapper = $(fileWrapperbasic).clone();
        }else if (type === 'onlyDownload') {
            originalFileWrapper = $(onlyDownloadFileWrapperbasic).clone();
        }else if (type === 'onlyView') {
            originalFileWrapper = $(onlyViewFileWrapperbasic).clone();
        }else if(type === 'deleteAndView') {
            originalFileWrapper = $(deleteAndView).clone();
        }else {
            originalFileWrapper = $(oldFileWrapperbasic).clone();
        }
        originalFileWrapper.find('.file-name').text($(source).eq(j).find('.originalName').val());
        originalFileWrapper.find('.file-name').attr('originalid', $(source).eq(j).find('.originalId').val());
        if (parseFloat($(source).eq(j).find('.originalSize').val()) < 1048576) {
            originalFileWrapper.find('.file-size').text(($(source).eq(j).find('.originalSize').val() / 1024).toFixed(2) + "KB");
        } else {
            originalFileWrapper.find('.file-size').text(($(source).eq(j).find('.originalSize').val() / 1024 / 1024).toFixed(2) + "MB");
        }
        ;
        var originaltype = $(source).eq(j).find('.originalType').val().toUpperCase();
        if (originaltype == '.JPG' || originaltype == '.JPEG' || originaltype == '.PNG' || originaltype == '.BMP') {
            originalFileWrapper.find('.file-icon-image').css('background-image', 'url(' + $(source).eq(j).find('.originalUrl').val() + ')');
        } else {
            originalFileWrapper.find('.file-icon-image').append('<i class="icon icon-file-pdf"></i>');
        }
        ;
        originalFileWrapper.find('.btn-delete-file').addClass('btn-delete-originalfile').removeClass("btn-delete-file");

        originalFileWrapper.find('.btn-yulan-file').attr('href', '/fileStorage/preview?fileId=' + $(source).eq(j).find('.originalId').val());
        originalFileWrapper.find('.btn-xiazai-file').attr('href', '/fileStorage/downloadFile?fileId=' + $(source).eq(j).find('.originalId').val());
        $(insert).find('.fileContent').append(originalFileWrapper)
    }
    ;
    j = null;
    if ($(insert).find('.file-wrapper').length > 0) {
        $(insert).find('.spanHolder').remove();
    }
    ;
};


function uploadFileMethod(params) {
  const { mainDom, insideDelegateDom, delegateDom,  delegateDomInput, depositDataDom = '.addFileList', delegateLabel = 'td', displayListDom = '.uploaderFile', isCustomUploadBtn = true} = params

    initDepositListData(depositDataDom)

    // 展示原附件
    // if($('#updatePage').length) {
    //
    //     showOriginalFile('.fileInfoListOriginal', '.addFileList');
    // }
    //  内部触发附件
    $(mainDom).on("click", insideDelegateDom, function(){
        if ( !window.FileReader ) {
            new $.zui.Messager('您的浏览器版本过低，请升级您的浏览器', {
                type: 'danger'
            }).show();
            return;
        };
        if($(this).find(".spanHolder").length>0 ){
            $(this).parent().prev().click();
        };
    });
    // 外部触发选择附件
    $(mainDom).on("click",delegateDom,function(){
        if ( !window.FileReader ) {
            new $.zui.Messager('您的浏览器版本过低，请升级您的浏览器', {
                type: 'danger'
            }).show();
            return;
        };
        $(this).parent().find('.fileinput').click();
    });

    // 选择附件
    $(mainDom).on("change", delegateDomInput, function(e){
        var that = $(this);
        var choosefiles = e.target.files || e.dataTransfer.files;
        for( var i=0;i<choosefiles.length;i++ ){
            var file = e.target.files[i] || e.dataTransfer.files[i];//用于提交
            $(this).parent().data('filearray').push(file);
            fileWrapper = $(fileWrapperbasic).clone();
            var type = file.type;
            var indexof = type.indexOf("/"),fileType='';
            if( indexof != -1 ){
                var index = parseInt(indexof)+1;
                fileType = type.substring(index,type.length).toUpperCase();
            };
            fileWrapper.find('.file-name').text(file.name);
            if( parseFloat(file.size) < 1048576 ){
                fileWrapper.find('.file-size').text((file.size/1024).toFixed(2)+'KB');
            }else{
                fileWrapper.find('.file-size').text((file.size/1024/1024).toFixed(2)+'MB');
            };
            that.next().find(".fileContent").append(fileWrapper);
            // 有附件时去掉框框里的'上传附件'字样
            if( that.next().find('.file-wrapper').length>0 ){
                that.next().find('.spanHolder').remove();
            };
            detailpreview(fileType,fileWrapper,file);
        };
        if(!isCustomUploadBtn) {
            $(this).parent().parent().find(delegateDom).hide()
        }
        i = null;
        function detailpreview(fileType,fileWrapper,file){
            var reader = new FileReader();
            reader.readAsDataURL(file);//转为base64(预览)
            reader.onload = function(e){
                e = e || window.event;
                if( fileType=='JPG' || fileType=='JPEG' || fileType=='PNG' || fileType=='BMP' || fileType=='JPG' ){
                    fileWrapper.find(".file-icon-image").css("backgroundImage",'url('+e.target.result+')')
                }else{
                    fileWrapper.find(".file-icon-image").append(`<i class="icon icon-file-pdf"></i>`)
                };
            };
        };
    });
    // 删除附件
    $(mainDom).on("click",".btn-delete-file",function(){
        if(!isCustomUploadBtn) {
            $(this).parents(delegateLabel).parent().find(delegateDom).show()
        }
        var deleteindex = $(this).parents(delegateLabel).find('.btn-delete-file').index($(this));
        $(this).parents(delegateLabel).data('filearray').splice(deleteindex,1);
        $(this).parents(displayListDom).prev().val(null);
        if( $(this).parents(delegateLabel).find('.file-wrapper').length == 1 ){
            $(this).parents(".file-wrapper").before('<span class="spanHolder">上传附件</span>');
        };
        $(this).parents(".file-wrapper").remove();

        return false;

    });
    // 删除(原有的)附件
    $(mainDom).on("click",".btn-delete-originalfile",function(event){
        if(!isCustomUploadBtn) {
            $(this).parents(delegateLabel).parent().find(delegateDom).show()
        }
        $(this).parents(delegateLabel).data('deletefileid').push($(this).parents('.file-wrapper').find('.file-name').attr('originalid'));
        $(this).parents(displayListDom).prev().val(null);
        if( $(this).parents(delegateLabel).find('.file-wrapper').length == 1 ){
            $(this).parents(".file-wrapper").before('<span class="spanHolder">上传附件</span>');
        };
        $(this).parents(".file-wrapper").remove();

        return false;
    });
}
