<?xml version="1.0" encoding="UTF-8"?>
<h:screen xmlns:h="http://www.hand-china.com/hap">
    <link href="${base.contextPath}/resources/hls/imgPreview/viewer.css" rel="stylesheet" type="text/css"/>
    <script src="${base.contextPath}/resources/hls/imgPreview/viewer.js"></script>
    <script src="${base.contextPath}/resources/hls/imgPreview/image-view.js"></script>
    <link href="${base.contextPath}/resources/css/WECHAT/weChatPushNoticce.css" rel="stylesheet" type="text/css"/>
    <script src="${base.contextPath}/common/code?materialType=WECHAT.MATERIALTYPE" type="text/javascript"></script>

    <style>
        #sys-favicon-img {
            display: none;
            max-height: 100% !important;
            max-width: 100% !important;
        }

        #addPhotoClickId {
            display: block
        }

        #photo_del_btn {
            margin-left: 20px;
            cursor: pointer
        }

        #editor-div a:hover {
            color: blue
        }

        .k-grid-content {
            height: 315px !important;
        }

        #insertPic {
            position: absolute;
            width: 32px;
            height: 32px;
            top: 94px;
            left: 858px;
            border-color: #ccc;
            border-width: 1px;
            border-style: solid;
            background-color: #FFF;
        }

        #insertPic:hover {
            background-color: transparent;
        }

        #insertPic > img:hover {
            filter: invert(100%);
        }
    </style>
    <script id="script"><![CDATA[
    //========初始化相关数据=======================================================================================================
    /*封面预览*/
    var coverPreView = '';

    /*预览消息id*/
    var noticeId = '';

    var noticeType = 'TEXT';
    var currentId;
    var grid;
    var griddDataSource;
    var currentToken;
    var photoTextMsg = '';
    var photoFileId = '';
    var photoMsg = '';
    var photoTextTitle = '';
    var MsgData = '';
    var photoTitle = '';
    var qyid = '${RequestParameters.id!}';
    var name = getQueryString('name');
    var viewModel = kendo.observable({
        isEnabled: false,
        data: {
            noticeTitle: '',
            noticeMessage: '',
            description: '',
            author: '',
        },
        model: {},
        partyIds: '',
        tagIds: '',
        userIds: '',
        thumbMediaId: '',
        openIds: '',
        accountId: -1
    });
    function getQueryString(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return decodeURI(r[2]);
        return '';
    }
    $(document).ready(function (e) {
        $("#modify-btn-lov").kendoLov($.extend(${lovProvider.getLov(base.contextPath, base.locale, "WECHAT_ACCOUNT")}, {
            query: function (e) {
                e.param['enabledFlag'] = 'Y';
            },
            select: function (e) {
                id = e.item.id;
                viewModel.data.sourceDocumentId = e.item.id;
                viewModel.appId = e.item.id;
                qyid = e.item.accountId;
                viewModel.accountId = e.item.accountId;
                viewModel.userIds = '';
                viewModel.openIds = '';
                viewModel.tagIds = '';
                viewModel.partyIds = '';
            }
        }))
        $($(".k-input.con-title-modify")[0]).val(name);
        viewModel.data.accountName = name;
        $("#editor").kendoEditor({
            tools: ["fontName", "fontSize", "formatting", "bold", "italic", "underline", "strikethrough", "justifyLeft", "justifyCenter", "justifyRight", "justifyFull", "insertUnorderedList", "insertOrderedList", "indent", "outdent", "insertImage", "subscript", "superscript", "foreColor", "backColor",],
        });
        $("#editor-photo").hide();
        $(".back-btn")[0].innerHTML = "<<返回"
    });
    function gridData() {
        griddDataSource = new kendo.data.DataSource({
            transport: {
                read: {
                    url: "${base.contextPath}/wechat/notice/query",
                    dataType: "json"
                },
                parameterMap: function (options, type) {
                    if (type !== "read" && options.models) {
                        var datas = Hap.prepareSubmitParameter(options, type);
                        return kendo.stringify(datas);
                    } else if (type === "read") {
                        viewModel.model.sourceDocumentId = currentId || null;
                        return Hap.prepareQueryParameter(viewModel.model.toJSON(), options);
                    }
                }
            },
            batch: true,
            serverPaging: true,
            pageSize: 10,
            schema: {
                data: 'rows',
                total: 'total',
                model: {
                    id: "noticeId",
                }
            }
        });
        grid = $("#grid").kendoGrid({
            dataSource: griddDataSource,
            navigatable: true,
            sortable: false,
            resizable: true,
            scrollable: true,
            editable: false,
            pageable: {
                pageSizes: [5, 10, 20, 50],
                refresh: true,
                buttonCount: 5
            },
            columns: [
                {
                    field: "noticeStatus",
                    title: '<@spring.message "状态"/>',
                    width: 80,
                    headerAttributes: {style: "text-align: center"},
                    template: function (dataItem) {
                        if (dataItem.noticeStatus == 'DRAFT') {
                            return '草稿';
                        } else if (dataItem.noticeStatus == 'SEND') {
                            return '发送';
                        }
                    }
                },
                {
                    field: "noticeType",
                    title: '<@spring.message "消息类型"/>',
                    width: 100,
                    headerAttributes: {style: "text-align: center"},
                    sortable: false,
                    template: function (dataItem) {
                        if (dataItem.noticeType == 'TEXT') {
                            return '文字';
                        } else if (dataItem.noticeType == 'TEXT_PHOTO') {
                            return '图文';
                        } else if (dataItem.noticeType == 'PHOTO') {
                            return '图片';
                        }
                    }
                },
                {
                    field: "noticeTitle",
                    title: '<@spring.message "消息主题"/>',
                    width: 80,
                    headerAttributes: {style: "text-align: center"},
                    sortable: false,
                },
                {
                    field: "noticeDatetime",
                    title: '<@spring.message "时间"/>',
                    width: 100,
                    headerAttributes: {style: "text-align: center"},
                    sortable: false,
                },
                {
                    field: "",
                    title: '<@spring.message "操作"/>',
                    width: 100,
                    headerAttributes: {style: "text-align: center"},
                    attributes: {style: "text-align:center"},
                    sortable: false,
                    template: function (dataItem) {
                        return '<div style="width: 42px;height: 1px;float: left;"></div><div MsgData=\'' + dataItem.noticeMessage + '\' ' +
                            'token="' + dataItem._token + '" ' +
                            'id="operation_' + dataItem.noticeId + '" ' +
                            'class="operation-btn" ' + 'fileId="' + dataItem.fileId + '"' +
                            'onclick="editorOperation(\'' + dataItem.noticeId + '\',\'' + dataItem.noticeType + '\',\'' + dataItem.noticeTitle + '\',\'' + dataItem.description + '\',\'' + dataItem.author + '\',\'' + dataItem.sourceDocumentId + '\')">' +
                            '编辑</div><div class="operation-btn">|</div>' +
                            '<div class="operation-btn" onclick="deleteOperation(\'' + dataItem.noticeId + '\')">删除</div>';
                    }
                },
            ]
        }).data("kendoGrid");
    }

    //========点击函数=======================================================================================================

    //切换文/字图文/图片
    function clickLi(this_node) {
        var e = this_node.getAttribute("title-type");
        for (var m = 0; m < $(".typtLi").length; m++) {
            $(".typtLi")[m].setAttribute("class", "typtLi");
        }
        this_node.setAttribute("class", "typtLi color-blue");
        noticeType = e;
        var addText = $(".test-area")[0] ? $(".test-area")[0].innerHTML : '请输入内容';
        if (e == 'TEXT') {
            if (!!MsgData) {
                $("#editor-div")[0].innerHTML = "<textarea onfocus='focusEvent(this)' onblur='blurEvent(this)' class='test-area'>" + MsgData + "</textarea>";
            } else {
                $("#editor-div")[0].innerHTML = "<textarea onfocus='focusEvent(this)' onblur='blurEvent(this)' class='test-area'>" + addText + "</textarea>";
            }
        } else if (e == 'TEXT_PHOTO') {
            if (!photoTextMsg && !photoTextTitle) {
                appendPhotoTextHtml();
            } else {
                appendData();
//                $("#appendImg").append($(photoTextMsg.replace(new RegExp("&quot;","g"),'"')));
            }
        } else if (e == 'PHOTO') {
            if (!photoFileId) {
                appendPhotoHtml();
            } else {
                $("#editor-div")[0].innerHTML = "<div id='wechat_photo' onclick='f(this)' class='test-photot-div addphoto'>" +
                    "<img id='sys-favicon-img' name='favicon' src='${base.contextPath}/sys/attach/file/detail?fileId=" + photoFileId + "&token=" + currentToken + "' style='max-width: 148px;max-height: 148px;height: 148px'/></div>";
                $("#editor-div").append('<div id="del-perview-div-a"><a imageIndex="preview' + photoFileId + '" ' +
                    'href="${base.contextPath}/sys/attach/file/detail?fileId=' + photoFileId + '&token=' + currentToken + '">预览</a>' +
                    '<a id="photo_del_btn" onclick="appendPhotoHtml(this)">删除</a></div>');
                $("#sys-favicon-img")[0].style.display = "block";
            }
        }
    }
    //第一进入图文界面拼接图文的html
    function appendPhotoTextHtml() {
        $("#editor-div")[0].innerHTML = "<div onclick='addPhoText()' class='test-photot-div addPhotoText'><div class='add-click'>+</div><div class='add-text'>添加图文</div></div>"
    }
    //第一次进入图片界面拼接图片html
    function appendPhotoHtml() {
        document.getElementById("photoUp").innerHTML = ' <input style="display: none" id="fphotoUp" type="file" name="file" accept="image/gif, image/jpeg, image/png" onchange="uploadPhoto()"/>'
        viewModel.photoFileName = '';
        $("#editor-div")[0].innerHTML = "<div id='wechat_photo' onclick='fPhoto()' class='test-photot-div addphoto'>" +
            "<div id='addPhotoClickId'><div class='add-click'>+</div><div class='add-text'>添加图片</div></div>" +
            "<img id='sys-favicon-img' name='favicon' src='' width='148' height='148' /></div>";
    }
    //点击图文
    function addPhoText() {
        $("#editor-home").hide();
        $("#editor-photo").show();
    }
    function focusEvent(this_node) {
        if (this_node.value == '请输入内容') {
            this_node.value = '';
        }
    }
    function blurEvent(this_node) {
        if (this_node.value == '') {
            this_node.value = "请输入内容";
        } else {
            MsgData = this_node.value
        }
    }
    //返回
    function reBack() {
        $("#editor-home").show();
        $("#editor-photo").hide();
    }
    //点击发送/send/wechat/msg/notice
    function sendMsg() {
        if (viewModel.appId == undefined) {
            kendo.ui.showErrorDialog({
                title: "提示",
                message: "请先选择应用"
            })
        } else {
            kendo.ui.showConfirmDialog({
                title: "发送",
                message: "确定要发送吗？"
            }).done(function (e) {
                if (e.button == 'OK') {
                    var mask = $("body").mLoading('正在发送.....');
                    var obj = {};
                    saveDra();
                    //fixme
                    if (noticeType == 'TEXT_PHOTO') {
                        obj.account = viewModel.accountId;
                        obj.appId = viewModel.appId;
                        obj.userIds = viewModel.userIds;
                        obj.partyIds = viewModel.partyIds;
                        obj.tagIds = viewModel.tagIds;
                        obj.openIds = viewModel.openIds;

                        obj.articles = [{
                            url: window.location.origin + "${base.contextPath}/weChat/review.view?noticeId=" + noticeId,
                            picUrl: window.location.origin + viewModel.data.picUrl,
                            description: viewModel.data.description,
                            title: photoTextTitle,
                            content: photoTextMsg,
                            author: viewModel.data.author,
                            showCoverPic: true,
                            thumbMediaId: viewModel.thumbMediaId
                        }];

                        var dataObj = JSON.stringify(obj);
                        var contentType = "application/json; charset=utf-8";
                        var url = '${base.contextPath}/wechat/message/send/MPNews'
                    } else if (noticeType == 'PHOTO') {
                        /*obj.msgType = 'image';
                         obj.mediaId = photoFileId;//上传图片的id*/
                        var dataObj = JSON.stringify({
                            accountId: viewModel.accountId,
                            appId: viewModel.appId,
                            fileName: viewModel.photoFileName,
                            userIds: viewModel.userIds,
                            partyIds: viewModel.partyIds,
                            tagIds: viewModel.tagIds,
                            openIds: viewModel.openIds,
                        })
                        var contentType = "application/json; charset=utf-8";
                        var url = "${base.contextPath}/wechat/message/send/image";

                    } else if (noticeType == 'TEXT') {
                        var dataObj = JSON.stringify({
                            accountId: viewModel.accountId,
                            appId: viewModel.appId,
                            userIds: viewModel.userIds,
                            partyIds: viewModel.partyIds,
                            tagIds: viewModel.tagIds,
                            openIds: viewModel.openIds,
                            text: MsgData
                        });

                        var contentType = "application/json; charset=utf-8";
                        var url = '${base.contextPath}/wechat/message/send/text'
                    }
                    var saveObj = $.extend(true, {}, obj);
                    saveObj.noticeStatus = "send";
                    saveObj.id = qyid;

                    if (checkData(obj, mask)) {
                        $.ajax({
                            /*${base.contextPath}/send/wechat/msg/notice*/
                            url: url,
                            contentType: contentType,
                            type: "POST",
                            dataType: 'json',
                            data: dataObj,
                            success: function (datas) {
                                if (!datas.success) {
                                    kendo.ui.showInfoDialog({
                                        title: $l('提示'),
                                        message: "发送失败"
                                    }).done(function (e) {
                                        mask.destroy();
                                    });
                                } else {
                                    kendo.ui.showInfoDialog({
                                        title: $l('提示'),
                                        message: "发送成功"
                                    }).done(function (e) {
                                        /*obj.noticeStatus = 'SEND';
                                         obj.id = qyid;
                                         saveDra();*/
                                        mask.destroy();
                                    })
                                    ;
                                }
                            }
                        });
                    }
                }
            })
        }
    }

    //发送数据校验
    function checkData(obj, mask) {
        if (noticeType == 'TEXT_PHOTO') {
            for (var key in obj) {
                if (key != "partyIds" && key != "tagIds" && key != "openIds" && key != "userIds") {
                    if (obj[key] == undefined || obj[key] == '') {
                        kendo.ui.showErrorDialog({
                            title: $l('提示'),
                            message: "信息未填完整"
                        }).done(function (e) {
                            mask.destroy();
                        })
                        return false;
                    }
                    if (key == "articles") {
                        var arr = obj[key];
                        for (var i = 0; i < arr.length; i++) {
                            for (var k in arr[i]) {
                                if (arr[i][k] == undefined) {
                                    kendo.ui.showErrorDialog({
                                        title: $l('提示'),
                                        message: "信息未填完整"
                                    }).done(function (e) {
                                        mask.destroy();
                                    })
                                    return false;
                                }
                            }
                        }
                    }
                }
            }
        } else if (noticeType == 'PHOTO') {
            if (viewModel.photoFileName == undefined || viewModel.photoFileName == '') {
                kendo.ui.showErrorDialog({
                    title: $l('提示'),
                    message: "信息未填完整"
                }).done(function (e) {
                    mask.destroy();
                })
                return false;
            }
        } else if (noticeType == 'TEXT') {
            if (MsgData == undefined || MsgData == '') {
                kendo.ui.showErrorDialog({
                    title: $l('提示'),
                    message: "信息未填完整"
                }).done(function (e) {
                    mask.destroy();
                })
                return false;
            }
        }
        return true;
    }

    function getObjData() {
        var obj = {};
        obj.sourceDocumentId = qyid;
        obj.noticeStatus = 'DRAFT';
        obj.noticeType = noticeType;
        if (noticeType == 'TEXT_PHOTO') {
            obj.description = viewModel.data.description;
            obj.author = viewModel.data.author;
            obj.noticeMessage = photoTextMsg;
            obj.noticeTitle = photoTextTitle;
        } else if (noticeType == 'PHOTO') {
            obj.fileId = photoFileId;
            obj.noticeTitle = photoTitle;
        } else if (noticeType == 'TEXT') {
            obj.noticeMessage = MsgData;
        }
        return obj;
    }
    //存为草稿
    function saveDra() {
        var obj = getObjData();
        $.ajax({
            url: '${base.contextPath}/wechat/notice/add',
            dataType: 'json',
            data: obj,
            success: function (datas) {
                if (datas.length > 0) {
                    $("#li-save").click();
                    noticeId = datas[0].noticeId;
                } else {
                    kendo.ui.showInfoDialog({
                        title: $l('提示'),
                        message: "保存失败"
                    });
                }
            }
        });
    }

    //预览
    function preMsg(noticeId) {
        if (noticeId == '') {
            kendo.ui.showErrorDialog({
                title: $l('提示'),
                message: "请先保存草稿"
            })
        } else {
            Hls.openBox({
                url: "${base.contextPath}/weChat/review.view?noticeId=" + noticeId,
                winId: "editWin",
                width: "410px"
            })
        }
    }

    //定时发送
    function setDateSend() {
    }
    //消息tab也切换
    function noticeTab(this_node) {
        var tab = this_node.getAttribute("tab");
        for (var i = 0; i < $(".title-class li").length; i++) {
            $(".title-class li")[i].setAttribute("class", "");
        }
        this_node.setAttribute("class", "backgroundColor-grey");
        if (tab == 'send') {
            $("#send-notice-div").show();
            $("#look-notice-div").hide();
            $("#pro-notice-div").hide();
        } else if (tab == 'save') {
            $("#send-notice-div").hide();
            $("#look-notice-div").show();
            $("#pro-notice-div").hide();
            lookNoticePage();
        } else if (tab == 'pro') {
            $("#pro-notice-div").show();
            $("#look-notice-div").hide();
            $("#send-notice-div").hide();
        }
    }
    //点击已发送
    function lookNoticePage() {
        $.ajax({
            url: '${base.contextPath}/wechat/notice/enterprise/query',
            dataType: 'json',
            success: function (datas) {
                var appendHtml = '';
                appendHtml += '<ul>';
                appendHtml += '<li onclick="clickNoticeLi(this)" class="backgroundColor-grey" sourceDocumentId="">全部消息</li>'
                for (var j = 0; j < datas.length; j++) {
                    appendHtml += '<li onclick="clickNoticeLi(this)" sourceDocumentId="' + datas[j].accountId + '">' + datas[j].name + '</li>'
                }
                appendHtml += '</ul>';
                $("#left-menu")[0].innerHTML = appendHtml;
            }
        });
        gridData();
    }
    //点击已发送左边菜单
    function clickNoticeLi(this_node) {
        for (var h = 0; h < $("#left-menu li").length; h++) {
            $("#left-menu li")[h].setAttribute("class", "");
        }
        this_node.setAttribute("class", "backgroundColor-grey");
        currentId = this_node.getAttribute("sourceDocumentId");
        $("#grid").data("kendoGrid").dataSource.page(1);
    }
    //清空
    function emptyData() {
        photoFileId = '';
        photoTitle = '';
        photoTextMsg = '';
        photoTextTitle = '';
        MsgData = '';
        $(".ww_editorTitle")[0].value = "";
        $("#editor-photo iframe")[0].contentWindow.document.body.innerHTML = "";
        $("#description").val("");
        $("#author").val("");
    }
    //点击grid编辑
    function editorOperation(id, type, title, description, author, docId) {
        noticeId = id;
        qyid = docId;
        emptyData();
        currentToken = $("#operation_" + id)[0].getAttribute("token");
        if (type == 'TEXT') {
            MsgData = $("#operation_" + id)[0].getAttribute("MsgData");
            $("#typeLiText").click();
        } else if (type == 'TEXT_PHOTO') {
            $("#description").val(description);
            $("#author").val(author);
            $(".ww_editorTitle")[0].value = title;
            photoTextMsg = $("#operation_" + id)[0].getAttribute("MsgData");
            photoTextTitle = title;
            //设置主要内容
            $("#editor-photo iframe")[0].contentWindow.document.body.append($("<div>" + photoTextMsg + "</div>")[0]);
            $("#typeLiTextPhoto").click();
            appendData();
//            $("#appendImg").append($(photoTextMsg.replace(new RegExp("&quot;","g"),'"')));
        } else if (type == 'PHOTO') {
            photoMsg = $("#operation_" + id)[0].getAttribute("MsgData");
            photoFileId = $("#operation_" + id)[0].getAttribute("fileId");
            $("#typeLiPhoto").click();
        }
        $("#li-send").click();
    }
    //点击grid删除
    function deleteOperation(noticeId) {
        kendo.ui.showConfirmDialog({
            title: "删除",
            message: "确定要删除吗？"
        }).done(function (event) {
            if (event.button == 'OK') {
                $.ajax({
                    url: '${base.contextPath}/wechat/notice/delete',
                    dataType: 'json',
                    data: {noticeId: noticeId},
                    success: function (datas) {
                        if (datas.success) {
                            kendo.ui.showInfoDialog({
                                title: $l('提示'),
                                message: "删除成功"
                            }).done(function (e) {
                                $("#grid").data("kendoGrid").dataSource.page(griddDataSource._page);
                            });
                        } else {
                            kendo.ui.showInfoDialog({
                                title: $l('提示'),
                                message: "删除失败"
                            });
                        }
                    }
                });
            }
        })
    }
    //获取数据
    function getData() {
        photoTextTitle = $(".ww_editorTitle")[0].value || '';
        photoTextMsg = $("#editor-photo iframe")[0].contentWindow.document.body.innerHTML || '';
        viewModel.data.description = $("#description").val() || '';
        viewModel.data.author = $("#author").val() || '';
    }
    //完成后拼接数据
    function appendData() {
        var str = '';
        str += '<div onclick="addPhoText()" class="test-photot-div"><div>' + photoTextTitle || '' + '</div>';
        //富文本框格式转换（cdata）
        str += coverPreView;
        str += '<div id="appendImg">' + photoTextMsg.replace(new RegExp("&lt;", "g"), "<").replace(new RegExp("&gt;", "g"), ">") + '</div>';
        str += '<div>' + viewModel.data.description || '' + '</div></div>';
        $("#editor-div")[0].innerHTML = str;
    }
    //完成编辑
    function complateEditor() {
        getCover();
        getData();
        reBack();
        appendData();
    }
    //上传封面
    function getCover() {
        var formData = new FormData($("#coverPic")[0]);
        //判断应用类型
        if (viewModel.accountId == undefined || viewModel.appId == undefined || viewModel.accountId == -1) {
            kendo.ui.showErrorDialog({
                title: $l('提示'),
                message: "请先在lov选择应用"
            })
        } else {
            $.ajax({
                url: "${base.contextPath}/wechat/account/judgeType?accountId=" + viewModel.accountId + "&appId=" + viewModel.appId,
                type: "GET",
                dataType: "json",
                success: function (datas) {
                    switch (datas) {
                        case -1:
                            kendo.ui.showErrorDialog({
                                title: $1('提示'),
                                message: "lov选择的应用信息错误"
                            })
                            break;
                        case 1:
                            $.ajax({
                                url: "${base.contextPath}/wechat/message/upload/picture",
                                async: false,
                                cache: false,
                                processData: false,
                                type: "POST",
                                dataType: "json",
                                data: formData,
                                contentType: false,
                                success: function (datas) {
                                    viewModel.data.picUrl = "${base.contextPath}/wechat/message/download?fileName=" + datas;
                                    coverPreView = '<img src="' + viewModel.data.picUrl + '"></img>';
                                },
                                error: function () {
                                    kendo.ui.showErrorDialog({
                                        title: $l('提示'),
                                        message: "保存封面失败"
                                    })
                                }
                            })
                            break;
                        default:
                            formData.append("accountId", viewModel.accountId);
                            $.ajax({
                                url: "${base.contextPath}/wechat/message/upload/thumbPicture",
                                async: false,
                                cache: false,
                                processData: false,
                                type: "POST",
                                dataType: "json",
                                data: formData,
                                contentType: false,
                                success: function (datas) {
                                    viewModel.thumbMediaId = datas.mediaId;
                                },
                                error: function () {
                                    kendo.ui.showErrorDialog({
                                        title: $l('提示'),
                                        message: "保存封面失败"
                                    })
                                }
                            })
                    }
                }
            })
        }
    }

    //选择发送范围
    function openAddress() {
        var url = "${base.contextPath}/weChat/selectReceiver.view?accountId=" + viewModel.accountId;
        if (viewModel.userIds != '') {
            url += "&userIds=" + viewModel.userIds;
        }
        if (viewModel.openIds != '') {
            url += "&openIds=" + viewModel.openIds;
        }
        if (viewModel.partyIds != '') {
            url += "&partyIds=" + viewModel.partyIds;
        }
        if (viewModel.tagIds != '') {
            url += "&tagIds=" + viewModel.tagIds;
        }
        Hls.openBox({
            url: url,
            winId: "editWin",
            width: "480px"
        })
        /* var editWin = $("#editWin").kendoWindow({
         actions: ["Maximize", "Minimize", "Close"],
         width: 550,
         height: 550,
         title: '通讯录',
         content: url/!* + '&departmentIds=' + departmentIds + '&tags=' + tags*!/,
         iframe: true,
         visible: false,
         modal: true,
         close: function () {
         }
         }).data("kendoWindow");
         editWin.center().open();*/
    }

    //==============图片上传预览=======================================================================================================

    var preview = function (file, container) {
        if (!!$("#addPhotoClickId")[0]) $("#addPhotoClickId")[0].style.display = "none";
        if (!!$("#sys-favicon-img")[0]) $("#sys-favicon-img")[0].style.display = "block";
        var container = document.getElementById(container), path = '';
        if (file && file.files.length > 0) {
            //setTimeout('$("#file").select();', 1);
            if (window.navigator.userAgent.indexOf("MSIE") >= 1) {
                file.select();
                if (window.getSelection) {
                    path = window.getSelection();
                } else if (window.document.getSelection) {
                    path = window.document.getSelection();
                } else if (window.document.selection) {
                    path = window.document.selection.createRange().text;
                }
            } else if (window.navigator.userAgent.indexOf("Firefox") >= 1) {
                if (file.files) {
                    path = window.URL.createObjectURL(file.files[0]);
                } else {
                    path = file.value;
                }
            } else if (window.navigator.userAgent.indexOf("Chrome") >= 1) {
                path = window.webkitURL.createObjectURL(file.files[0]);
            }
            container.src = path;
//            photoFileId = path;
            photoTitle = file.files[0].name;
        }
    }

    ]]></script>
    <div id="editWin"></div>
    <!-- start -->
    <form id="attForm" style="border: none">
        <!-- 定义一些隐藏的input框，用户对信息做一个存储，以便于下面上传的时候获取 -->
        <input type="hidden" id="sourceKey" name="sourceKey"/>
        <input type="hidden" id="id" name="id"/>
        <input type="hidden" id="name" name="name"/>
        <input type="hidden" id="type" name="type"/>
        <input type="hidden" id="uploadDate" name="uploadDate"/>
        <input type="hidden" id="size" name="size"/>
        <input type="hidden" id="fileId" name="fileId"/>
    </form>
    <input style="border:none; display:none;" type="file" name="files" id="files"
           onChange="preview(this,'sys-favicon-img');"/>
    <!-- end -->

    <div id="addPhotoText"/>
    <div class="body">

        <div id="editor-home">
            <div class="title-class">
                <ul>
                    <li id="li-send" class="backgroundColor-grey" tab="send" onclick="noticeTab(this)">发消息</li>
                    <li id="li-save" style="border-left: 0px;/*border-right: 0px*/" tab="save"
                        onclick="noticeTab(this)">
                        已发送
                    </li>
                    <!--<li id="li-pro" tab="pro" onclick="noticeTab(this)">素材库</li>-->
                </ul>
            </div>

            <div id="send-notice-div" class="send-conetent-class">
                <div class="con-title-div">
                    <span>应用名称：</span><!--<input readonly id="con-title">-->
                    <div name="modify-btn" id="modify-btn-lov" class="con-title-modify"/>
                </div>
                <div class="con-size-div">
                    <a class="con-size" onclick="openAddress()">选择发送范围</a>
                </div>
                <div class="con-text">
                    <div class="con-text-title">
                        <ul>
                            <li class="typtLi color-blue" id="typeLiText" title-type="TEXT" onclick="clickLi(this)">文字
                            </li>
                            <li class="typtLi" id="typeLiTextPhoto" title-type="TEXT_PHOTO" onclick="clickLi(this)">图文
                            </li>
                            <li class="typtLi" id="typeLiPhoto" title-type="PHOTO" onclick="clickLi(this)">图片</li>
                            <!--<li title-type="VOICE" onclick="clickLi('VOICE')">语音</li>-->
                            <!--<li title-type="VIDEO" onclick="clickLi('VIDEO')">视频</li>-->
                            <!--<li title-type="FILE" onclick="clickLi('FILE')">文件</li>-->
                        </ul>
                    </div>
                    <form id="photoUp">

                        <input style="display: none" id="fphotoUp" type="file" name="file"
                               accept="image/gif, image/jpeg, image/png"
                               onchange="uploadPhoto()"/>
                    </form>
                    <div id="editor-div">
                        <textarea class='test-area' onfocus="focusEvent(this)" onblur="blurEvent(this)">请输入内容</textarea>
                        <script><![CDATA[
                        var sourseCode;
                        function f(e) {
                            /*判断上传的是图文还是图片*/
                            if (e.id == "wechat_photo") {
                                sourseCode = "WECHAT_PHOTO"
                            } else if (e.id = "insertPhoto") {
                                sourseCode = "INSERT_PHOTO"
                            }
                            $("#files").click();
                        }
                        /*上传图片*/
                        function fPhoto() {
                            $("#fphotoUp").click();
                        }

                        /*点击确定后*/
                        function uploadPhoto() {
                            if (!!$('#del-perview-div-a')[0]) {
                                $("#del-perview-div-a").remove();
                            }
//                            $("#editor-div").append('<div id="del-perview-div-a"><a imageIndex="preview' + fileId + '" href="${base.contextPath}/sys/attach/file/detail?fileId=' + fileId + '&token=' + myToken + '">预览</a><a id="photo_del_btn" onclick="appendPhotoHtml(this)">删除</a></div>');

                            /*$("[name='appId']").val(viewModel.appId);*/
                            $.ajax({
                                url: "${base.contextPath}/wechat/message/upload/picture",
                                async: false,
                                cache: false,
                                processData: false,
                                type: "POST",
                                dataType: "json",
                                data: new FormData($("#photoUp")[0]),
                                contentType: false,
                                success: function (datas) {
                                    viewModel.photoFileName = datas;
                                    $("#editor-div")[0].innerHTML = "<div id='wechat_photo' onclick='fPhoto()' class='test-photot-div addphoto'>" +
                                        "<img id='sys-favicon-img' name='favicon' src='${base.contextPath}/wechat/message/download?fileName=" + datas + "' style='max-width: 148px;max-height: 148px;height: 148px'/></div>";
                                    $("#editor-div").append('<div id="del-perview-div-a"><a href="${base.contextPath}/wechat/message/download?fileName=' + datas + '">预览</a><a id="photo_del_btn" onclick="appendPhotoHtml(this)">删除</a></div>');
                                    $("#sys-favicon-img")[0].style.display = "block";
                                }
                            })
                        }

                        //定义文件上传
                        $("#files").kendoUpload({
                            async: {
                                saveUrl: "${base.contextPath}/sys/attach/upload?${_csrf.parameterName}=${_csrf.token}",
                                removeUrl: "${base.contextPath}/sys/attach/remove"
                            },
                            showFileList: false,
                            upload: onUpload,
                            success: onSuccess
                        });

                        function onSuccess(e) {
                            kendo.ui.showInfoDialog({
                                title: '提示信息',
                                message: e.response.message
                            });
                            if (e.response.success) {
                                var fileId = e.response.rows[0].fileId;
                                var myToken = e.response.rows[0]._token;
                                currentToken = myToken;
                                photoFileId = fileId;
                                if (!!$('#del-perview-div-a')[0]) {
                                    $("#del-perview-div-a").remove();
                                }
                                if (sourseCode == "WECHAT_PHOTO") {
                                    $("#editor-div").append('<div id="del-perview-div-a"><a imageIndex="preview' + fileId + '" href="${base.contextPath}/sys/attach/file/detail?fileId=' + fileId + '&token=' + myToken + '">预览</a><a id="photo_del_btn" onclick="appendPhotoHtml(this)">删除</a></div>');
                                } else if (sourseCode == "INSERT_PHOTO") {
                                    $("#editor-photo iframe")[0].contentWindow.document.body.innerHTML += '<img src="${base.contextPath}/sys/attach/file/download?fileId=' + fileId + '&token=' + myToken + '"></img>'
                                }
                            }
                        }
                        //校验上传文件的格式是否正确
                        function onUpload(e) {
                            var files = e.files;
                            $.each(files, function () {
                                $("#size").val(this.size);
                                $("#uploadDate").val(this.rawFile.lastModifiedDate);
                                $("type").val(this.rawFile.type);
                                $("#name").val(this.name);
                            });
                            e.data = {
                                sourceType: sourseCode,
                                sourceKey: id,
                                id: $("#id").val(),
                                name: $("#name").val(),
                                type: $("type").val(),
                                lastModifiedDate: $("#uploadDate").val(),
                                size: $("#size").val()
                            }
                        }
                        ]]></script>
                    </div>

                    <!-- <div class="secret-div-btn"><input type="checkbox"/>保密<span style="margin-left: 10px">开启保密后，文章详情页面将印有收件人姓名</span>
                     </div>-->
                </div>
                <div class="btn-class">
                    <div class="send-btn" onclick="sendMsg()">发送</div>
                    <!--<div class="send-save-btn" onclick="setDateSend()">定时发送</div>-->
                    <div class="send-save-btn" onclick="saveDra()">存为草稿</div>
                    <div class="preview" onclick="preMsg(noticeId)">预览</div>
                    <span style="">*预览前必须要保存草稿</span>
                </div>
            </div>

            <div class="look-notice-div" id="look-notice-div">
                <div class="left-menu" id="left-menu"></div>
                <div class="notice-grid" id="notice-grid">
                    <div id="grid"/>
                </div>
            </div>

            <div id="pro-notice-div" style="display: none">
                <script><![CDATA[
                function schemaError() {

                }
                function dsEditable() {
                    return true;
                }

                function parameterMap(options, type) {
                    if (type !== "read" && options.models) {
                        var datas = options.models;
                        if (type == 'create' || type == 'update') {
                            datas = options.models.map(function (data) {
                                data['__status'] = (type == 'create' ? 'add' : 'update');
                                return data;
                            })
                        }
                        return kendo.stringify(datas);
                    } else if (type === "read") {
                        var map = {};
                        map.page = options.page;
                        map.pagesize = options.pageSize;
                        for (var k in map) {
                            if (map[k] === '' || map[k] === null || map[k] === undefined)
                                delete map[k]
                        }
                        return map;
                    }
                }
                function gridLocate(e) {
                    var d = this.dataItem(e.element);
                }
                function requestError() {

                }
                function detailTemp(dataItem) {
                    return '<a onclick="openDetail(' + dataItem.materialId + ')">详细</a>'
                }
                function openDetail(materialId) {
                    var editWin = $("#editWin").kendoWindow({
                        actions: ["Close"],
                        width: 910,
                        height: 500,
                        title: '详细信息',
                        content: '${base.contextPath}/weChat/wechat_material_info.view?materialId=' + materialId,
                        iframe: true,
                        visible: false,
                        modal: true,
                        close: function () {
                        }
                    }).data("kendoWindow");
                    editWin.center().open();
                }
                function typeEditor(container, options) {
                    $('<input name="' + options.field + '"/>')
                        .appendTo(container)
                        .kendoDropDownList({
                            dataTextField: "meaning",
                            dataValueField: "value",
                            valuePrimitive: true,
                            dataSource: materialType
                        });
                }
                function typeTemp(dataItem) {
                    var result = '';
                    materialType.forEach(function (value, index, array) {
                        if (dataItem.type == value.value) {
                            result = value.meaning;
                        }
                    });
                    return result;
                }
                ]]></script>
                <h:dataSource id="gridDataSource" batch="true" pageSize="10" serverPaging="true" error="requestError">
                    <h:transport parameterMap="parameterMap">
                        <h:read url="${base.contextPath}/wechat/material/query" type="GET" dataType="json"/>
                        <h:create url="${base.contextPath}/wechat/material/submit" type="POST"
                                  contentType="application/json"/>
                        <h:update url="${base.contextPath}/wechat/material/submit" type="POST"
                                  contentType="application/json"/>
                        <h:destroy url="${base.contextPath}/wechat/material/remove" type="POST"
                                   contentType="application/json"/>
                    </h:transport>
                    <h:schema data="rows" total="total" errors="schemaError">
                        <h:model id="materialId" editable="dsEditable">
                            <h:fields>

                            </h:fields>
                        </h:model>
                    </h:schema>
                </h:dataSource>
                <h:hlsGridBox hlsGridId="materialGrid" hlsBtnType="add,save" title="素材库"
                              viewModelName="viewModel.data" dataSourceId="gridDataSource">
                    <h:hlsGrid id="materialGrid" dataSource="gridDataSource"
                               hlsBtnType="ADD,DELETE"
                               editable="true" height="400px" resizable="true" navigatable="true"
                               locate="gridLocate">
                        <h:pageable pageSizes="all,5,10,20,50" buttonCount="0" refresh="true">
                        </h:pageable>
                        <h:columns>
                            <h:column field="materialDesc" title='描述'
                                      width="70">
                                <h:headerAttributes style="text-align:center"/>
                                <h:attributes style="text-align:center"/>
                            </h:column>
                            <h:column field="type" title='素材类型' editor="typeEditor" template="typeTemp"
                                      width="70">
                                <h:headerAttributes style="text-align:center"/>
                                <h:attributes style="text-align:center"/>
                            </h:column>
                            <h:column field="mediaType" title='媒体文件类型'
                                      width="70">
                                <h:headerAttributes style="text-align:center"/>
                                <h:attributes style="text-align:center"/>
                            </h:column>
                            <h:column field="validAt" title="有效时间截止至"
                                      width="70">
                                <h:headerAttributes style="text-align:center"/>
                                <h:attributes style="text-align:center"/>
                            </h:column>
                            <h:column field="" title="详细描述" width="50" template="detailTemp">
                                <h:headerAttributes style="text-align:center"/>
                                <h:attributes style="text-align:center"/>
                            </h:column>

                        </h:columns>
                    </h:hlsGrid>
                </h:hlsGridBox>
            </div>

        </div>

        <div id="editor-photo" style="position: relative">

            <div class="back-btn" onclick="reBack()"></div>
            <div class="photo-text-title">
                <input maxlength="64" class="ww_editorTitle" data-bind="value:model.title" type="text" value=""
                       placeholder="在此输入标题"/>
            </div>
            <textarea id="editor" data-label="<@spring.message '在此处输入正文'/>" data-bind="value:model.content"
                      style="height:350px;width:100%">
            </textarea>
            <span id="insertPic">
                <img id="insertPhoto" height="20px" width="20px" style="margin-top: 7px;margin-left: 6px; "
                     src="${base.contextPath}/resources/images/WECHAT/picture_fill.png" onclick="f(this)"/>
            </span>
            <!--<div class="add-doc">添加附件</div>-->
            <!--<div class="add-doc add-face" id="wechat_cover" onclick="f(this)">添加封面</div>-->
            <div class="add-doc add-face" id="wechat_cover">
                <form id="coverPic" style="border: none">
                    <input type="file" id="photoCover" name="file" accept="image/gif, image/jpeg, image/png"/>
                </form>
            </div>
            <div class="add-doc add-desc"><span>摘要：</span><input class="add-input" id="description"/></div>
            <div class="add-doc add-desc"><span>作者：</span><input class="add-input" id="author"/></div>
            <div class="add-doc add-desc btn-div">
                <div class="add-btn add-save" onclick="complateEditor()">完成</div>
                <div class="add-btn add-cancel" onclick="reBack()">取消</div>
            </div>
        </div>

    </div>
</h:screen>
