<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title></title>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1,user-scalable=no">
	<meta name="apple-mobile-web-app-capable" content="yes">
	<meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0,viewport-fit=cover">
	<link rel="stylesheet" type="text/css" href="https://res.wx.qq.com/open/libs/weui/1.1.2/weui-for-work.min.css" />
	<link rel="stylesheet" type="text/css" th:href="@{/css/weixin-work/public.css}" />
	<style type="text/css">
	</style>
</head>
<body ontouchstart>
	<div class="page__bd" style="margin-bottom: 50px;">
		
		<!-- 图片预览窗口 -->
		<div class="weui-gallery" id="gallery">
            <span class="weui-gallery__img" id="galleryImg"></span>
            <div class="weui-gallery__opr">
                <a href="javascript:" class="weui-gallery__del">
                    <i class="weui-icon-delete weui-icon_gallery-delete"></i>
                </a>
            </div>
        </div>
		
		<!-- 上传文件 临时存储box -->
		<form id="form1" action="" method="post" enctype="multipart/form-data">
			<div id="file-list" style="display:none;"></div>
		</form>
		
		<div class="weui-cells weui-cells_form">
            <div class="weui-cell">
                <div class="weui-cell__bd">
                    <div class="weui-uploader" id="dbfilelist" style="margin-bottom: 15px;">
                        <div class="weui-uploader__hd">
                            <p class="weui-uploader__title">文件列表</p>
                        </div>
                    </div>
                    
                    <div class="weui-uploader">
                        <div class="weui-uploader__hd modifybox" style="display:none">
                            <p class="weui-uploader__title">文件上传</p>
                            <!-- <div class="weui-uploader__info">0/2</div> -->
                        </div>
                        <div class="weui-uploader__bd">
                            <ul class="weui-uploader__files" id="uploaderFiles"></ul>
                            <div class="weui-uploader__input-box modifybox">
                                <input id="uploaderInput" class="weui-uploader__input uploaderInput" type="file" accept="" multiple />
                            </div>
                        </div>
                    </div>
                    
		            <div class="weui-cells__title modifybox" style="display:none">标题</div>
			        <div class="weui-cells weui-cells_form modifybox" style="display:none">
			            <div class="weui-cell">
			                <div class="weui-cell__bd">
			                   <input class="weui-input" type="text" id="title" placeholder="请输入标题" maxlength="40" />
			                </div>
			            </div>
			        </div>
                </div>
            </div>
            
            <div class=weui-btn-area>
           		<a id="uploaderCustomBtn" href="javascript:;" class="weui-btn weui-btn_primary modifybox" style="display:none">上 传</a>
           		<a class="weui-btn weui-btn_default" href="javascript:history.back();">返 回</a>
			</div>
            
        </div>

	</div><!-- .page__bd -->

<script type="text/javascript" src="https://lib.baomitu.com/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.4.0.js"></script>
<script type="text/javascript" th:src="@{/js/weixin-work/public.js}"></script>
<script type="text/javascript" th:src="@{/js/weixin-work/example.js}"></script>
<script type="text/javascript">
var 
tmpl = '<li class="weui-uploader__file" style="background-image:url({url})" imgid="{imgid}"><div class="weui-uploader__file-content">{filename}</div></li>',
tmp2 = '<li class="weui-uploader__file weui-uploader__file_status" style="background-image:url({url})" imgid="{imgid}"><div class="weui-uploader__file-content">{filename}</div></li>',
$gallery = $("#gallery"), 
$galleryImg = $("#galleryImg"),
$uploaderInput = $("#uploaderInput"),
$uploaderFiles = $("#uploaderFiles");

var pid = null;

//获取上传的文件名，截掉盘符目录字符
function getFileName(filename){
	if(isBlank(filename))return filename;
	filename=filename.substr(filename.lastIndexOf("\\")+1, filename.length);
	return filename;
}

// 删除新添加的文件
function comfirmDelImg(){
	var imgid =  $galleryImg.attr("imgid");
	$('#uploaderFiles li').each(function(){
		if($(this).attr('imgid') == imgid)$(this).remove();
	});
	$('#file-list .tempfile').each(function(){
		if($(this).attr('imgid') == imgid)$(this).remove();
	});
	hideConfirmDialog();
	$gallery.fadeOut(100);
}

$(function(){
	pid = getQueryString('pid');
	if(!isBlank(pid)){
		getList();
	}
	
	getJsConfig();
	
	// 事件转移,将+号按钮点击事件转移到file里
	$uploaderInput.on("click", function(e){
		$('#file-list').append('<input type="file" name="updfile" class="tempfile">');
		$('#file-list .tempfile:last-child').click();
		return false;
		//$('#testfile').click();
    	//$("#testfile")[0].click();
	});
	
	// 选择文件,监听改变事件
//	$uploaderInput.on("change", function(e){
    $("#file-list").on("change", '.tempfile', function(e){
		var thisobj = $(this);
    	var filename = getFileName($(this).val());
        var src, url = window.URL || window.webkitURL || window.mozURL, files = e.target.files;
        for (var i = 0, len = files.length; i < len; ++i) {
            var file = files[i];
            if (url) {
           		src = url.createObjectURL(file);
            } else {
           		src = e.target.result;
            }
            var tmpHtml = tmp2;
      		if(filename.endWith('.jpg') || filename.endWith('.png') || filename.endWith('.icn')){
      			tmpHtml=tmpl;
      		}
      		$uploaderFiles.append($(tmpHtml.replace('{url}', src).replace('{imgid}', src).replace('{filename}', filename)));
      		thisobj.attr('imgid', src);
        }
    });
    
    // 点击小图预览大图
    $uploaderFiles.on("click", "li", function(){
		var imgid = $(this).attr("imgid");
       	$galleryImg.css("background-image", 'url('+imgid+')');
        $galleryImg.attr("imgid", imgid);
        $gallery.fadeIn(100);
        var filename = $(this).find('.weui-uploader__file-content').text();
        if(filename.endWith('.jpg') || filename.endWith('.png') || filename.endWith('.icn')){
        	$galleryImg.html('');
        	$galleryImg.css('text-align', 'center').css('margin','0');
        }else{
        	$galleryImg.html('该文件不可预览');
        	$galleryImg.css('text-align', 'center').css('color','#fff').css('margin-top','50%');
        }
    });
    
    // 点击大图直接关闭预览
    $galleryImg.on("click", function(){
        $gallery.fadeOut(100);
    });
    
    // 预览大图,点击删除按钮
    $gallery.on("click", ".weui-gallery__del", function(){
    	showConfirmDialog('确定要删除？',comfirmDelImg);
    });
    
    // 点击上传按钮
    $('#uploaderCustomBtn').click(function(){
		submitForm();
	});
    
    // 预览数据库查出来的附件(基于企业微信APP)
    $('#dbfilelist').on("click", ".previewfile", function(){
    	if(!isWeiXin()){
    		toastMsg('该浏览器暂不支持查看');
    		return;
    	}
    	var uuid = $(this).parent('.dbfileitem').attr('uuid');
    	var ext = $(this).parent('.dbfileitem').attr('ext');
    	var filename = $(this).parent('.dbfileitem').attr('filename');
    	var filesize = $(this).parent('.dbfileitem').attr('filesize');
    //	var fileurl = 'project/file/download.do?name='+name+'&uuid='+uuid+'&ext='+ext;
    //	上面通过download.do无法在微信里直接打开
    //	var fileurl = getSysBaseUrl()+'/upfiles/projectFiles/'+uuid+'.'+ext;
    	var fileurl = 'http://wx.szxgl.cn/oa'+'/upfiles/projectFiles/'+uuid+'.'+ext;
    	wx.checkJsApi({
    	    jsApiList: ['previewFile'], // 需要检测的JS接口列表，所有JS接口列表见附录2,
    	    success: function(res) {
    	        // 以键值对的形式返回，可用的api值true，不可用为false
    	        // 如：{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
    	        
    	  		wx.previewFile({
   	        	    url: fileurl, 			// 需要预览文件的地址(必填，可以使用相对路径)
   	        	    name: filename, 		// 需要预览文件的文件名(不填的话取url的最后部分)
   	        	 	size: filesize 			// 需要预览文件的字节大小(必填)
   	    		});
    	     	/* 
    	        if(res.checkResult.previewFile){ // 新版本这个不是true
    	        	
    	        }else{
    	        	toastMsg('该浏览器暂不支持查看');
    	        	return;
    	        }
    	      	*/
    	    }
    	});
    });
    
	// 删除数据库查出来的附件(基于企业微信APP)
    $('#dbfilelist').on("click", ".delfile", function(){
    	var projectId = $(this).parent('.dbfileitem').attr('projectId');
    	var id = $(this).parent('.dbfileitem').attr('dataid');
    	var uuid = $(this).parent('.dbfileitem').attr('uuid');
    	console.log('projectId='+projectId+', id='+id+'uuid='+uuid);
    	showConfirmDialog('确定要删除该文件吗？', function(){
    		hideConfirmDialog();
    		$.post('project/file/delOnWx.do', {projectId: projectId, id: id, uuid: uuid}, function(result){
    			var data = JSON.parse(JSON.stringify(result).trim());
    			if(data.statusCode == 200){
    				hideConfirmDialog();
    				toastMsg('删除成功！', 1);
    				getList();
    			}else{
    				toastMsg(data.message);
    			}
    		}, 'json');
    	});
    });
    
});

//查询记录列表
var list_item_html = 
	 '<div class="weui-uploader__hd dbfileitem" style="margin-left: 12px; color: gray;" projectId="{projectId}" dataid="{dataid}" uuid="{uuid}" filename="{filename}" filesize="{filesize}" ext="{ext}">'
	+'	<p class="weui-uploader__title">{shortfilename}</p>'
	+'	<a href="javascript:;" class="previewfile">查看</a>'
	+'	&nbsp;&nbsp;<a href="javascript:;" class="delfile" style="color:red; display:{showdel}">删除</a>'
	+'</div>';

function getList(){
	var params = {};
	params['offset'] = 1;
	params['limit'] = 100;
	params['pid'] = pid;
	showLoading();
	$.post('[[@{/mobile/api/project/file/getList}]]', params, function(result){
		hideLoading();
		var allowModify = result.allowModify;
		if(allowModify)$('.modifybox').show();
		else $('.modifybox').hide();
		
		if(result.total > 0){
			var items = result.rows;
			$('#dbfilelist .dbfileitem').remove();
			var html = '';
			for(var i in items){
				var files = items[i].files;
				if(files == null || $.trim(files)=='')continue;
				files = JSON.parse(files.replace(new RegExp('\"','g'),'"'));
				for(var j=0;j<files.length;j++){
				console.log('items[i] == '+JSON.stringify(items[i]));
				//	var fileurl = 'project/file/download.do?name='+files[j].name+'&uuid='+files[j].uuid+'&ext='+files[j].ext;
				//  上面通过download.do无法在微信里直接打开
				
				//	var fileurl = getSysBaseUrl()+'/upfiles/projectFiles/'+files[j].uuid+'.'+files[j].ext;
					var fileurl = 'http://wx.szxgl.cn/oa'+'/upfiles/projectFiles/'+files[j].uuid+'.'+files[j].ext;
					html += list_item_html.replaceAll("{projectId}", items[i].projectId).replaceAll("{dataid}", items[i].id)
					.replaceAll("{uuid}", files[j].uuid).replaceAll("{filename}", files[j].name).replaceAll("{shortfilename}", subString(files[j].name, 22))
					.replaceAll("{filesize}", files[j].size).replaceAll("{ext}", files[j].ext).replaceAll("{showdel}", allowModify ? "''" : "none");
				}
			}
			$('#dbfilelist').append(html);
		}else{
			$('#dbfilelist').append('<div class="weui-loadmore weui-loadmore_line dbfileitem"><span class="weui-loadmore__tips">暂无文件</span></div>');
		}
	}, 'json');
}

// 提交表单
function submitForm(){
	var title = $('#title').val();
	if(isBlank(title)){
		toastMsg('请输入标题');
		return;
	}
	var fd = new FormData();
	fd.append('projectId', pid);
	fd.append('title', title);
	var filenum = 0;
	$('#file-list .tempfile').each(function(){
		fd.append('file', $(this)[0].files[0]);
		filenum++;
	});
	if(filenum == 0){
		toastMsg('请上传附件');
		return;
	}
	
	$.ajax({
	    type: 'POST',
	    url: 'project/file/add.do',
	    data: fd,
	    dataType: 'json',
	    processData: false, // 不会将 data 参数序列化字符串
	    contentType: false, // 根据表单 input 提交的数据使用其默认的 contentType
		xhr: function() {
	        var xhr = new window.XMLHttpRequest();
	        xhr.upload.addEventListener("progress", function(evt) {
	            if (evt.lengthComputable) {
	                var percentComplete = (evt.loaded / evt.total)*100;
	                percentComplete=parseInt(percentComplete);
	                showLoading('上传中 '+percentComplete+'%');
	            }
	        }, false);
	        return xhr;
		},
		err: function(XMLHttpRequest, textStatus, errorThrown){
			hideLoading();
			console.error('textStatus='+textStatus+', errorThrown='+textStatus);
		},
		success: function(result){
			hideLoading();
			var data = JSON.parse(JSON.stringify(result).trim());
			if(data.statusCode == 200){
				toastMsg('保存成功！', 1);
				getList(); // 重新加载数据
				// 清空file
				$('#file-list').html(''); 
				$("#uploaderFiles").html('');
				$('#title').val('');
			}else{
				toastMsg(data.message);
			}
		}
	});
}
</script>
</body>
</html>