<template>
    <div>
        <div>
            <Navbar title='新建任务'
                    :isGoBack="true"></Navbar>

            <div>
                <div class="form-group">
                    <label for="exampleInputEmail1">标题</label>
                    <input type="text"
                           class="form-control"
                           id="exampleInputEmail1"
                           placeholder="标题"
                           v-model="traceDto.summary">
                </div>
                <div class="form-group">
                    <label for="exampleInputPassword1">内容</label>
                    <div id="summernote"></div>
                </div>
                <AudioField @handleStop="handelEndRecord" :className = "className" :srcArray = "srcArray" @deleteAudioSrc = "deleteAudioSrc" :isReadonly = "'false'"/>
                <div class="form-group">
                    <label for="trackUserId">责任人</label>
                    <select id="trackUserId"
                            class="form-control"
                            v-model="userSelected">
                        <option value="" ></option>
                        <option :value="user.userId"
                                v-for="user in userList">{{user.userName}}</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="projectName">项目</label>
                    <select id="projectName"
                            class="form-control"
                            v-model="projectId"
                            :disabled="'projectId != null'?'true':'false'">
                        <option :value="project.projectItemId"
                                v-for="project in projectUserList">{{project.projectItemName}}</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="projectName">时间节点</label>
                    <Treeselect ref = "treeSelect" :multiple="false" :options="projectTaskDtos" />
                </div>
                <div class="form-group">
                    <label>完成时间</label>
                    <DateWidget @on-value-change="depreciationStartDateChanged" 
                                :dateValue="planFinishedDate"
                                class="form-control"
                                :readonly="isdisable"></DateWidget>
                              
                 </div><!--style="float:right;position:relative;top: -46px; right: 5px -->
                   <span class="glyphicon glyphicon-remove-circle"  style="float:right;top:-45px;left:-50px;position:relative;" @click="removeTime" ></span>  
                <button style="width:100%;background-color: #007aff;color: white"
                        @click="saveTrace()"
                        type="button"
                        class="btn btn-blue search-button">
                    保存
                </button>

            </div>
        </div>
        <Loading ref="loading"></Loading>
    </div>
</template>
<script type="text/javascript">
var Notify = require("pc-client-component").Notify;
var Common = require("../common/Common.js");
var Uuid = require("pc-client-component").Uuid;
var DynamicJsLoader = require("../common/DynamicJsLoader.js");
var UpladFile = require("../widget/UpladFile.js");

var Navbar = require("pc-client-component").Navbar;
var DateWidget = require("pc-client-component").Date;
var Loading = require("pc-client-component").Loading;
import Treeselect from "../widget/TreeSelect.vue";
var AudioField = require("../widget/AudioField.vue").default;
export default {
    data: function () {
        return {
            traceDto: {},
            className: "com.leanwo.prodog.Trace",
            userList: [],
            userSelected: '',
            projectUserList: [],
            planFinishedDate: '',
            isdisable: false, //日期框是否可编辑
            projectId: '', //项目Id
            summernoteInitSuccess: false, // summernote初始化成功
            projectTaskDtos:[],//项目任务时间点
            srcArray:[]
        }
    },
    components: {
        Navbar,
        Loading,
        Common,
        Notify,
        DynamicJsLoader,
        UpladFile,
        DateWidget,
        Treeselect,
        AudioField
    },
    methods: {
    	/**
    	 * 删除语音
    	 * @param {Object} index
    	 */
    	deleteAudioSrc:function(index){
			var _self = this;
			_self.srcArray.splice(index,1);
			_self.traceDto.audioSrcs = JSON.stringify(_self.srcArray);
		},
    	/**
    	 * 录音停止之后
    	 * @param {Object} param
    	 */
    	handelEndRecord: function(param) {
    		var _self = this;
		     if(param.fileName != undefined){
		     	_self.srcArray.push(param.fileName);
			    _self.traceDto.audioSrcs = JSON.stringify(_self.srcArray);
		     }
		},
        back: function () {
            history.back();
        },
        removeTime: function(){
           this.planFinishedDate = ''
        },
        saveTrace: function () {
            var _self = this;
            _self.traceDto.receiveUserId = _self.userSelected;//接收人Id
			_self.traceDto.projectTaskId = _self.$refs.treeSelect.getValue();
            if (_self.planFinishedDate != undefined && _self.planFinishedDate != "") {
                _self.traceDto.planFinishedDate = _self.planFinishedDate; //完成时间
            }
            _self.traceDto.projectId = _self.projectId;//项目Id

            _self.traceDto.detail = $('#summernote').summernote('code');
            if (_self.traceDto.summary != "" && _self.traceDto.summary != undefined) {
                _self.$refs.loading.show();
                $.ajax({
                    url: Common.getApiURL('TraceResource/saveTrace'),
                    type: 'post',
                    contentType: "application/json",
                    data: JSON.stringify(_self.traceDto),
                    beforeSend: function (request) {
                        Common.addTokenToRequest(request);
                    },
                    success: function (data) {
                        Notify.success("提示", "追踪成功！");
                        _self.$refs.loading.hide();
                        _self.back();
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        _self.$refs.loading.hide();
                        Common.processException(XMLHttpRequest, textStatus, errorThrown);
                    }
                });
            } else {
                Notify.error("提示", "标题不能为空！");
            }
        },

        //图片上传  
        sendFile: function (file, editor, $editable) {
            var _self = this;
            UpladFile.photoCompress(file, {
                quality: 1
            }, function (base64Codes) {
                var bl = UpladFile.convertBase64UrlToBlob(base64Codes);
                var rst = new FormData();
                rst.append("上传图片", bl, "file_" + Date.parse(new Date()) + ".jpg");
                rst.append("className", _self.className);
                $.ajax({
                    url: Common.getApiURL("file/imageUpload"),
                    type: "post",
                    data: rst,
                    contentType: false,
                    processData: false,
                    beforeSend : function(request){
						Common.addTokenToRequest(request);
					},
                    success: function (data) {
                        if (data != "error") {
                        	var imageName = data.substring(data.indexOf(":") + 1);
							$("#summernote").summernote('insertImage', Common.getResourceUrl("image", _self.className, imageName), 'image name');
                        }
                    },
                    error: function () {
                        Notify.error("提示", "上传失败！");
                        return;
                    }
                });
                return rst.file;
            });
        },

        /**
         * 初始化人员
         * @author ZhangTeng 20190213
         */
        initData: function () {
            var _self = this;
            _self.userList.splice(0, _self.userList.length);
            $.ajax({
                url: Common.getApiURL('ProjectItemUserResource/listByProjectItemId'),
                type: 'get',
                dataType: 'json',
                contentType: "application/json",
                data: { "projectItemId": _self.projectId },
                beforeSend: function (request) {
                    Common.addTokenToRequest(request);
                },
                success: function (data) {
                    if (data != null) {
                        for (var index = 0; index < data.length; index++) {
                            _self.$set(_self.userList, index, data[index]);
                            // if (index == 0) {
                            //     _self.userSelected = data[index].userId;
                            // }
                        }
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    Common.processException(XMLHttpRequest, textStatus, errorThrown);
                }
            });
        },

        /**
         * 初始化项目
         * @author ZhangTeng 20190213
         */
        initProject: function () {
            var _self = this;
            _self.projectUserList.splice(0, _self.projectUserList.length);
            $.ajax({
                url: Common.getApiURL('ProjectItemUserResource/listByUserId'), //查询所有的项目用户
                type: 'get',
                contentType: "application/json",
                beforeSend: function (request) {
                    Common.addTokenToRequest(request);
                },
                success: function (data) {
                    if (data != null) {
                        for (var index = 0; index < data.length; index++) {
                            _self.$set(_self.projectUserList, index, data[index]);
                        }
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    Common.processException(XMLHttpRequest, textStatus, errorThrown);
                }
            })
        },


        //日期选择
        depreciationStartDateChanged: function (value) {
            this.planFinishedDate = value
        },
        /**
         * 根据项目id查询项目任务时间节点
         * @author GuoZhiBo 20191010
         */
        queryProjectTaskDtoByProjectId: function(){
			var _self = this;
			$.ajax({
				url: Common.getApiURL('ProjectTaskResource/queryProjectTaskDtoByProjectId'),
				type: 'get',
				dataType: 'json',
				contentType: 'application/json',
				data: {
					projectId: _self.projectId
				},
				beforeSend: function(request) {
					Common.addTokenToRequest(request);
				},
				success: function(data) {
					_self.projectTaskDtos = data;
				},
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					Common.processException(XMLHttpRequest, textStatus, errorThrown);
				}
			});
		},
    },


    mounted: function () {
        var _self = this;
        this.projectId = this.$route.params.projectId;
        this.initProject();
        this.initData();
        DynamicJsLoader.loadSummernote(function () {
            $('#summernote').summernote({
            	toolbar:[
			        ['insert', ['link', 'picture', 'video', 'audio', 'hr', 'table', //插件
			        'fontname', 'fontsize', 'color', 'bold', 'italic', 'underline', 'strikethrough', 'clear',//字体样式
			        'style', 'ol', 'ul', 'paragraph', 'height',//段落样式
			        'fullscreen', 'codeview', 'undo', 'redo', 'help'//Misc
			        ]],
			    ],
                height: 400,
                minHeight: 300,
                maxHeight: 500,
                focus: true,
                lang: 'zh-CN',
                callbacks: {
                    onImageUpload: function (files, editor, $editable) {
                        _self.sendFile(files[0], editor, $editable);
                    },
                }
            });
            _self.summernoteInitSuccess = true;
        })
    },

    destroyed: function(){
        if(this.summernoteInitSuccess == true){
            $('#summernote').summernote('destroy');
        }
        //界面销毁时，修改插入连接的display属性
        $('.note-link-popover').removeAttr('style');
    },
	watch: {
		"projectId" : function(curVal, oldVal){
			var _self = this;
			_self.$refs.treeSelect.setValue(undefined);
			_self.queryProjectTaskDtoByProjectId();
		}
	}

}
</script>

<style scoped>
</style>