{{ define "kas/archive_article_add.htm" }}
<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <title>添加文章 - 后台管理 - 看丽人</title>
    <script type="text/javascript">
        const ISGOKEEP = true;
    </script>
    {{ template "_common.htm" .}}
    <link rel="stylesheet" href="{{.global.host_img}}/assets/css/jquery.fileupload.css">
    <script src="{{.global.host_img}}/assets/js/jsrender.min.js"></script>
    <script src="{{.global.host_img}}/assets/js/md5.min.js"></script>
    <link href="{{.global.host_img}}/assets/css/cropper.min.css" rel="stylesheet">
    <script src="{{.global.host_img}}/assets/js/cropper.min.js"></script>
    <link href="{{.global.host_img}}/assets/css/summernote-bs4.css" rel="stylesheet">
    <script src="{{.global.host_img}}/assets/js/summernote-bs4.js"></script>
    <script src="{{.global.host_img}}/assets/js/lang/summernote-zh-CN.js"></script>
    <script type="text/javascript" src="{{.global.host_img}}/assets/js/moment.min.js"></script>
    <script type="text/javascript" src="{{.global.host_img}}/assets/js/daterangepicker.min.js"></script>
    <link rel="stylesheet" type="text/css" href="{{.global.host_img}}/assets/css/daterangepicker.css" />
    <style type="text/css">
        .template-upload td {
            max-width: 120px;
        }

        .itempreview {
            width: 400px;
        }
    </style>
    <script type="text/javascript">
    LoadMemberInfo();
    </script>
</head>

<body>
    {{ template "kas/_header.htm" .}}
    <main role="main">
        <div class="album py-3 bg-light">
            <div class="container">
                {{ template "kas/_nav.htm" .}}
                <div class="alert alert-dark border-bottom"><a href="/kas/archive/article_main">文章管理</a> > 添加文章</span>
                </div>
                <div class="form-group">
                    <label for="iptTitle">文章标题</label>
                    <input name="title" type="text" class="form-control" id="iptTitle" value="">
                </div>
                <div class="form-group">
                    <label for="selTypeid">分类</label>
                    <select id="selTypeid" name="typeid" class="form-control">
                        <option value="0">请选择栏目...</option>
                    </select>
                </div>
                <div class="form-group">
                    <label><input id="ckIsShow" name="isshow" value="1" type="checkbox"> 首页推荐</label>
                    <!-- <label><input id="ckArcrank" name="arcrank" value="10" type="checkbox"> 仅会员查看</label> -->
                </div>
                <div class="form-group">
                    <label for="iptMoney">需要金币（默认为0，免费）</label>
                    <input name="money" type="text" class="form-control" id="iptMoney" value="0">
                </div>
                <div class="form-group">
                    <label>缩略图</label>
                    <div class="row fileupload-buttonbar">
                        <div class="col-lg-7">
                            <span class="btn btn-success fileinput-button">
                                <i class="glyphicon glyphicon-plus"></i>
                                <span>设置缩略图...</span>
                                <input type="file" name="files[]" id="iptAddImages">
                            </span>
                            <button id="btnClearAll" type="button" class="btn btn-danger delete">
                                <i class="fa fa-trash-o"></i>
                                <span>清空</span>
                            </button>
                        </div>
                        <div class="col-lg-5 fileupload-progress fade">
                            <div class="progress progress-striped active" role="progressbar" aria-valuemin="0"
                                aria-valuemax="100">
                                <div class="progress-bar progress-bar-success" style="width:0%;"></div>
                            </div>
                            <div class="progress-extended">&nbsp;</div>
                        </div>
                        <div class="col-12 py-3">
                            <img id="litPic" src="{{.global.host_img}}/assets/img/logo.png" style="width: 133.33px; height: 100px;">
                        </div>
                    </div>
                </div><!-- end form-group -->
                <div class="form-group">
                    <label>内容</label>
                    <div class="row fileupload-buttonbar">
                        <div class="col-12">
                            <div id="articleContent"></div>
                        </div>
                    </div>
                </div><!-- end form-group -->
                <div class="form-group">
                    <label for="iptMoney">描述</label>
                    <textarea class="form-control" id="tarDescription" rows="3"></textarea>
                </div>
                <div class="form-group">
                    <label for="iptMoney">来源</label>
                    <input name="source" type="text" class="form-control" id="iptSource" value="">
                </div>
                <div class="form-group">
                    <label for="iptMoney">预发布时间（设置未来将要上线的时间，不设置则不预发布）</label>
                    <input name="source" type="text" class="form-control" id="iptWillPub" value="">
                </div>
                <button id="btnPublish" class="btn btn-danger btn-block" type="submit">发布</button>
                <button onclick="javascript:history.go(-1);" class="btn btn-outline-secondary btn-block"
                    type="button">返回</button>
            </div><!-- end container -->

        </div>
    </main>

    <canvas id="pvCanvas" style="display: none;"></canvas>

    {{ template "kas/_footer.htm" .}}

    <script type="text/javascript">
        var gokeep_token = GetCookie(TokenName())
        if (gokeep_token == null) {
            DirectTo("/kas");
        }

        var willpub = 0;

        $.views.settings.delimiters("{%", "%}"); // 设置js render标签

        // 加载栏目选项
        LoadTypeidSelectOptions("#selTypeid", 0, 23);

        var litpicImgSrc = "";
        var litpicImg = "";


        $("#btnClearAll").click(function(event) {
            litpicImgSrc = "";
            litpicImg = "";
            $("#litPic").attr("src","{{.global.host_img}}/assets/img/logo.png");
        })

        $('#articleContent').summernote({
            placeholder: '',
            tabsize: 2,
            lang: 'zh-CN',
            height: 280
        });

        $('#iptWillPub').daterangepicker({
            timePicker: true,
            singleDatePicker: true,
            locale: {
                format: 'YYYY/MM/DD HH:mm'
            }
        });
        $('#iptWillPub').on('apply.daterangepicker', function (ev, picker) {
            willpub = picker.startDate.unix();
        });

        // 添加图片
        $("#iptAddImages").change(function (event) {
            var files = event.target.files;
            for (var i = 0, f; f = files[i]; i++) {
                Log("[#iptAddImages.change]", f);
                // 如果不是图片忽略
                if (!f.type.match('image.*')) {
                    continue;
                }

                // 将图片渲染到浏览器
                var reader = new FileReader();
                reader.onload = (function (theFile) {
                    return function (e) {
                        litpicImgSrc = e.target.result;
                        SetThumb(litpicImgSrc);
                    };
                })(f);
                reader.readAsDataURL(f);
            }
            $("#iptAddImages").val("");
        });


        function SetThumb(srcURL) {
          var footer = "<p><a href='?' class='btn btn-outline-primary' data-dismiss='modal' aria-label='Close'>确定</a></p>";
          var mdlID = ShowMsg('<div><div class="float-left" style="width:300px;"><img id="cropImg~modalID~" src="'+srcURL+'" width=200></div><div class="pv float-right" style="width:150px;height:100px;overflow:hidden;"></div></div>',{
            footer:footer,
            noClose:false,
          });

          setTimeout(function(){
            $("#cropImg"+mdlID).cropper({
                aspectRatio: 4/3,
                preview: ".pv",
                // 拖动截取缩略图后，截取的缩略图更新到imageItems中
                cropend: function(data) {
                  // 这里的ID要单独取出来
                  var dataUrl = $(this).cropper("getCroppedCanvas").toDataURL();
                  litpicImg = dataUrl;
                  $("#litPic").attr("src", litpicImg);
                }
            });
          }, 500);
        }

        // 发布
        $('#btnPublish').click(function (event) {
            if ($("#iptTitle").val() == "") {
                ShowMsg("请添加标题");
                return;
            } if (parseInt($("#selTypeid").val()) == 0) {
                ShowMsg("请选择栏目");
                return;
            }
            if ($('#articleContent').summernote('isEmpty')) {
                ShowMsg("内容不能为空");
                return;
            }
            if (willpub > 0 && willpub <= NowUnix) {
                ShowMsg("预发布时间需要是未来时间");
                return;
            }

            $('#btnPublish').addClass('disabled');
            $('#btnPublish').text('正在发布...');
            $.ajax({
                type: "POST",
                dataType: 'json',
                contentType: "application/json;",
                url: "/api/v1/auth/archive/article_add",
                beforeSend: function (xhr) {
                    xhr.setRequestHeader('Authorization', 'Bearer ' + gokeep_token);
                },
                data: JSON.stringify({
                    title: $("#iptTitle").val(),
                    description: $("#tarDescription").val(),
                    typeid: parseInt($("#selTypeid").val()),
                    isshow: $("#ckIsShow").is(":checked") ? 1 : 0,
                    // arcrank: $("#ckArcrank").is(":checked")? 10 : 0,
                    money: parseInt($("#iptMoney").val()),
                    source: $("#iptSource").val(),
                    body:$('#articleContent').summernote('code'),
                    litpic: litpicImg,
                    willpub: willpub,
                }),
                timeout: 0,
                success: function (data) {
                    Log(data);
                    if (data.code == 0) {
                        var publishUrl = "{{.global.host_www}}/view/" + data.result.UnqID;
                        var targetStr = "_blank";
                        if (willpub > 0 && willpub > NowUnix) {
                            publishUrl = "/kas/archive/article_edit?unqid=" + data.result.UnqID;
                            targetStr = "_self";
                        }
                        var footer = "<p><a href='" + publishUrl + "' class='btn btn-primary' target='" + targetStr + "'>查看已发布内容</a> <a href='/kas/archive/article_edit?unqid=" + data.result.UnqID + "' class='btn btn-primary' target='" + targetStr + "'>编辑已发布内容</a> <a href='/kas/archive/article_add' class='btn btn-primary'>继续发布</a></p>";
                        ShowMsg("发布成功", {
                            footer: footer,
                            noClose: true,
                        });
                    } else {
                        ShowMsg("[错误代码:" + data.code + "]发布失败，请检查填写内容是否完整、正确");
                    }
                },
                error: function () {
                    ShowMsg("发布失败");
                }
            }).always(function () {
                $('#btnPublish').removeClass('disabled');
                $('#btnPublish').text('发布');
            });
        });
    </script>
</body>

</html>
{{ end }}