var currFilesList = null;

function FilesList(option){
    this.isSaveIds = option.isSaveIds || 0
    this.isSaveUrls = option.isSaveUrls || 0
    this.target = option.target || null
    this.close = option.close || 0
    this.isOpen = 1
}

FilesList.prototype = {
    loadFiles(files) {
        currFilesList = this;
        var fileIds = ""
        var fileUrls = ""
        var html = "";
        for (var i = 0; i < files.length; i++) {
            var file = files[i]
            html += this.getFileHtml(file)
            fileIds += file.id + ","
            fileUrls += file.url + ","
        }
        $("#" + this.target).append(html);
        if(this.isSaveIds)
            $("#fileIds").val($("#fileIds").val() + fileIds);
        if(this.isSaveUrls)
            $("#fileUrls").val($("#fileUrls").val() + fileUrls);
    },
    getFileHtml(file){
        var ext = file.url.substring(file.url.lastIndexOf('.') + 1);
        var html = "<div id='fileItemBox_"+file.id+"' class='fileItemBox' onmouseout=javascript:$('#file_float_" + file.id + "').css('display','none') onmouseover=javascript:$('#file_float_" + file.id + "').css('display','block') >"
        if(ext === "jpg" || ext === "jpeg" || ext === "png") {
            html += "<img src='/images/" + file.url + "' alt='" + file.id + "' height='100px' width='100px' class='layui-upload-img uploadImgPreView' />"
        }
        if(ext === "pdf"){
            html +='<div style="width: 100px;height: 100px;text-align: center;word-wrap: break-word; word-break: normal;">';
            html +='<img  src="/static/css/img/pdf.jpg" height="75px" width="75px" class="layui-upload-img uploadImgPreView"><br>'
            html +=file.url
            html += '</div>'
        }
        html +=	    '<div onclick=javascript:currFilesList.fileopen("/images/' + file.url + '")  id="file_float_' + file.id + '" class="float-div">'
        if(this.close){
            html +=          '<a onmouseout="javascript:currFilesList.isOpen=1" onmouseover="javascript:currFilesList.isOpen=0" href=javascript:currFilesList.removeFile('+file.id+',"'+file.url+'");>X</a>'
        }
        html +=     '</div>'
        html += '</div>'
        return html;
    },
    removeFile(fileId,fileUrl){
        currFilesList.isOpen=1
        var fileIds = $("#fileIds").val();
        fileIds = fileIds.replace(fileId + ",","")
        var fileUrls = $("#fileUrls").val();
        fileUrls = fileUrls.replace(fileUrl + ",","")
        $("#fileIds").val(fileIds)
        $("#fileUrls").val(fileUrls)
        var fileItemBox = document.getElementById("fileItemBox_"+ fileId);
        fileItemBox.parentNode.removeChild(fileItemBox);
    },
    fileopen(url){
        if(currFilesList.isOpen)
            window.open(url)
    }
}