<template>
    <div>
        <div>
            <input ref="fileInput"
                   type="file"
                   class="form-control file-input"
                   @change="onFileChanges" />
            <label for="attachment">
                <a role="button"
                   class="btn btn-primary btn-sm"
                   @click="clickButton">
                    <i class="fa fa-upload" />
                    &nbsp;
                    上传附件
                </a>
            </label>
        </div>

        <div v-if="attachmentList != undefined && attachmentList.length > 0">
            <ul class="list-group">
                <template v-for="attachment in attachmentList">
                    <li class="list-group-item"
                        :key="attachment.id">
                        <span class="badge"
                              @click="deleteByTraceAttachmentId(attachment.id)">删除</span>
                        <span @click="download(attachment)"
                              class="badge">下载</span>
                        {{attachment.attachment}}
                    </li>
                </template>
            </ul>
        </div>
        <Loading ref="loading"></Loading>
    </div>
</template>

<script>
var Common = require("../common/Common.js");
var Notify = require("pc-client-component").Notify;
var DownloadService =require("pc-client-component").DownloadService;
var Loading = require("pc-client-component").Loading;

export default {
    props: ["traceId"],
    data: function () {
        return {
            className: "com.leanwo.prodog.model.trace.TraceAttachment",
            attachmentList: [],
            traceConfigDto:{}
        }
    },
    components: {
        Loading,DownloadService
    },
    methods: {

        /**
         * 下载文件
         * @param  {String} fileName 文件名
         * @return {void}          
         */
        download: function (item) {
             var _self = this;
			DownloadService.fileDownload(_self.className, item.attachment);
        },

        /**
         * 删除任务附件
         */
        deleteByTraceAttachmentId: function (traceAttachementId) {
            var _self = this;
            $.ajax({
                url: Common.getApiURL('TraceAttachmentResource/deleteByTraceAttachmentId'),
                type: 'get',
                dataType: 'json',
                data: {
                    'id': traceAttachementId
                },
                beforeSend: function (request) {
                    Common.addTokenToRequest(request);
                },
                success: function (data) {
                    if (data == false) {
                        Notify.error("提示", "您没有权限删除附件，只有任务发起人和附件上传人有权限删除附件！");
                        _self.listTraceAttachmentByTraceId();
                    } else {
                        _self.listTraceAttachmentByTraceId();
                    }
                },
            });
        },

        /* 选择文件发生改变
         * @param  {[type]} e [description]
         * @return {[type]}   [description]
         */
        onFileChanges: function (e) {
            var files = e.target.files || e.dataTransfer.files;
            if (!files.length)
                return;
            this.uploadFile(files[0]);
        },

        /**
         * 上传文件
         * @param  {File} selectedFile 选择的文件
         */
        uploadFile: function (selectedFile) {
            var _self = this;
            if (selectedFile == undefined) {
                return;
            }
            var size = undefined;
            if(_self.traceConfigDto.traceAttachmentSize != undefined && _self.traceConfigDto.traceAttachmentSize != null){
            	size = _self.traceConfigDto.traceAttachmentSize;
            }
            //当系统没有配置附件大小时默认8m
            if(size == undefined){
            	size = 8;
            }
            if ((selectedFile.size / 1024) <= (1024 * size)) {
	            var formData = new FormData();
	            formData.append("files", selectedFile);
	            formData.append("className", _self.className);
	            _self.$refs.loading.show();
	            $.ajax({
	                url: Common.getApiURL("file/classFileUpload"),
	                type: "post",
	                beforeSend: function (request) {
	                    Common.addTokenToRequest(request);
	                },
	                data: formData,
	                contentType: false,
	                processData: false,
	                success: function (data) {
	                    _self.$refs.loading.hide();
	                    if (data != "error") {
	                        var fileName = data.substring(data.indexOf(":") + 1);
	                        _self.uploadTraceAttachment(fileName);
	                    }
	                },
	                error: function (XMLHttpRequest, textStatus, errorThrown) {
	                    _self.$refs.loading.hide();
	                    Common.processException(XMLHttpRequest, textStatus, errorThrown);
	                }
	            });
	        } else {
                Notify.error("提示", "文件大小不能超过"+size+"M，可在任务配置功能中配置！");
            }
        },

		/**
		 * 获取任务管理配置
		 */
		getTraceConfig: function() {
			var _self = this;
			$.ajax({
				url: Common.getApiURL('TraceConfigResource/queryTraceConfigDto'),
				type: "get",
				dataType: "json",
				beforeSend: function(request) {
					Common.addTokenToRequest(request);
				},

				success: function(data) {
					_self.traceConfigDto = data;
				},
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					Common.processException(XMLHttpRequest, textStatus, errorThrown);
				}
			});
		},

        /**
         * 查询当前追踪单下所有的附件
         */
        listTraceAttachmentByTraceId: function () {
            var _self = this;
            $.ajax({
                url: Common.getApiURL("TraceAttachmentResource/listByTraceId"),
                type: "get",
                contentType: "application/json",
                beforeSend: function (request) {
                    Common.addTokenToRequest(request);
                },
                data: {
                    'traceId': _self.traceId,
                },
                success: function (data) {
                    console.log(data);
                    _self.attachmentList = data;
                },
            });
        },



        /**
         * 上传附件
         */
        uploadTraceAttachment: function (fileName) {
            var _self = this;
            var traceAttachement = {
                traceId: _self.traceId,
                attachment: fileName,
            };
            $.ajax({
                url: Common.getApiURL("TraceAttachmentResource/save"),
                type: "post",
                contentType: "application/json",
                beforeSend: function (request) {
                    Common.addTokenToRequest(request);
                },
                data: JSON.stringify(traceAttachement),
                success: function (data) {
                    _self.listTraceAttachmentByTraceId();
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    Common.processException(XMLHttpRequest, textStatus, errorThrown);
                    Notify.error("提示", "上传失败！");
                }
            });
        },

        
        /**
         * 点击上传按钮事件
         * @return {[type]} [description]
         */
        clickButton: function () {
            $(this.$refs.fileInput).click();
        },
    },

    mounted: function () {
        if (this.traceId != undefined) {
            this.listTraceAttachmentByTraceId();
        }
        this.getTraceConfig();
    },

    watch: {
        "traceId": function (curVal, oldVal) {
            if (curVal != undefined) {
                this.listTraceAttachmentByTraceId();
            }
        }
    }
}
</script>

<style scoped>
.badge {
    cursor: pointer;
    background-color: #428bca;
    color: white;
}
</style>

<style scoped>
.file-input {
    width: 0.1px;
    height: 0.1px;
    opacity: 0;
    overflow: hidden;
    position: absolute;
    z-index: -1;
}
</style>