<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">

<head>
    <meta name="referrer" content="same-origin">
    <th:block th:include="include :: header('修改公众号文章详情')" />
    <th:block th:include="include :: select2-css" />
    <th:block th:include="include :: summernote-css" />
    <th:block th:include="include :: bootstrap-fileinput-css" />
</head>

<body class="white-bg">
<div class="wrapper wrapper-content animated fadeInRight ibox-content">
    <form class="form-horizontal m" id="form-detail-edit" th:object="${playletPublicDetail}">
        <input name="id" th:field="*{id}" type="hidden">
        <div class="form-group">
            <label class="col-sm-2 control-label">公众号：</label>
            <div class="col-sm-10">
                <select id="publicId" name="publicId" class="form-control m-b" required>
                    <option th:each="publicAccount:${publicAccounts}" th:value="${publicAccount.id}"
                            th:text="${publicAccount.name}" th:field="*{publicId}"></option>
                </select>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label">标题：</label>
            <div class="col-sm-10">
                <input name="title" th:field="*{title}" class="form-control" type="text">
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label">作者花名：</label>
            <div class="col-sm-10">
                <input name="authorAlias" th:field="*{authorAlias}" class="form-control" type="text">
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label">缩略图：</label>
            <div class="col-sm-10">
                <input name="imgUrl" th:field="*{imgUrl}" type="text" hidden="hidden">
                <div class="file-loading">
                    <input id="imgUrlFile" name="file" type="file">
                </div>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label">缩略图状态：</label>
            <div class="col-sm-10">
                <label class="toggle-switch switch-solid">
                    <input type="checkbox" id="imgStatus" th:checked="${playletPublicDetail.imgStatus == 0 ? true : false}">
                    <span></span>
                </label>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label">头图：</label>
            <div class="col-sm-10">
                <input name="headUrl" th:field="*{headUrl}" type="text" hidden="hidden">
                <div class="file-loading">
                    <input id="headUrlFile" name="file" type="file">
                </div>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label">头图状态：</label>
            <div class="col-sm-10">
                <label class="toggle-switch switch-solid">
                    <input type="checkbox" id="headStatus" th:checked="${playletPublicDetail.headStatus == 0 ? true : false}">
                    <span></span>
                </label>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label">文章类型：</label>
            <div class="col-sm-10">
                <label class="radio-box">
                    <input type="radio" th:checked="${playletPublicDetail.type == '01' ? true : false}" value="01"
                           name="type">富文本</label>
                <label class="radio-box">
                    <input type="radio" th:checked="${playletPublicDetail.type == '02' ? true : false}" value="02"
                           name="type">PDF</label>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label">PDF附件：</label>
            <div class="col-sm-10">
                <input name="pdfUrl" type="text" hidden="hidden">
                <div class="file-loading">
                    <input id="pdfUrlFile" name="file" type="file">
                </div>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label">所在地：</label>
            <div class="col-sm-10">
                <input name="address" th:field="*{address}" class="form-control" type="text">
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label">简介：</label>
            <div class="col-sm-10">
                <input name="remark" th:field="*{remark}" class="form-control" type="text">
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label">文章标签：</label>
            <div class="col-sm-10">
                <select id="detailTags" class="form-control select2-multiple" multiple>
                    <option th:each="tag:${tags}" th:value="${tag.tag}" th:text="${tag.tag}" th:selected="${tag.flag}"></option>
                </select>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label">详情(富文本)：</label>
            <div class="col-sm-10">
                <!-- <input type="hidden" class="form-control" th:field="*{content}">
            <div class="summernote" id="content"></div> -->
                <textarea id="mytextarea" name="content" th:field="*{content}"></textarea>

            </div>
        </div>
    </form>
</div>
<th:block th:include="include :: footer" />
<th:block th:include="include :: select2-js" />
<th:block th:include="include :: summernote-js" />
<th:block th:include="include :: bootstrap-fileinput-js" />
<th:block th:include="include :: tingmce-min-js" />
<script th:inline="javascript">
    var prefix = ctx + "system/playlet/detail";
    $("#form-detail-edit").validate({
        focusCleanup: true
    });

    $(function() {
        $('#detailTags').select2({
            placeholder: "请选择文章标签",
            allowClear: true
        });
    })

    function submitHandler() {
        if ($.validate.form()) {
            var content = tinymce.get('mytextarea').getContent();
            var detailTag = $.form.selectSelects("detailTags");
            var headStatus = $("input[id='headStatus']").is(':checked') === true ? 0 : 1;
            var imgStatus = $("input[id='imgStatus']").is(':checked') === true ? 0 : 1;
            $.operate.save(prefix + "/edit", $('#form-detail-edit').serialize() + encodeURIComponent(content) + "&detailTag=" + detailTag + "&headStatus=" + headStatus + "&imgStatus=" + imgStatus);
        }
    }

    // 详情页
    $("#imgUrlFile").fileinput({
        uploadUrl: ctx + 'tool/oss/uploadFromPlaylet',
        maxFileCount: 1,
        dropZoneEnabled: false,      //是否显示拖拽区域
        showPreview: false,
        autoReplace: true
    }).on('fileuploaded', function (event, data, previewId, index) {
        console.log(data);
        if (data.response.success) {
            $("input[name='imgUrl']").val(data.response.msg)
        } else {
            alert("上传失败!");
        }
    }).on('fileremoved', function (event, id, index) {
        $("input[name='" + event.currentTarget.id + "']").val('')
        $("input[name='imgUrl']").val('')
    })

    $("#headUrlFile").fileinput({
        uploadUrl: ctx + 'tool/oss/uploadFromPlaylet',
        maxFileCount: 1,
        dropZoneEnabled: false,      //是否显示拖拽区域
        showPreview: false,
        autoReplace: true,
        showCaption: true,
        showRemove: true
    }).on('fileuploaded', function (event, data, previewId, index) {
        console.log(data);
        if (data.response.success) {
            $("input[name='headUrl']").val(data.response.msg)
        } else {
            alert("上传失败!");
        }
    }).on('fileremoved', function (event, id, index) {
        $("input[name='" + event.currentTarget.id + "']").val('')
        $("input[name='headUrl']").val('')
    })

    // 详情页
    $("#pdfUrlFile").fileinput({
        uploadUrl: ctx + 'tool/oss/uploadFromPlaylet',
        maxFileCount: 1,
        dropZoneEnabled: false,      //是否显示拖拽区域
        showPreview: false,
        autoReplace: true
    }).on('fileuploaded', function (event, data, previewId, index) {
        console.log(data);
        if (data.response.success) {
            $("input[name='pdfUrl']").val(data.response.msg)
        } else {
            alert("上传失败!");
        }
    }).on('fileremoved', function (event, id, index) {
        $("input[name='" + event.currentTarget.id + "']").val('')
        $("input[name='pdfUrl']").val('')
    })

    async function uploadOneFile(file) {
        return new Promise((resolve, reject) => {
            var data = new FormData();
            data.append("file", file);
            $.ajax({
                type: "post",
                url: ctx + "common/upload",
                data: data,
                cache: false,
                contentType: false,
                processData: false,
                dataType: 'json',
                success: function (result) {
                    if (result.code == web_status.SUCCESS) {
                        resolve(result.url)
                    } else {
                        reject(result.msg)
                    }
                },
                error: function (error) {
                    reject("图片上传失败。")
                }
            });
        })

    }

    $(function () {
        // $('.summernote').each(function(i) {
        //     $('#' + this.id).summernote({
        //         lang: 'zh-CN',
        //         dialogsInBody: true,
        //         height: 300,
        //         callbacks: {
        //             onChange: function(contents, $edittable) {
        //                 $("input[name='" + this.id + "']").val(contents);
        //             },
        //             onImageUpload: function(files) {
        //                 var obj = this;
        //                 var data = new FormData();
        //                 data.append("file", files[0]);
        //                 $.ajax({
        //                     type: "post",
        //                     url: ctx + "common/upload",
        //                     data: data,
        //                     cache: false,
        //                     contentType: false,
        //                     processData: false,
        //                     dataType: 'json',
        //                     success: function(result) {
        //                         if (result.code == web_status.SUCCESS) {
        //                             $('#' + obj.id).summernote('insertImage', result.url);
        //                         } else {
        //                             $.modal.alertError(result.msg);
        //                         }
        //                     },
        //                     error: function(error) {
        //                         $.modal.alertWarning("图片上传失败。");
        //                     }
        //                 });
        //             }
        //         }
        //     });
        //     var content = $("input[name='" + this.id + "']").val();
        //     $('#' + this.id).summernote('code', content);
        // })

        tinymce.init({
            selector: '#mytextarea',
            language: "zh_CN", //语言类型
            content_style: "img {max-width:100%;}",
            placeholder: '在这里输入文字',
            height: 700,
            autoresize_min_height: 700, //编辑区域的最小高度
            remove_trailing_brs: false,
            branding: false,  //tiny技术支持信息是否显示
            extended_valid_elements: 'br',
            plugins: ' preview searchreplace autolink directionality visualblocks visualchars fullscreen image link media code codesample table charmap pagebreak nonbreaking anchor insertdatetime advlist lists wordcount autosave',
            toolbar: 'fullscreen undo redo restoredraft | cut copy paste pastetext | forecolor backcolor bold italic underline strikethrough link anchor | alignleft aligncenter alignright alignjustify outdent indent | \
	 styleselect formatselect fontselect fontsizeselect | bullist numlist | blockquote subscript superscript removeformat | \
	 table image media charmap hr pagebreak insertdatetime preview | code selectall searchreplace visualblocks | indent2em lineheight formatpainter axupimgs',
            toolbar_mode: 'wrap',
            paste_retain_style_properties: "all",
            paste_word_valid_elements: "*[*]", //word需要它
            paste_convert_word_fake_lists: true, // 插入word文档需要该属性
            paste_webkit_styles: "all",
            paste_merge_formats: true,
            nonbreaking_force_tab: false,
            paste_auto_cleanup_on_paste: false,
            paste_data_images: true,  //图片是否可粘贴
            paste_data_images: true,  //图片是否可粘贴
            images_upload_handler: (blobInfo) => {
                return new Promise(async (resolve, reject) => {
                    if (blobInfo.blob().size / 1024 / 1024 > 10) {
                        reject("上传失败，图片大小请控制在 10M 以内")
                    } else {
                        const url = await uploadOneFile(blobInfo.blob())
                        resolve(url)
                    }
                })

            },
            file_picker_types: 'media',
            file_picker_callback: function (callback, value, meta) {
                if (meta.filetype == 'media') {
                    //创建一个隐藏的type=file的文件选择input
                    let input = document.createElement('input');
                    input.setAttribute('type', 'file');
                    input.onchange = async function () {
                        let file = this.files[0]; //只选取第一个文件。如果要选取全部，后面注意做修改
                        const url = await uploadOneFile(file)
                        callback(url)
                    }
                    //触发点击
                    input.click();
                }
            },
            setup: function (editor) {
                editor.on('init', () => {
                    var content = $("textarea[name='content']").val();
                    console.info('content===', content);
                    editor.setContent(content)
                    $("textarea[name='content']").val('');
                })
            },
        });
    });
</script>
</body>

</html>