//iframe.js
(function ($, window, document, undefined) {
    'use strict';

    let pluginName = 'iframes';
    let tabContainer = '';
    let frameContainer = '';
    let height = '700px';//以这种形式出现的iframe,必须设置高度,不能设置100%

    //已经打开的tab
    let openTabs = [];
    let breadcrumb = [];
    let breadcrumbMap = new Map();

    //入口方法
    $.fn[pluginName] = function (options) {
        let self = $(this);
        if (this == null)
            return null;
        let data = this.data(pluginName);
        if (!data) {
            data = new BaseIframe(this, options);
            self.data(pluginName, data);
        }
        return data;
    };
    let BaseIframe = function (element, options) {
        this.$element = $(element);
        this.options = $.extend(true, {}, this.default, options);
        tabContainer = $('#'+this.options.tabContainer);
        frameContainer = $('#'+this.options.frameContainer);
        // console.log(this.options,tabContainer,frameContainer);
        this.init();
    }
    //默认配置
    BaseIframe.prototype.default = {
        showIndex: 0, //默认显示页索引
        loadAll: false,//true=一次全部加在页面,false=只加在showIndex指定的页面，其他点击时加载，提高响应速度
        tabContainer: '',
        frameContainer: ''
    }
    // 结构模板参考
    // <ul class="nav nav-tabs page-header-tab" >
    //      <li class="nav-item">
    //          <a class="nav-link active" id="pills-calendar-tab" data-toggle="pill" href="#pills-calendar" role="tab" aria-controls="pills-calendar" aria-selected="false">单人关卡</a>
    //      </li>
    //      <li class="nav-item">
    //          <a class="nav-link" id="pills-timeline-tab" data-toggle="pill" href="#pills-timeline" role="tab" aria-controls="pills-timeline" aria-selected="true">对战关卡</a>
    //      </li>
    // </ul>
    // <div class="row clearfix">
    //      <div class="col-md-12 ">
    //          <div class="tab-content" id="pills-tabContent">
    //              <div class="tab-pane fade show active" id="pills-calendar" role="tabpanel" aria-labelledby="pills-calendar-tab">
    //                   <div class="card">
    //                      <div class="card-body">
    //                      </div>
    //                   </div>
    //              </div>
    //              <div class="tab-pane fade" id="pills-timeline" role="tabpanel" aria-labelledby="pills-timeline-tab">
    //                  <div class="card">
    //                      <div class="card-body">
    //                      </div>
    //                  </div>
    //              </div>
    //          </div>
    //      </div>
    // </div>
    //根据上面列子结构模板
    BaseIframe.prototype.template = {
        nav_tabs: '<ul class="nav nav-tabs page-header-tab" id="page-tabs"></ul>',
        nav_item: '<li class="nav-item"></li>',
        nav_a: '<a href="javascript:void(0);" class="nav-link " data-toggle="pill" role="tab" aria-selected="false" data-id="{0}" data-index="{1}" name="{2}" url="{3}">{2}</a>',//这里不能用id,id会追加代码到a标签内
        div_content:
            ' <div class="row clearfix">\n' +
            '    <div class="col-md-12 ">\n' +
            '        <div class="tab-content" id="tab-content">\n' +
            '        </div>\n' +
            '    </div>\n' +
            ' </div>',
        div_iframe: '' +
            '  <div class="tab-pane fade show active" id="iframe-content" role="tabpanel" aria-labelledby="pills-calendar-tab">\n' +
            '    </div>\n',
        iframe: '<iframe data-id="{0}" data-index="{1}"  name="{2}" src="{3}" height="{4}"  width="100%"  frameborder="0"  seamless style="display: none;"></iframe>',
        a_close: '<i class="fa fa-remove" title="关闭" data-id="{0}"></i>'
    }

    //初始化
    BaseIframe.prototype.init = function () {
        if (!this.options.data || this.options.data.length == 0) {
            console.error("请指定tab页数据");
            return;
        }
        //当前显示的显示的页面是否超出索引
        if (this.options.showIndex < 0 || this.options.showIndex > this.options.data.length - 1) {
            console.error("showIndex超出了范围");
            //指定为默认值
            this.options.showIndex = this.default.showIndex;
        }
        if (this.options.height) {
            height = this.options.height;
        }
        //清除原来的tab页
        tabContainer.html("");
        frameContainer.html("");
        this.builder(this.options.data);
    }

    //使用模板搭建页面结构
    BaseIframe.prototype.builder = function (data) {
        //生成菜单栏
        let nav_tabs = $(this.template.nav_tabs);
        for (let i = 0; i < data.length; i++) {
            let nav_item = $(this.template.nav_item);
            //nav-tab
            let nav_a = $(this.template.nav_a.format(data[i].id, i, data[i].text, data[i].url));
            //如果可关闭,插入关闭图标，并绑定关闭事件
            if (data[i].closeable) {
                let a_close = $(this.template.a_close.format(data[i].id));
                nav_a.append(" ");
                nav_a.append(a_close);
            }
            nav_item.append(nav_a);
            nav_tabs.append(nav_item);
        }

        let div_content = $(this.template.div_content);
        let div_iframe = $(this.template.div_iframe);
        div_content.find("#tab-content").append(div_iframe);
        //标签列表，和标签所显示的内容
        tabContainer.append(nav_tabs);
        frameContainer.append(div_content);
        this.loadData();
    }
    /**加载数据*/
    BaseIframe.prototype.loadData = function () {
        let data = this.options.data;
        //如果是当前页或者配置了一次性全部加载，否则点击tab页时加载
        for (let i = 0; i < data.length; i++) {
            // console.log(data[i].url);
            openTabs.push({id:data[i].id});
            // 同时处理顶部 breadcrumb，breadcrumb 根据 iframe name 区分
            breadcrumbMap.set(data[i].id,[]);
            if (this.options.loadAll || this.options.showIndex == i) {
                if (data[i].url) {
                    // 添加iframe，name 也是设置id
                    let iframe = $(this.template.iframe.format(data[i].id, i, data[i].id, data[i].url, height));
                    frameContainer.find("#iframe-content").append(iframe);
                } else {
                    console.error("id=" + data[i].id + "的iframe页未指定url");
                }
            }
        }
        console.log("初始化breadcrumbMap--",breadcrumbMap)
        //存在数据时候，设置active
        if (data.length > 1) {
            frameContainer.find("#iframe-content iframe").eq(this.options.showIndex).css("display", "inline");
            let dataId = tabContainer.find('#page-tabs a').eq(this.options.showIndex).addClass('active').attr("data-id");
            // console.log(tabContainer.find('#page-tabs a').eq(this.options.showIndex))
            breadcrumb = breadcrumbMap.get(dataId);
            console.log("设置当前的breadcrumb-1=",breadcrumbMap)
        } else {
            frameContainer.find("#iframe-content iframe").eq(0).css("display", "inline");
            let dataId = tabContainer.find('#page-tabs a').eq(0).addClass('active').attr("data-id");
            breadcrumb = breadcrumbMap.get(dataId);
            console.log("设置当前的breadcrumb-2=",breadcrumbMap)
        }
        //绑定事件
        BaseIframe.prototype.eventses();
    }
    /**
     * 添加Iframe
     * */
    BaseIframe.prototype.openIframe = function (context) {
        let {dataId, dataUrl, dataIndex} = context;
        // 获取标识数据
        let flag = true;
        if (dataUrl == undefined || $.trim(dataUrl).length == 0) return false;
        frameContainer.find("#iframe-content iframe").each(function () {
            // console.log('id', $(this).data('id'));
            // console.log('url', dataUrl);
            if ($(this).data('id') == dataId) {
                flag = false;
            }
        });
        if (flag) {
            //name 也是用id
            let iframe = $(this.template.iframe.format(dataId, dataIndex, dataId, dataUrl, height));
            frameContainer.find("#iframe-content").append(iframe);
        }
        //打开页面时候，切换
        breadcrumb = breadcrumbMap.get(dataId);
        console.log('切换tab',dataId,breadcrumbMap);
        BaseIframe.prototype.showBreadcrumb();
        BaseIframe.prototype.hidden_a(dataId);
        return false;
    }

    /**点击事件*/
    BaseIframe.prototype.eventses = function () {
        //关闭按钮
        tabContainer.find("#page-tabs a i").each(function () {
            $(this).click(function () {
                let id = $(this).data('id');
                console.log('ad0', id);
                BaseIframe.prototype.remove(id);
            });
        });
        //切换tab
        tabContainer.find("#page-tabs a").click(function () {
            // console.log("点击a: ", this);
            let dataId = $(this).data('id');
            // var menuName = $(this).text();
            // let menuName = $(this).attr('name');
            let dataUrl = $(this).attr('url');
            let dataIndex = $(this).data('index');
            BaseIframe.prototype.openIframe({
                dataUrl, dataIndex, dataId
            });
        });

    }

    //新增一个Iframe页
    BaseIframe.prototype.addIframe = function (obj) {
        let bAdd = false;
        for(let i=0;i<openTabs.length;i++){
            if(obj.id=== openTabs[i].id){
                bAdd = true;
                break;
            }
        }
        if(bAdd){
            console.log('已添加过标签');
            return;
        }
        let _index = $('#page-tabs a').length;
        let nav_a = $(this.template.nav_a.format(obj.id,_index,obj.text,obj.url));
        //如果可关闭,插入关闭图标，并绑定关闭事件
        if (obj.closeable) {
            let a_close = $(this.template.a_close.format(obj.id));
            nav_a.append(" ");
            nav_a.append(a_close);
        }
        let nav_item = $(this.template.nav_item);
        nav_item.append(nav_a);
        tabContainer.find('#page-tabs').append(nav_item);
        BaseIframe.prototype.eventses();
        //添加标签记录
        openTabs.push({id:obj.id});
        // 同时处理顶部 breadcrumb，breadcrumb 根据 iframe name 区分
        breadcrumbMap.set(obj.id,[]);
        //自动切换到当前页面
        BaseIframe.prototype.openIframe({
            dataUrl:obj.url, dataIndex:_index, dataId:obj.id
        });
    }

    /**隐藏其他的,显示当前*/
    BaseIframe.prototype.hidden_a = function (obj) {
        tabContainer.find('#page-tabs a').each(function () {
            $(this).removeClass('active');
        });
        frameContainer.find('#iframe-content iframe').each(function () {
            $(this).css("display", "none");
        });
        frameContainer.find("iframe[name='" + obj + "']").css("display", "inline");
        tabContainer.find("a[name='" + obj + "']").addClass('active');
    }

    //根据id获取活动也标签名
    BaseIframe.prototype.find = function (tabId) {
        return tabContainer.find(".nav-tabs li a[href='#" + tabId + "']").text();
    }

    // 删除活动页
    BaseIframe.prototype.remove = function (obj) {
        frameContainer.find("#iframe-content iframe[data-id='" + obj + "']").remove();
        tabContainer.find("#page-tabs a[data-id='" + obj + "']").parent().remove();
        for (let i=0;i<openTabs.length;i++){
            if(obj === openTabs[i].id){
                openTabs.splice(i,1);
                break;
            }
        }
        //设置一个显示的元素
        tabContainer.find('#page-tabs a').eq(0).addClass('active');
        frameContainer.find("#iframe-content iframe").eq(0).css("display", "inline");
        if (tabContainer.find('#page-tabs a').length > 0) {
            let a = tabContainer.find('#page-tabs a').eq(0);//todo 找到第一个a标签取出数据
            this.openIframe({
                dataUrl: a.attr('url'),dataIndex: a.data('index'), dataId: a.data('id')
            });
        }
    }

    //根据id设置活动iframe页
    BaseIframe.prototype.showIframe = function (tabId) {
        let a = tabContainer.find("#page-tabs a[name='" + tabId + "']");//找到a标签
        console.log("a标签", a);
        let dataUrl = a.data('id');
        let dataIndex = a.data('index');
        BaseIframe.prototype.openIframe(dataUrl, tabId, dataIndex);
    }

    BaseIframe.prototype.showBreadcrumb = function(callback){
        $(".breadcrumb").html('');
        breadcrumb.forEach((value, index, array)=>{
            let _breadcrumb_item_li = '<li class="breadcrumb-item"><a name="{2}" href="javascript:void(0);">{1}</a></li>';
            let _breadcrumb_item = $(_breadcrumb_item_li.format(value.url, value.name, value.index));
            $(".breadcrumb").append(_breadcrumb_item);
            _breadcrumb_item.click(()=>{
                if(value.index == breadcrumb[breadcrumb.length-1].index) return;
                let _id = BaseIframe.prototype.getCurrentIframeId();
                console.log({
                    dataUrl:value.url, indexName:value.name, dataIndex:value.index, dataId:_id
                });
                let _frame = window.frames[_id];
                _frame.history.go(-(breadcrumb.length-value.index));
                if(callback)
                    callback(value);
            });
        })
    }

    BaseIframe.prototype.setBreadcrumb = function(item){
        let {index} = item;
        let hasIndex = false;
        let spliceIndex = 0;
        for (let i=0;i<breadcrumb.length;i++){
            if(index === breadcrumb[i].index){
                hasIndex = true;
                spliceIndex =i;
                // console.log(index,i);
                break;
            }
        }
        if(hasIndex){
            console.log("splice1",spliceIndex)
            breadcrumb.splice(spliceIndex+1,breadcrumb.length-1);
        }else{
            console.log("splice2",item.url, item.name, item.index)
            breadcrumb.push(item);
        }
        BaseIframe.prototype.showBreadcrumb((value)=>{
            BaseIframe.prototype.setBreadcrumb(value);
        });
        console.log(breadcrumb);
    }

    //获取当前活动iframe页的ID
    BaseIframe.prototype.getCurrentIframeId = function () {
        let id = tabContainer.find("#page-tabs .active").attr("data-id");
        console.log('id', id);
        return id;
    }

    String.prototype.format = function () {
        if (arguments.length == 0) return this;
        let s = this;
        for (let i = 0; i < arguments.length; i++)
            s = s.replace(new RegExp("\\{" + i + "\\}", "g"), arguments[i]);
        return s;
    };
})(jQuery, window, document)