<?php
/*
 * Template name: （BaaS）友链模板
 * Template Post Type: page
*/
$baas = get_option('site_leancloud_switcher') && strpos(get_option('site_leancloud_category'), basename(__FILE__))!==false; //in_array(basename(__FILE__), explode(',', get_option('site_leancloud_category')))
// 输出站点链接
function the_site_links($t1='小伙伴', $t2='技术の', $t3='荐见鉴') { //, $baas=false
    global $baas;
    if($baas) {
        echo '<div class="fade-item"><div class="inbox-clip"><h2 id="exchanged"> '.$t1.' </h2></div><div class="deals exchanged flexboxes"></div><!-- rcmd begain --></div><div class="fade-item"><div class="inbox-clip"><h2 id="rcmded"> '.$t3.' </h2></div><div class="deals rcmd flexboxes"></div><!-- lost begain --></div><div class="fade-item"><div class="inbox-clip"></div><div class="deals oldest"><div class="inboxSliderCard"><div class="slideBox flexboxes"></div></div></div></div>';
        return;
    };
    $output = '';
    $output_sw = false;
    if(get_option('site_cache_switcher')) {
        $caches = get_option('site_cache_includes');
        $temp_slug = get_cat_by_template('2bfriends','slug');
        $output_sw = in_array($temp_slug, explode(',', $caches));
        $output = $output_sw ? get_option('site_link_list_cache') : '';
    };
    if($output==='' || !$output_sw) {
        $STANDARD = 'standard';
        $TECHNICAL = 'technical';
        $SPECIAL = 'special';
        $OTHERS = 'others';
        $rich_links = get_site_bookmarks($STANDARD);
        $tech_links = get_site_bookmarks($TECHNICAL);  // $tech_links = get_filtered_bookmarks($TECHNICAL, $OTHERS);
        $rcmd_links = get_site_bookmarks($SPECIAL, 'rand', 'DESC');
        $other_links = get_site_bookmarks($OTHERS, 'link_id', 'DESC');
        $stete_rich = $stete_tech = $stete_rcmd = '';
        if(get_option('site_links_code_state')) {
            $state_includes = get_option('site_links_code_state_cats');
            $stete_rich = in_array($STANDARD, explode(',', $state_includes));
            $stete_tech = in_array($TECHNICAL, explode(',', $state_includes));
            $stete_rcmd = in_array($SPECIAL, explode(',', $state_includes));
        }
        $output .= $rich_links ? '<div class="fade-item"><div class="inbox-clip"><h2 id="exchanged"> '.$t1.' </h2></div><div class="deals exchanged flexboxes">'.get_site_links($rich_links, 'full', '', $stete_rich, $STANDARD).'</div></div>' : '<div class="empty_card"><i class="icomoon icom icon-'.current_slug().'" data-t=" EMPTY "></i><h1> '.current_slug(true).' </h1></div></div>';
        if($tech_links) $output .= '<div class="fade-item"><div class="inbox-clip"><h2 id="exchanged"> '.$t2.' </h2></div><div class="deals tech exchanged flexboxes">'.get_site_links($tech_links, 'full', '', $stete_tech, $TECHNICAL).'</div></div>';
        if($rcmd_links) $output .= '<div class="fade-item"><div class="inbox-clip"><h2 id="rcmded"> '.$t3.' </h2></div><div class="deals rcmd flexboxes">'.get_site_links($rcmd_links, 'half', '', $stete_rcmd, $SPECIAL).'</div></div>';
        if($other_links) $output .= '<div class="deals oldest"><div class="fade-item"><div class="inboxSliderCard"><div class="slideBox flexboxes">'.get_site_links($other_links).'</div></div></div></div>';
        if($output_sw) update_option('site_link_list_cache', wp_kses_post($output));
    };
    echo wp_kses_post($output);
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <link type="text/css" rel="stylesheet" href="<?php echo $src_cdn; ?>/style/2bfriends.css?v=<?php echo get_theme_info(); ?>" />
    <?php get_head(); ?>
    <style>
        .friends-boxes .deals .inbox.girl em{background: url('<?php echo $img_cdn; ?>/images/girl_symbols.png') no-repeat center center /contain;}
        .friends-boxes .deals .inbox.girl::after{background: url('<?php echo $img_cdn; ?>/images/girl_symbols.png') center center /contain no-repeat;}
        .main,
        #vcomments{
            margin: auto!important;
        }
        /*.friends-boxes .deals .inbox .inbox-headside {*/
        /*    width: 68%;*/
        /*}*/
        .friends-boxes .deals.exchanged .inbox .inbox-aside {
            margin-left: 20px;
            text-align: left;
            align-items: baseline;
        }
        .friends-boxes .deals.tech .inbox:hover .inbox-aside {
            margin: 25px auto;
            padding-bottom: 35px;
            width: 100%;
            height: 100%;
        }
        .friends-boxes .deals.tech .inbox:hover .inbox-aside span.lowside-title {
            white-space: normal;
        }
        .friends-boxes .deals .inbox .inbox-aside span,
        .friends-boxes .deals.tech .inbox:hover .inbox-aside span.lowside-title h4{
            max-width: 100%;
            margin: 0;
        }
        .friends-boxes .deals.tech .inbox {
            max-width: calc(100% / 6.35);
            max-width: calc(100% / 7.5);
            max-width: calc(100% / 10);
        }
        .friends-boxes .deals.tech .inbox .inbox-aside span {
            margin: 0;
            max-width: 100%;
            white-space: nowrap;
        }
        .friends-boxes .deals.tech .inbox .inbox-aside span.lowside-title h4{
            /*max-width: 4em;*/
            overflow: hidden;
            text-overflow: ellipsis;
        }
        .friends-boxes .deals.tech .inbox .inbox-inside {
            flex-flow: column;
            align-items: center;
        }
        .friends-boxes .deals.tech .inbox .inbox-headside {
            /*width: 80%;*/
        }
        .friends-boxes .deals .inbox:hover > .inbox-inside .inbox-aside {
            align-items: center;
            /*text-align: center;*/
        }
        .friends-boxes .deals.tech .inbox .inbox-headside img#err,
        .friends-boxes .deals.tech .inbox .inbox-inside a.inbox-aside {
            align-items: center;
            /*text-align: center;*/
            margin: 15px auto auto;
        }
        .friends-boxes .deals.tech .inbox .inbox-headside img#err {
            opacity: .75;
            font-size: 10px;
        }
        
        .friends-boxes .deals .inboxSliderCard {
            white-space: nowrap;
        }
        .friends-boxes .deals .inboxSliderCard.sliding {
            scroll-behavior: auto!important;
        }
        .friends-boxes .deals .inboxSliderCard.sliding .slideBox {
            display: table;
            display: inline-block;
            white-space: nowrap;
            transition: transform .35s ease;
        }
        .friends-boxes .deals .inboxSliderCard.sliding .slideBox a {
            /*padding: 0 15px 0 0;*/
            letter-spacing: 3px;
            writing-mode: tb-rl;
            -webkit-writing-mode: vertical-rl;
            will-change: transform;
        }
        .friends-boxes .deals .inboxSliderCard .slideBox a:last-child {
            padding: 0;
        }
        .friends-boxes .deals .inbox span.ssl {
	        background: var(--preset-4a);
        }
        .friends-boxes .deals .inbox:hover > .inbox-inside.aside {
            transform: translateY(-15px) scale(.75);
            opacity: 1;
            z-index: 1;
        }
        .friends-boxes .deals .inbox .inbox-inside.aside::after {
            content: none;
        }
        .friends-boxes .deals .inbox .inbox-inside.aside {
            height: auto;
            padding: 0;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            opacity: 0;
            position: absolute;
            bottom: 0;
            transform: translateY(0) scale(1);
            transition: all .35s ease;
            cursor: cell;
        }
        .friends-boxes .deals .inbox .inbox-inside.aside a {
            display: block;
            /*max-width: 88%;*/
            overflow: hidden;
            text-overflow: ellipsis;
        }
        .friends-boxes .deals .inbox .inbox-inside.aside ol {
            margin: 25px auto;
            /*padding-left: 25px;*/
        }
        .friends-boxes .deals.rcmd .inbox .inbox-inside.aside ol {
            margin: 15% auto;
        }
        .friends-boxes .deals.tech .inbox .inbox-inside.aside ol {
            margin: 18% auto;
        }
        .friends-boxes .deals .inbox .inbox-inside.aside.loading {
            cursor: not-allowed;
            cursor: wait;
            cursor: progress;
        }
        /*.friends-boxes .deals .inbox:hover > .inbox-inside.aside.loaded.pre {*/
        /*    transform: translateY(0) scale(1);*/
            /*transform: translateY(-100%) scale(1);*/
            /*transform: translateY(108%) scale(1);*/
            /*z-index: 999;*/
        /*}*/
        .friends-boxes .deals .inbox.standby {
            z-index: 0;
        }
        .friends-boxes .deals .inbox .inbox-inside.aside.loaded.pre {
            /*transform: translateY(-25%) scale(.5);*/
            transform: translateY(25%) scale(.5);
        }
        .friends-boxes .deals .inbox:hover > .inbox-inside.aside.loaded.pre,
        .friends-boxes .deals .inbox .inbox-inside.aside.loaded {
            transform: translateY(0) scale(1);
            top: 0;
            cursor: default;
        }
        .friends-boxes .deals .inbox .inbox-inside.aside #container a:hover,
        .friends-boxes .deals .inbox .inbox-inside.aside.loaded i.close:hover {
            color: var(--theme-color);
            /*text-decoration: underline;*/
        }
        .friends-boxes .deals .inbox .inbox-inside.aside.loaded a#loadRSSFeeds,
        .friends-boxes .deals .inbox .inbox-inside.aside #container,
        .friends-boxes .deals .inbox .inbox-inside.aside i.close {
            display: none;
        }
        .friends-boxes .deals.tech .inbox .inbox-inside.aside.loaded #container {
            padding-left: 30px;
        }
        .friends-boxes .deals .inbox .inbox-inside.aside.loaded #container,
        .friends-boxes .deals .inbox .inbox-inside.aside.loaded i.close {
            display: block;
        }
        .friends-boxes .deals .inbox .inbox-inside.aside.loaded i.close::before {
            content: '\e91d';
        }
        .friends-boxes .deals .inbox .inbox-inside.aside.loaded i.close {
            font-size: small;
            font-weight: bold;
            width: 15px;
            height: 15px;
            padding: 15px;
            position: absolute;
            top: 0;
            right: 0;
            z-index: 2;
            cursor: pointer;
        }
        .friends-boxes .deals .inbox .inbox-inside.aside a#loadRSSFeeds::after {
            /*content: '【点击加载】RSS 聚合内容';*/
            content: '【点击查看】ta の 近期更新';
        }
        .friends-boxes .deals .inbox .inbox-inside.aside.loading a#loadRSSFeeds::after {
            content: 'RSS 内容加载中..';
        }
        .friends-boxes .deals .inbox .inbox-inside.aside.loading a#loadRSSFeeds {
            pointer-events: none;
            opacity: .75;
        }
        .friends-boxes .deals .inbox .inbox-inside.aside a#loadRSSFeeds {
            padding: 12px;
            box-sizing: border-box;
            margin: 0 auto;
        }
    </style>
</head>
<body class="<?php theme_mode(); ?>">
    <div class="content-all">
        <header>
            <nav id="tipson" class="ajaxloadon">
                <?php get_header(); ?>
            </nav>
        </header>
        <?php get_inform(); ?>
        <div class="content-all-windows" style="padding-top:0;">
            <div class="friends-boxes flexboxes">
                <?php 
                    the_site_links('朋友圈', '技术圈');
                    // wp_cache_flush(); // 清除所有缓存，包括选项
                    // global $wpdb;
                    // echo $wpdb->get_var($wpdb->prepare("SELECT option_value FROM $wpdb->options WHERE option_name = %s", 'site_link_list_cache'));
                    echo '<br />';
                    the_content();  // the_page_content(current_slug());
                    dual_data_comments();
                ?>
            </div>
        </div>
		<footer>
            <?php get_footer(); ?>
		</footer>
    </div>
<!-- siteJs -->
<script type="module">
    try {
        import("<?php echo custom_cdn_src(0,1);//$src_cdn; ?>/js/slidebox.js").then((res)=> {
            const { AutoSlideBox, Utils } = res;
            const slideBox = new AutoSlideBox({
                slideSpeed: Utils.BASIC.randomNumber(0.5),
                // slideDirection: 1,
                // slideSpeed: 10,
                // slideRound: 2,
                // slideRandom: false,
                // slideDebug: true,
                slideRestart: 2000,
                slideElements: {
                    slideFrame: document.querySelector('.inboxSliderCard'),
                    slideBox: document.querySelector('.slideBox'),
                }
            });
            // slideBox.#config.slideSpeed = slideBox.UTILS.randomNumber(0.5); // false
            // slideBox.setConfig('slideSpeed', slideBox.UTILS.randomNumber(0.5)); // true
            slideBox.initAnimation();
        });
    } catch(e) {
        console.warn("import err.", e)
    }
</script>
<!-- inHtmlJs -->
<!-- pluginJs !!! Cannot redefine property: applicationId (av-min must be same with valine.js cdn) !!! av-min.js must be load via dynamicLoad(use no raw function twice) to head js which allow init AV twice -->
<!--<script src="//cdn.jsdelivr.net/npm/leancloud-storage/dist/av-min.js"></script>-->
<!-- inHtmlJs -->
<script type="text/javascript">
    function bindEvents(events = 'onclick', parent, ids, callback) {
        if (!parent) {
            console.warn('bindEvents failed', parent);
            return;
        }
        parent[events] = (e)=> {
            e = e || window.event;
            let t = e.target || e.srcElement;
            if(!t) return;
            while(t!=parent){
                if(!ids || ids==="") {
                    callback(t,e);
                    break;
                }
                if(t.id===ids || t.classList && t.classList.contains(ids) || t.nodeName.toUpperCase()===ids.toUpperCase()){
                    // callback?.();
                    if(callback&&typeof callback==='function') callback(t,e); //callback(t) || callback(t); // callback.apply(this, ...arguments);
                    break;
                }
                // console.log('origin', t);
                t = t.parentNode;
            }
        };
    };
    // bindEventClick(document.querySelector('.friends-boxes'), 'loadRSSFeeds', function(t) {
    // });
    bindEvents('onclick', document.querySelector('.friends-boxes'), '', (t, e)=> {
        if (t.classList.contains('close')) {
            t.parentNode.classList.remove('loaded');
            // t.parentNode.remove();
            return;
        }
        if (t.id === 'loadRSSFeeds') {
            const aside = t.parentNode;
            const _container = aside.querySelector('#container');
            // load from cache
            if (_container) {
                aside.classList.add('loaded');
                return;
            }
            // fetch new data
            aside.classList.add('loading');
            fetch(t.dataset.api)
            .then((res)=> {
                if (res.status !== 200) {
                    t.textContent = `loadRSSFeeds failed: ${res.status}`;
                    console.log(res);
                    return;
                }
                return res.json();
            })
            .then((data)=> {
                console.log(data);
                const mainContent = decodeURIComponent(data.desc);
                const container = document.createElement('OL');
                const closeBtn = document.createElement('I');
                container.id = 'container';
                closeBtn.className = 'BBFontIcons close';
                container.innerHTML = `<li><a href="${data.link === 'javascript:;' ? data.rss : data.link}" target="_blank" title="${mainContent}"><b>${data.title || mainContent}</b></a></li>`;
                if (data.child && data.child.length) {
                    data.child.forEach((item, index)=> {
                        // console.log(index, +t.dataset.limit);
                        if (t.dataset.limit && +t.dataset.limit === index) return;
                        const childContent = item.desc; // decodeURIComponent(item.desc)
                        container.innerHTML += `<li><a href="${item.link}" target="_blank" title="${childContent}">${item.title || childContent}</a></li>`;
                    });
                };
                aside.appendChild(container);
                aside.appendChild(closeBtn);
                aside.classList.add('loaded');
                aside.classList.remove('loading');  // enable reload
                // t.remove();
            })
            .catch((err)=> {
                console.warn(err);
                aside.classList.add('loading');  // disable reload
                t.textContent = err; // decodeURIComponent(err);
            })
            .finally(() => {
                // aside.classList.remove('loading');  // enable reload
            });;
        }
    });
</script>
<?php
    get_foot();
    // declear lazyLoad standby-avatar(seo-fix alt tips)
    if ($baas) {
?>
    <script type="text/javascript">
        //request AV.Query
        const link_query_all = new AV.Query("link"),
              friends = document.querySelector(".friends-boxes .deals.exchanged"),
              special = document.querySelector(".friends-boxes .deals.rcmd"),
              others = document.querySelector(".friends-boxes .deals.oldest .inboxSliderCard .slideBox"),
              loadlist = ["friends", "special", "others"],
              fill = function() {
                var compare = {
                        "status": "others",
                        "mark": "special"
                    };
                for(key in compare){
                    if(key==compare[key]){
                        let el = eval(compare[key]);
                        el.innerHTML += template(name,desc,avatar,link,sex,ssl,status)
                        el.querySelector("#loading").remove()
                    }
                }
              },
              template = (name,desc,avatar,link,sex,ssl,status,rel,mark)=>{
                  var templates;
                  if(status=="others"){
                      templates = `<a href="${link}" class="inbox-aside" target="_blank" rel="${rel||'nofollow'}">${name}</a>`
                  }else if(mark=="special"){
                      templates = `<div class="inbox flexboxes ${status} ${sex}"><a href="${link}" class="inbox-aside" target="_blank" rel="${rel||'recommend'}"><span class="lowside-title"><h4>${name}</h4></span><span class="lowside-description"><p>${desc}</p></span></a></div>`
                  }else{
                      templates = `<div class="inbox flexboxes ${status} ${sex}"><div class="inbox-headside flexboxes"><a href="${link}" target="_blank" rel="${rel||'friends'}"><img class="lazy" data-src="${avatar}" src="${avatar}" alt="${name}" draggable="false" /><span class="ssl ${ssl}">${ssl}</span></a></div><a href="${link}" class="inbox-aside" target="_blank" rel="${rel||'friends'}"><span class="lowside-title"><h4>${name}</h4></span><span class="lowside-description"><p>${desc}</p></span></a></div>`
                  };
                  return templates;
              };
        for(let i=0,listLen=loadlist.length;i<listLen;i++){
            let eachload = loadlist[i],
                loading = document.createElement("span"),
                evalload = eval(eachload);
            loading.id="loading";
            evalload.appendChild(loading);
        };
        link_query_all.addAscending("createdAt").limit(99).find().then(result=>{
            let marked = 0,
                dom=document.getElementById("left");
            for (let i=0; i<result.length;i++) {
                let res = result[i],
                    name = res.attributes.name,
                    desc = res.attributes.desc,
                    avatar = res.attributes.offline||res.attributes.online,
                    link = res.attributes.link,
                    sex = res.attributes.sex,
                    ssl = res.attributes.ssl,
                    mark = res.attributes.mark,
                    status = res.attributes.status,
                    sitelink = res.attributes.sitelink;
                mark=="friends"&&status!="others" ? marked++ : false;
                if(status=="others"){
                    others.innerHTML += template(name,desc,avatar,link,sex,ssl,status,'nofollow')
                }else if(mark=="special"){
                    special.innerHTML += template(name,desc,avatar,link,sex,ssl,status,'recommend',mark)
                }else{
                    friends.innerHTML += template(name,desc,avatar,link,sex,ssl,status,'friends')
                }
            };
            if(dom){
                marked<50 ? dom.innerHTML="友链数量即将达到 50 限制（当前：<b>"+marked+"</b>）在这之后" : dom.innerHTML="友链数量已达到限制<b> 50（<b>"+marked+"）</b>，";
            }
            // loading.remove();
            const loads = document.querySelectorAll("#loading");
            for(let i=0,loadLen=loads.length;i<loadLen;i++){
                loads[i].remove()
            }
        })
    </script>
<?php
    }
?>
</body></html>