{% load staticfiles %}

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="format-detection" content="telephone=no,email=no,address=no">
    <meta name="viewport" content="width=device-width,initial-scale=1.0,user-scalable=no">
    <title>拍爱</title>

    <link href="{% static 'page/css/scroll_loader.css' %}" rel="stylesheet">
    <link href="//cdnjs.cloudflare.com/ajax/libs/photoswipe/4.1.2/photoswipe.css" rel="stylesheet">
    <link href="//cdnjs.cloudflare.com/ajax/libs/photoswipe/4.1.2/default-skin/default-skin.css" rel="stylesheet">

    <style>
        .text-center {
            text-align: center;
        }

        .float-left {
            float: left;
        }

        .float-right {
            float: right;
        }

        .clear-both {
            clear: both;
        }

        .halfscreen {
            width: 49%;
            box-sizing: border-box;
        }

        .halfscreen > .imgctx > img {
            width: 100% !important;
            box-sizing: border-box;
            outline: 0;
            display: block;
        }

        .photo-top {
            height: 40px;
            display: flex;
            flex-direction: row;
            align-items: center;
        }

        .group-avatar {
            box-shadow: 0 0 1px 0 #ccc;
            width: 25px !important;
            height: 25px;
            border-radius: 100%;
            margin-left: 3px;
        }

        .group-name {
            max-width: 50%;
            height: 25px;
            line-height: 25px;
            text-align: left;
            margin-left: 5px;
            font-size: 12px;
            overflow: hidden;
        }

        .photo-bottom {
            height: 32px;
        }

        .section-text {
            line-height: 25px;
            font-size: 12px;
            margin: 0 5px 0 auto;
            color: #999;
        }

        .section-icon {
            width: 16px;
            height: 16px;
            margin: 3px;
        }

        .thump-comment-num {
            line-height: 22px;
            font-size: 12px;
            margin-right: 5px;
            color: #999;
        }

        .mask-thump > img {
            position: absolute;
            right: 10px;
            bottom: 10px;
            width: 30px;
            z-index: 99999;
        }

        .nomark-buy, .origin-buy {
            position: fixed;
            right: 2px;
            bottom: 2px;
            left: 2px;
            height: 50px;
            line-height: 50px;
            text-align: center;
            color: whitesmoke;
            border: 1px solid #fff;
            border-radius: 5px;
            box-sizing: border-box;
            z-index: 99999;
        }

        .qrscan {
            position: fixed;
            right: 10px;
            bottom: 10px;
            width: 60px;
            height: 60px;
            z-index: 99999;
        }

        .qrscan > img {
            width: 100%;
            height: 100%;
        }
    </style>
</head>
<body>
<div>
    <div id="photos">
        <div id="left" class="halfscreen" style="float: left;">
            {#            <img src="https://placekitten.com/600/400" data-idx="0">#}
            {#            <img src="https://placekitten.com/1200/900" data-idx="2">#}
        </div>
        <div id="right" class="halfscreen" style="float: right;">
            {#            <img src="https://placekitten.com/1200/900" data-idx="1">#}
            {#            <img src="https://placekitten.com/600/400" data-idx="3">#}
        </div>
    </div>
{#    <div id="mask-thump" class="mask-thump">#}
{#        <img class="" src="{% static 'page/img/thumbup.png' %}"/>#}
{#    </div>#}
    <div id="buy" style="display:none">
        <div id="nomark" class="nomark-buy">去除水印</div>
        {#        <div id="origin" class="origin-buy">购买原图</div>#}
    </div>
    <!-- 扫一扫 -->
    <div id="qrscan" class="qrscan">
        <img class="" src="{% static 'page/img/qrscan.png' %}"/>
    </div>

    <p id="loading" class="loading text-center clear-both">{% if left %}加载中...{% else %}--- 没有更多了 ---{% endif %}</p>
</div>
<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">
    <!-- Background of PhotoSwipe.
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>
    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">
        <!-- Container that holds slides.
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>
        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">
            <div class="pswp__top-bar">
                <!--  Controls are self-explanatory. Order can be changed. -->
                <div class="pswp__counter"></div>
                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>
                <button class="pswp__button pswp__button--share" title="Share"></button>
                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>
                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>
                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>
            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>
            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>
            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>
        </div>
    </div>
</div>

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/photoswipe/4.1.2/photoswipe.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/photoswipe/4.1.2/photoswipe-ui-default.min.js"></script>
<script src="//res.wx.qq.com/open/js/jweixin-1.3.2.js"></script>
<script src="{% static 'pai2/js/jswe-0.0.4.js' %}"></script>
<script src="{% static 'page/js/scroll_loader.js' %}"></script>
<script>
    $(function () {
        /** 格式化输入字符串 **/
        // 用法: "hello{0}".format('world')；返回'hello world'
        String.prototype.format = function () {
            var args = arguments;
            return this.replace(/\{(\d+)\}/g, function (s, i) {
                return args[i];
            });
        }

        function fromNow(UTCDateString) {
            var SECONDS_INTERVAL = 60;
            var MINUTES_INTERVAL = SECONDS_INTERVAL * 60;
            var HOURS_INTERVAL = MINUTES_INTERVAL * 24;
            var DAYS_INTERVAL = HOURS_INTERVAL * 31;
            var MONTHS_INTERVAL = DAYS_INTERVAL * 12;
            var SECONDS_SUFFIX = "秒前";
            var MINUTES_SUFFIX = "分钟前";
            var HOURS_SUFFIX = "小时前";
            var DAYS_SUFFIX = "天前";
            var MONTHS_SUFFIX = "月前";
            var YEARS_SUFFIX = "年前";
            var second = new Date(Date.parse(UTCDateString)).getTime() / 1000;
            var curSecond = new Date().getTime() / 1000;
            var distance = curSecond - second;
            var result = "";
            if (distance <= 0) {
                result = UTCDateString;
            } else if (distance < SECONDS_INTERVAL) {
                result = Math.ceil(distance) + SECONDS_SUFFIX;
            } else if (distance < MINUTES_INTERVAL) {
                var count = distance / SECONDS_INTERVAL;
                result = Math.ceil(count) + MINUTES_SUFFIX;
            } else if (distance < HOURS_INTERVAL) {
                var count = distance / MINUTES_INTERVAL;
                count = Math.floor(count) || 1;
                result = count + HOURS_SUFFIX;
            } else if (distance < DAYS_INTERVAL) {
                var count = distance / HOURS_INTERVAL;
                count = Math.floor(count) || 1;
                result = count + DAYS_SUFFIX;
            } else if (distance < MONTHS_INTERVAL) {
                var count = distance / DAYS_INTERVAL;
                count = Math.floor(count) || 1;
                result = count + MONTHS_SUFFIX;
            } else {
                var count = distance / MONTHS_INTERVAL;
                count = Math.floor(count) || 1;
                result = count + YEARS_SUFFIX;
            }
            return result;
        }

        function parse(paramstr) {
            var ret = {},
                    seg = paramstr.split('&'),
                    len = seg.length, i = 0, s;
            for (; i < len; i++) {
                s = seg[i].split('=');
                ret[s[0]] = s[1];
            }
            return ret
        }

        var GROUP_AVATAR_LIST = [
            'apple',
            'banana',
            'broccoli',
            'carambola',
            'carrot',
            'cherry',
            'corn',
            'dragon',
            'eggplant',
            'fig',
            'grape',
            'lemon',
            'mangosteen',
            'orange',
            'papaya',
            'peach',
            'pineapple',
            'strawberry',
            'watermelon'
        ]

        var width = $(document).width();
        var renderData = {{ data|safe }};
        var session_photos = renderData['session_photos'];
{#        {% include 'page/snippets/sessionphotos.html' %}#}
        var photoWidth = width * 49 / 100;
        var photoHeight = 0;
        var photoIdx = 0;
        var leftHeight = 0;
        var rightHeight = 0;
        var leftImgs = '';
        var rightImgs = '';
        var swipeItems = [];
        var swipePhotos = [];
        var curIdx = -1;
        var orderId = '';
        var orderQueryTimer = null;

        var user_id = '{{ user_id }}';
        var nickname = '{{ nickname }}';

        function session_photos_display(session_photos) {
            for (var i = 0; i < session_photos.length; i++) {
                var photos = session_photos[i].photos;
                for (var j = 0; j < photos.length; j++) {
                    photoHeight = photos[j].photo_thumbnail_h / photos[j].photo_thumbnail_w * photoWidth;
                    var header = (
                            '<div class="photo-top">' +
                            '<img class="group-avatar float-left" src="../../static/page/img/fruits/{0}.png" />' +
                            '<text class="group-name float-left">{1}</text>' +
                            '<text class="section-text float-right">{2}</text>' +
                            '</div>'
                    ).format(GROUP_AVATAR_LIST[photos[j].group_default_avatar], photos[j].group_name, fromNow(photos[j].created_at));
                    var imgctx = '<img src="{0}" data-idx="{1}" style="width:{2}px;height:{3}px">'.format(photos[j].photo_thumbnail_url, photoIdx, photoWidth, photoHeight);
                    var footer = (
                            '<div class="photo-bottom">' +
                            '<img class="section-icon float-left" src="../../static/page/img/thumbup.png" />' +
                            '<text class="thump-comment-num float-left">{0}</text>' +
                            '<img class="section-icon float-left" src="../../static/page/img/comment.png" />' +
                            '<text class="thump-comment-num float-left">{1}</text>' +
                            '</div>'
                    ).format(photos[j].thumbup_num, photos[j].comment_num);
                    if (leftHeight > rightHeight) {
                        rightHeight += photoHeight + 72;
                        rightImgs += '<div class="imgctx">{0}{1}{2}</div>'.format(header, imgctx, footer);
                    } else {
                        leftHeight += photoHeight + 72;
                        leftImgs += '<div class="imgctx">{0}{1}{2}</div>'.format(header, imgctx, footer);
                    }
                    swipeItems.push({
                        src: photos[j]['porder'].m_photo_url || photos[j].photo_url,
                        w: photos[j].photo_w,
                        h: photos[j].photo_h,
                    })
                    swipePhotos.push(photos[j]);
                    photoIdx += 1;
                }
            }

            $('#left').html(leftImgs);
            $('#right').html(rightImgs);
        }

        session_photos_display(session_photos);

        var pswpElement = document.querySelectorAll('.pswp')[0];
        // define options (if needed)
        var options = {
            // optionName: 'option value'
            // for example:
            loop: true,
            index: 1, // start at first slide
            // Tap on sliding area should close gallery'
            tapToClose: true,
        };

        function displayornot() {
            var photoInfo = swipePhotos[curIdx];
            var display_payment_btn = photoInfo['display_payment_btn'];
            if (photoInfo['display_payment_btn'] && (typeof photoInfo['porder'].m_photo_url == 'undefined' || photoInfo['porder'].m_photo_url == '')) {
                $('#buy').show();
            } else {
                $('#buy').hide();
            }
{#            $('#mask-thump').show();#}
        }

        // Initializes and opens PhotoSwipe
        $(document).on('click', '#photos img', function(){
            $('#qrscan').hide();

            curIdx = parseInt($(this).attr('data-idx'));
            options['index'] = curIdx;
            var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, swipeItems, options);
            gallery.init();

            displayornot();


            // After slides change
            // (after content changed)
            gallery.listen('afterChange', function () {
                console.log(gallery.getCurrentIndex());
                curIdx = gallery.getCurrentIndex();
                displayornot()
            });

            // Gallery starts closing
            gallery.listen('close', function () {
                $('#qrscan').show();
                $('#buy').hide();
{#                $('#mask-thump').hide();#}
            });
        })

        /** 去水印图片购买 **/
        function order_query(orderId, photoId) {
            $.ajax({
                url: '/mini/order_query',
                type: 'POST',
                data: {
                    order_id: orderId,
                },
                timeout: 5000,
                cache: true,
                success: function (res) {
                    if (res.status == 200) {
                        window.clearTimeout(orderQueryTimer);
                        // 支付成功，获取 porder
                        $.ajax({
                            url: 'f/bought',
                            data: {
                                user_id: user_id,
                                photo_id: photoId,
                            },
                            success: function (res) {
                                if (res.data.status == 200) {
                                    var swipeItem = swipeItems[curIdx];
                                    swipeItem['src'] = res.data.porder.m_photo_url || swipeItem['src'];
                                    swipeItems[curIdx] = swipeItem;

                                    $('.pswp__img')[0].src = swipeItem['src'];

                                    var photoInfo = swipePhotos[curIdx];
                                    photoInfo['porder'] = res.data.porder;
                                    swipePhotos[curIdx] = photoInfo;
                                }
                            }
                        })
                    } else {
                        orderQueryTimer = window.setTimeout(function () {
                            order_query(orderId, photoId);
                        }, 1000)
                    }
                },
                error: function (res) {
                }
            });
        }

        $('#nomark').click(function () {
            var photoInfo = swipePhotos[curIdx];
            var photoId = photoInfo.photo_id;

            $.ajax({
                url: '/mini/order_create',
                type: 'POST',
                data: {
                    group_id: photoInfo.group_id,
                    user_id: photoInfo.user_id,
                    photo_id: photoId,
                    photo_type: 'nomark',
                    body: '去除水印',
                    total_fee: 1,
                    trade_type: 'MINIAPP',
                },
                timeout: 5000,
                cache: true,
                success: function (res) {
                    if (res.status == 200) {
                        orderId = res.data.order_id;
                        var wxpay_params = res.data.wxpay_params;
                        //点击微信支付后，调取统一下单接口生成微信小程序支付需要的支付参数
                        var params = '?timeStamp=' + wxpay_params.timeStamp + '&nonceStr=' + wxpay_params.nonceStr
                                + '&package=' + wxpay_params.package.split("=")[1] + '&signType=MD5'
                                + '&paySign=' + wxpay_params.paySign;
                        //定义path 与小程序的支付页面的路径相对应
                        var path = '/pages/wxpay/wxpay' + params;
                        //通过JSSDK的api使小程序跳转到指定的小程序页面
                        wx.miniProgram.navigateTo({url: path});

                        order_query(orderId, photoId);
                    }
                },
                error: function (res) {
                }
            });
        })

        /** 二维码扫描 **/
        $('#qrscan').click(function (e) {
            V.scanQRCode({
                needResult: 1
            });
        })

        V.wxScanQRCodeSuccess = function (res) {
            var qrcodeurl = V.parseScanQRCodeResultStr(res.resultStr);
            var matched = /(https{0,1}:\/\/[\w*.]+\w*)\/(\w*)\/(\w*)\?*(.*)/.exec(qrcodeurl);
            // 如果匹配失败
            if (!matched) {
                return
            }
            matchedInfo = {
                uri: matched[1],
                type: matched[2],
                id: matched[3],
                params: matched[4],
            }
            if (matchedInfo.type == 's') {
                $.ajax({
                    url: '/s/join',
                    type: 'POST',
                    data: {
                        session_id: matchedInfo.id,
                        user_id: user_id,
                        nickname: nickname,
                        lensman_id: parse.parse(matchedInfo.params).lensman_id,
                    },
                    success: function (res) {
                        if (res.data.status == 200) {
                            window.location.reload();
                        }
                    }
                })
            }
            else if (matchedInfo.type == 'g') {
                requests.post({
                    url: '/g/join',
                    data: {
                        group_id: matchedInfo.id,
                        user_id: user_id,
                        nickname: nickname,
                    },
                    success: function (res) {
                        if (res.data.status == 200) {
                            // 刷新照片
                            window.location.reload();
                        }
                    }
                })
            }
            else if (matchedInfo.type == 'tgu') {
                requests.post({
                    url: '/tgu/join',
                    data: {
                        admin_id: matchedInfo.id,
                        user_id: user_id,
                    },
                    success: function (res) {
                        if (res.data.status == 200) {
                            // 刷新照片
                            window.location.reload();
                        }
                    }
                })
            }
        }

        /** 上拉加载 **/
        var enable_loader = {{ left }};
        var current_page = 1;
        var count_pre_load = 50;

        function scroll_func(page, count, callback) {
            $.ajax({
                url: '/pai2/home',
                type: 'POST',
                data: {
                    user_id: user_id,
                    page: current_page,
                },
                success: function (res) {
                    if (res.status === 200) {
                        if (res.data.left === 0) {
                            enable_loader = false;
                            $('#loading').text('--- 没有更多了 ---');
                        }
                        var session_photos = res.data.session_photos;
                        if (session_photos) {
                            session_photos_display(session_photos);
                        }
                    }
                    callback();
                },
            })
        }

        function scroll_handler(callback) {
            if (enable_loader) {
                scroll_func(++current_page, count_pre_load, callback);
            }
        }

        // 开启滚动加载
        scroll_loader(scroll_handler, false);
    })
</script>
</body>
</html>