/**
 * 系统工作台之消息页面JS
 *
 * Created by li.kui on 2021/3/11.
 */
'use strict';

// 新闻动态缩略图轮播对象
var sWiperPlug;
var screenWidth = window.screen.width;

/**
 * 文档就绪
 */
$(function () {

    // 初始化页面轮播
    // initPageCarousel();

    // 刷新页面顶部供应商相关统计; isSup -> 0:非供应商 1:供应商
    var isSup = $('#isSup').val();
    if (Number(isSup) === 0) {
        refreshSupplierStatistics();
    }

    // 初始化新闻动态
    refreshNewsDynamic();

    // 初始化站内消息
    refreshSiteMessage();

    // 初始化预警信息
    refreshEarlyWarning();

    // 初次加载自定义应用导航
    refreshCustomNavigation();
});


/**
 * 初始化页面轮播对象
 */
function initPageCarousel() {
    sWiperPlug = new Swiper('.swiper-container', {
        // 无限轮播
        loop: true,
        // 滑动速度(ms)
        speed: 1000,
        // 自动滑动
        // autoplay: true,
        autoplay: {
            delay: 2000,
            stopOnLastSlide: false,
            disableOnInteraction: false
        },
        // 底部分页器 HTML .swiper-container 节点下面
        pagination: {
            el: '.swiper-pagination'
        },
        // 分页器可以点击
        paginationClickable: true,
        // 用于防止触摸时触发链接跳转
        preventClicks: true,
        // 阻止click冒泡 拖动Swiper时阻止click事件
        preventClicksPropagation: true,
        // 事件监听
        on: {
            // 单击事件
            tap: function (swiper) {
                openNewsDetail(swiper.path[0]);
            }
        }
    });
}


/**
 * 刷新供应商统计
 */
function refreshSupplierStatistics() {
    $.ajax({
        type: 'POST',
        url: g.ctx + 'system/workbench/rest/find/sup/statistics',
        success: function (data) {
            var html = [], statisticsDiv = $('.statistics');
            if (data.length === 0) {
                statisticsDiv.empty();
            } else {
                for (var i = 0; i < data.length; i++) {
                    var item = data[i], divImg = '/static/img/zc_agent.png', statisticsBoxClass = '';
                    switch (i) {
                        case 1:
                            divImg = '/static/img/qz_agent.png';
                            statisticsBoxClass = 'statistics-box1';
                            break;
                        case 2:
                            divImg = '/static/img/hg_agent.png';
                            statisticsBoxClass = 'statistics-box2';
                            break;
                        case 3:
                            divImg = '/static/img/zs_agent.png';
                            statisticsBoxClass = 'statistics-box3';
                            break;
                    }
                    html.push('<li onclick="openMenuPage(this)" data-rid="' + item.resId + '" data-rui="' + item.resUrl + '" data-rn="' + item.resName + '" data-dtn="' + item.dwtTotalNum + '">');
                    html.push('<div class="box ' + statisticsBoxClass + '">');
                    html.push('<img src="' + divImg + '" alt="">');
                    html.push('<div class="ctx">');
                    html.push('<div class="num">' + item.dwtTotalNum + '</div>');
                    html.push('<div>' + item.dwtName + '</div>');
                    html.push('</div>');
                    html.push('</div>');
                    html.push('</li>');
                }

                statisticsDiv.empty();
                statisticsDiv.html(html.join(''));
            }
        }
    });
}


/**
 * 刷新新闻动态
 */
function refreshNewsDynamic() {
    $.ajax({
        type: 'POST',
        url: g.ctx+'pc/sys/notice/rest/list?page=1&rows=15',
        success: function (data) {
            console.log(data.rows)
            var html1 = [], newsDynamicDiv = $('.news-dynamic'), html2 = [], wrapperDiv = $('.swiper-wrapper');
            if (data.rows.length === 0) {
                newsDynamicDiv.empty();
                wrapperDiv.empty();

                html2.push('<div class="swiper-slide">');
                html2.push('<img src="/static/img/news_dynamic.png" alt="" data-id="0">');
                html2.push('</div>');
            } else {
                for (var i = 0; i < data.rows.length; i++) {
                    var item = data.rows[i];
                    html1.push('<li onclick="openNewsDetail(this)" data-id="' + item.id + '">');
                    html1.push('<div class="title" title="' + item.title + '">');
                    html1.push('<span></span>' + item.title);
                    html1.push('</div>');
                    html1.push('<div class="date">');
                    html1.push('<sapn class="name">' + item.publishUserName + '</sapn>');
                    html1.push(moment(item.publishTime).format('YYYY-MM-DD'));
                    html1.push('</div>');
                    html1.push('<div style="clear: both;"></div>');
                    html1.push('</li>');

                    // if (item.pic) {
                    //     item.pic = g.ctx + '/pc/sys/file/rest/download/' + item.pic;
                    //     html2.push('<div class="swiper-slide">');
                    //     html2.push('<img src="' + item.pic + '" alt="" data-id="' + item.id + '">');
                    //     html2.push('</div>');
                    // }
                }

                newsDynamicDiv.empty();
                newsDynamicDiv.html(html1.join(''));

                // 新闻消息轮播器
                // wrapperDiv.empty();
                // wrapperDiv.html(html2.join(''));
                // initPageCarousel();
            }
        }
    });
}


/**
 * 刷新站内消息
 */
function refreshSiteMessage() {
    $.ajax({
        type: 'POST',
        url: g.ctx + 'system/workbench/rest/find/site/message',
        success: function (data) {
            var html = [], siteMessageDiv = $('.site-message');
            if (data.length === 0) {
                siteMessageDiv.empty();
            } else {
                for (var i = 0; i < data.length; i++) {
                    var item = data[i];
                    html.push('<li onclick="openSiteMessageDetail(this)" data-id="' + item.id + '" data-did="' + item.detailId + '" data-cf="' + item.ccFlag + '" data-read="' + item.readFlag + '">');
                    html.push('<div class="title" title="' + item.title + '">');

                    if (Number(item.readFlag) === 0) {
                        html.push('<span></span>' + item.title + '<img style="margin-top: -5px;" src="/static/img/new-message.png" />');
                    } else {
                        html.push('<span></span>' + item.title);
                    }

                    html.push('</div>');
                    html.push('<div class="date">');
                    html.push('<sapn class="name">' + item.createUserName + '</sapn>');
                    html.push(moment(item.createTime).format('YYYY-MM-DD'));
                    html.push('</div>');
                    html.push('<div style="clear: both;"></div>');
                    html.push('</li>');
                }

                siteMessageDiv.empty();
                siteMessageDiv.html(html.join(''));
            }
        }
    });
}


/**
 * 刷新预警信息
 */
function refreshEarlyWarning() {
    $.ajax({
        type: 'POST',
        url: g.ctx + 'pc/sys/home/rest/find/early/warning',
        success: function (data) {
            var html = [], warningDiv = $('.warning');
            if (data.length === 0) {
                warningDiv.empty();
                $('#warningMessage').css('display', 'none');
            } else {
                $('#warningMessage').css('display', 'block');

                for (var i = 0; i < data.length; i++) {
                    var item = data[i];
                    html.push('<div class="warning-box">');
                    html.push('<div class="warning-title">');
                    html.push('<span></span>' + item.targetTypeName);
                    html.push('</div>');
                    html.push('<ul class="warning-item">');

                    for (var j = 0; j < item.dwtList.length; j++) {
                        var dwt = item.dwtList[j], dwtTotalNum = dwt.dwtTotalNum;

                        html.push('<li onclick="openMenuPage(this)" data-rid="' + dwt.resId + '" data-rui="' + dwt.resUrl + '" data-rn="' + dwt.resName + '" data-dtn="' + dwtTotalNum + '">');
                        html.push('<div class="title">');
                        html.push('<img src="/static/img/pz_icon.png" alt="">' + dwt.dwtName);
                        html.push('</div>');
                        if (Number(dwtTotalNum) > 0) {
                            // html.push('<div class="date" style="color: #EB5F02;font-weight: 600">' + dwt.dwtTotalNum + '</div>');
                            html.push('<span class="layui-badge date">' + dwt.dwtTotalNum + '</span>');
                        } else {
                            html.push('<div class="date" style="color: grey;font-weight: 600">' + dwt.dwtTotalNum + '</div>');
                        }

                        html.push('</li>');
                    }

                    html.push('</ul>');
                    html.push('</div>');
                }

                warningDiv.empty();
                warningDiv.html(html.join(''));
            }
        }
    });
}


/**
 * 刷新自定义导航
 */
function refreshCustomNavigation() {
    $.ajax({
        type: 'GET',
        url: g.ctx + 'pc/sys/shortcut/rest/user',
        success: function (data) {
            var html = [], navBox = $('.nav-box');
            if (data.length === 0) {
                navBox.empty();
            } else {
                var moreNav = 0;
                var iconNum = parseInt(((screenWidth - 200 - 400) / 80).toFixed(0));
                iconNum = iconNum > 12 ? 12 : iconNum;
                if (data.length > iconNum) {
                    data = data.splice(0, iconNum);
                    moreNav = 1;
                }

                for (var i = 0; i < data.length; i++) {
                    var n = i + 1;
                    var item = data[i], quickMenuImg = '/static/img/customNavigationIcon/' + n + '.png';
                    html.push('<div class="nav-menu" onclick="openMenuPage(this)" data-rid="' + item.resId + '" data-rui="' + item.resourceUrl + '" data-rn="' + item.resourceName + '" data-dtn="1">');
                    html.push('<img src="' + quickMenuImg + '" alt="">');
                    html.push('<div style="margin-top: 5px;">' + item.resourceName + '</div>');
                    html.push('</div>');
                }

                if (Number(moreNav) === 1) {
                    html.push('<div class="nav-menu" onclick="openMoreNav()">');
                    html.push('<img src="/static/img/more.png" alt="">');
                    html.push('<div style="margin-top: 5px;">更多</div>');
                    html.push('</div>');
                }

                navBox.empty();
                navBox.html(html.join(''));
            }
        }
    });
}


/**
 * 自定义设置应用导航
 */
function customSettingsNavigation() {
    var csnDialog = openDialog('csn', g.ctx + 'pc/sys/shortcut/config', {
        title: '自定义设置应用导航',
        width: '80%',
        height: '80%',
        cache: false,
        modal: true,
        border: false,
        draggable: false,
        shadow: false,
        onClose: function () {
            csnDialog.dialog('destroy');
        },
        buttons: [
            {
                text: itablei8n.save,
                iconCls: 'icon-save',
                handler: function () {
                    topWin.frames['csn'].dataSave(function () {
                        topWin.layer.msg('数据保存成功', {icon: 1});
                        csnDialog.dialog('close');

                        refreshCustomNavigation();
                    });
                }
            },
            {
                text: itablei8n.close,
                iconCls: 'icon-clear',
                handler: function () {
                    csnDialog.dialog('close');
                }
            }
        ]
    });
}


/**
 * 打开快捷应用更多
 */
function openMoreNav() {
    layer.open({
        type: 2,
        title: false,
        closeBtn: false,
        shade: [0.01, '#FFF'],
        shadeClose: true,
        move: false,
        fixed: false,
        skin: 'layui-anim layui-anim-rl layui-layer-adminRight',
        offset: 'rb',
        area: ['180px', '200px'],
        anim: 2,
        content: g.ctx + 'user/shortcut/more'
    });
}


/**
 * 打开菜单页面
 */
function openMenuPage(ele) {
    var rid = $(ele).data('rid'), rui = $(ele).data('rui'), rn = $(ele).data('rn');
    var dwtTotalNum = $(ele).data('dtn');
    if (Number(dwtTotalNum) > 0) {
        parent.tabAdd(rn, rui, rid, true);
    }
}


/**
 * 打开新闻动态详情
 *
 * @param ele DOM节点
 */
function openNewsDetail(ele) {
    var newsId = $(ele).data('id');
    if (newsId > 0) {
        var url = g.ctx + 'pc/sys/notice/look?id=' + newsId;
        var newsDetailDialog = openDialog('newsDetail', url, {
            title: '新闻动态详情',
            width: '80%',
            height: '80%',
            cache: false,
            modal: true,
            border: false,
            draggable: false,
            shadow: false,
            maximizable: true,
            maximized: true,
            onClose: function () {
                newsDetailDialog.dialog('destroy');
            },
            buttons: [
                {
                    text: itablei8n.close,
                    iconCls: 'icon-clear',
                    handler: function () {
                        newsDetailDialog.dialog('close');
                    }
                }
            ]
        });
    }
}


/**
 * 打开更多新闻动态
 */
function openMoreNews() {
    var rid = -1000, rui = g.ctx + 'pc/sys/notice/more', rn = '更多新闻动态';
    parent.tabAdd(rn, rui, rid, true);
}


/**
 * 打开站内消息详情
 *
 * @param ele DOM节点
 */
function openSiteMessageDetail(ele) {
    // msgId -> 站内消息ID;  detailId -> 站内消息明细ID; ccFlag -> 抄送标识(1:抄送消息 2:非抄送消息); readFlag -> 已读标识(0:未读 1:已读)
    var msgId = $(ele).data('id'), detailId = $(ele).data('did'), ccFlag = $(ele).data('cf'),
        readFlag = $(ele).data('read');

    var url = g.ctx + 'messageReceivedSupplierRest/detail?messageId=' + msgId + '&addresseeId=' + detailId;

    // 1.设置站内消息已读(需先判断是否需要设置已读)
    // 2.打开消息详情
    if (Number(readFlag) === 1) {
        openMessageDialog(url);
    } else {
        $.ajax({
            url: g.ctx + 'system/workbench/rest/set/message/read',
            type: 'POST',
            data: {mdId: detailId, ccFlag: ccFlag},
            success: function () {
                openMessageDialog(url);
            },
            error: function () {
                parent.layer.alert(common_opt_msg.opt_fail_message, {icon: 2});
            }
        });
    }
}


/**
 *打开更多站内消息
 */
function openMoreMessage() {
    var rid = -1001, rui = '/messageReceivedRest/listUI', rn = '更多站内消息';
    parent.tabAdd(rn, rui, rid, true);
}


/**
 * 打开站内消息详情弹框
 *
 * @param url 弹框内容地址
 */
function openMessageDialog(url) {
    parent.layer.open({
        skin: 'layui-layer-molv',
        title: '消息详情',
        type: 2,
        scrollbar: false,
        area: ['80%', '80%'],
        maxmin: false,
        content: url,
        cancel: function () {
            refreshSiteMessage();
        }
    });
}


/**
 * 重启轮播(不要问为什么)
 * 现象: EasyUI-Tab切换时轮播会停止, 实际上轮播器的状态还是running的状态
 */
function restartSWiperPlay() {
    // 销毁轮播器
    sWiperPlug.destroy();
    initPageCarousel();
}