/**
 * 视图控制
 * @date 2014-4-11
 * @author zhulin
 */
define(function (require, exports, module) {
    'use strict';
    var msg = require('./msg.js');
    var sendLog = require('./log.js');
    var Box = require('./popout/index.js');
    var drControl = require('depricedReminder.js'); // 降价提醒模块方法

    var view = module.exports;

    // --------------------------------------------------------------------
    // 配置项 start
    // --------------------------------------------------------------------
    // 模板引用
    var tmpls = {

        // 收藏夹条目模板，all/depriced/promitioned 共用
        collections : _.template(require('./templates/collections.html')),
        // 降价提醒订阅项模板
        depricedReminders : _.template(require('./templates/depricedReminder.html')),

        // bundle controls 包括上下页和全选删除
        bundleOps : _.template(require('./templates/bundleOps.html')),

        // 无收藏
        noCollection : _.template(require('./templates/noCollection.html')),
        // 无降价提醒订阅
        noDepricedItem : _.template(require('./templates/noDepricedItem.html')),
        // 无促销
        noPromotion : _.template(require('./templates/noPromotion.html')),

        // 未登录提示框
        noLogin : _.template(require('./templates/noLogin.html')),

        // 正在加载
        loading : _.template(require('./templates/loading.html')),

        // 网络错误
        offLine : _.template(require('./templates/offLine.html')),

        // 页码控制 供所有类别使用
        pageBtns : _.template(require('./templates/pageIndicators.html'))
    };


    var colllectionTabs = ['all', 'depriced', 'promotion'];
    var supportedType = ['all', 'depriced', 'promotion', 'depricedReminder'];

    // 视图参数配置
    view.ref = {
        'all' : {
            container : $('#allContainer'),
            tmpl : tmpls.collections,
            emptyTmpls : tmpls.noCollection,
            pagesCounts : undefined,
            hdControls : $('#allOps')
        },
        'depriced' : {
            container : $('#depricedContainer'),
            tmpl : tmpls.collections,
            emptyTmpls : tmpls.noDepricedItem,
            pagesCounts : undefined,
            hdControls : $('#depricedOps')
        },
        'promotion' : {
            container : $('#promotionContainer'),
            tmpl : tmpls.collections,
            emptyTmpls : tmpls.noPromotion,
            pagesCounts : undefined,
            hdControls : $('#promotionOps')
        },
        'depricedReminder' : {
            container : $('#depricedReminderContainer'),
            tmpl : tmpls.depricedReminders,
            emptyTmpls : tmpls.noDepricedItem,
            pagesCounts : undefined,
            hdControls : $('#depricedReminderOps')
        },
        containerSelector : '.list',
        loadingSelector : '.loading',
        pageBtnsContainerSelector : '.pageBtns'
    };

    var PAFE_COUNTS_IN_SHOW = 3; // 最多展示的页码按钮数目/2

    var ref = view.ref;

    // --------------------------------------------------------------------
    // 配置项 end
    // --------------------------------------------------------------------


    // --------------------------------------------------------------------
    // 私有方法 begin
    // --------------------------------------------------------------------

    var allSelectedFlag = false;// 是否当前处于全选状态

    /**
     * 批量事件绑定代理辅助函数
     * @param  {[type]} eventsConf [description]
     * {
     *     eventType selector, callback
     *     'click #selectAll' : selectAll,
     *     'click #deleteSelected' : deleteSelected,
     *     'click #deleteCurItem' : deleteCurItem,
     * }
     * @param  {selector} el  事件绑定的目标元素选择器, 或者目标元素
     * @return {[type]}            [description]
     */
    var _eventsBinder= function (eventsConf, el) {

        if (!_.isObject(eventsConf)) {
            throw new Error('事件绑定参数错误');
        }

        if (el === undefined) {
            // 默认绑定到document上
            el = document;
        }

        var eventType, target, callback;
        for (var evnt in eventsConf) {
            if (eventsConf.hasOwnProperty(evnt)) {
                callback = eventsConf[evnt];
                target = evnt.split(' ');
                eventType = target.shift();
                target = target.join(' ');

                $(el).on(eventType, target, callback);
            }
        }

    };

    /**
     * 渲染收藏夹数据
     * @param  {[type]} data [description]
     * @param  {[type]} type [all | depriced]
     * @return {[type]}      [description]
     */
    var _renderCollections = function (type, data) {

        if ( !_.isArray(data) || _.indexOf(supportedType, type) === -1) {
            // 参数类型错误
            throw new Error('返回数据不是数组！或者是填错参数啦，all或者depriced类型的啦！');
            return false;

        }

        var temp = {};
        temp.list = data || [];
        return view.ref[type].tmpl(temp);

    };


    /**
     * 渲染页码控制区域
     * @param  {[type]} cur 当前页码
     * @param  {[type]} max   最大页码
     */
    var _pageControlsRender = function (cur, max) {

        var LENGTH  = 5; // 展示数目 - 4{}
        var startInx, endInx; // 计算要展示的页码范围
        var hasFirstFolder = false,
            hasLastFolder = true; // 是否展示前后..
        // 1 和 max是肯定会展示的

        if (max <=9) {
            startInx = 2;
            endInx = max - 1;
            hasLastFolder = false;
            hasFirstFolder = false;
        } else {
            if (cur <= LENGTH) {
                startInx = 2;
                if (LENGTH + 2 >= max) {
                    endInx = max - 1;
                    hasLastFolder = false;
                } else {
                    endInx = LENGTH + 2;
                }
            } else if (cur <= max - LENGTH) {
                startInx = cur - 2;
                endInx = cur + 2;
                hasFirstFolder = true;
                hasLastFolder = true;
            } else {
                // cur > max - Length
                startInx = max - 6;
                endInx = max - 1;
                hasFirstFolder = true;
                hasLastFolder = false;
            }
        }

        hasFirstFolder = (startInx - 1 >1);
        hasLastFolder = (max - endInx >1);


        var conf = {
            startInx : startInx,
            endInx : endInx,

            hasFirstFolder : hasFirstFolder,
            hasLastFolder : hasLastFolder,

            pagesCounts : max,
            curPage : cur // 当前页
        };
        return tmpls.pageBtns(conf);
    };

    // -------------------------------------------------------------------------
    // 暴露出去供index调用的接口
    /**
     * 设置降价提醒tab按钮上的浮标数字
     */
    view.setNumber = function (selector, number, originalNumber) {
        $(selector).text(number).toggle(originalNumber > 0 );
    };


    /**
     * 初始化 渲染头部批量控制和上下页
     */
    view.init = function () {
        _.each(supportedType, function (type) {
            $('.ops' + '[data-type=' + type + ']').html(tmpls.bundleOps());
        });
        $('.ops').first().show();
        $('.go-top').hide();

    };

    view.checkContents = function (type) {
        return (ref[type].container.find('.list').children().length === 0);
    };

    /**
     * 渲染新tab
     * @param  {[type]} type    [description]
     * @param  {[type]} data    [description]
     * @param  {[type]} curPage [description]
     * @return {[type]}         [description]
     */
    view.renderNewTab = function (type, data, curPage, maxPage) {

        var listCont = ref[type].container.find(ref.containerSelector);
        var pageBtnsCont = ref[type].container.find(ref.pageBtnsContainerSelector);

        listCont.html(_renderCollections(type, data));

        pageBtnsCont.html(_pageControlsRender(curPage, maxPage));

    };

    /**
     * 渲染无数据模板
     */
    view.renderNoDataTip = function (type) {
        ref[type].container.html(view.ref[type].emptyTmpls({}));
    };

    /**
     * 追加渲染当前tab
     */
    view.appendCurTab = function (type, data) {
        var temp = $(_renderCollections(type, data));
        temp.appendTo(ref[type].container.find(ref.containerSelector));

        // 判断当前是否在全选状态
        // 全选状态的话需要自动全选后添加的项
        if (allSelectedFlag) {
            temp.find('.select').click();
        }
    };

    /**
     * 删除指定条目
     */
    view.deleteItem =  function (url) {
        var item = $('[data-url="' + url + '"]');
        item.css({
            'transition' : '.3 opacity',
            'opacity' : .5
        });
        setTimeout(function() {
            item.remove();
        }, 300);
    };

    /**
     * 更新头部页码导航状态
     */
    view.refreshPageControl = function (type, prevFlag, nextFlag) {
        var hdPageBtns = ref[type].hdControls;
        hdPageBtns.find('.next').toggleClass('disable', !nextFlag);
        hdPageBtns.find('.prev').toggleClass('disable', !prevFlag);

    };

    view.renderNoLoginTip = function () {
        var targetUrl = encodeURIComponent('http://zhushou.huihui.cn/myzhushou');
        var data = {
            noLogin : {
                loginUrl : 'http://www.huihui.cn/login?url=' + targetUrl
            }
        };

        view.ref['all'].container.html(tmpls.noLogin(data));
    };

    view.renderLoadingTip = function (type) {
        var curRef = view.ref[type];
        var loadingMod = curRef.container.find(ref.loadingSelector);
        if (loadingMod.children().length === 0 ) {
            loadingMod.html(tmpls.loading());
        } else if (loadingMod.children('.offline').length !== 0) {
            loadingMod.html(tmpls.loading()).show();
        } else {
            loadingMod.show();
        }
    };
    view.hideLoadingTip = function (type) {
        var curRef = view.ref[type];
        var loadingMod = curRef.container.find(ref.loadingSelector);
        loadingMod.hide();
    };

    view.renderOffLineTip = function (type) {
        var curRef = ref[type];
        curRef.container.find('.loading').html(tmpls.offLine());
    };

    // -------------------------------------------------------------------------
    // 注册dom事件
    // -------------------------------------------------------------------------

    /**
     * 事件配置
     */
    var domEvents = {
        selectSingleItem : function () {
            var curType = $(this).parents('.items-list').data('type');
            var $selectAll = ref[curType].hdControls.find('.selectAll');
            if (allSelectedFlag) {
                if ( $($selectAll[0].checked)) {
                    $selectAll[0].checked = false;
                    allSelectedFlag = false;
                }
            } else {
                // check 是否是全选状态
                if (_.every($('.items-list:visible .select'), function (item) {
                    return item.checked;
                })) {
                    allSelectedFlag = true;
                    $selectAll[0].checked = true;
                }

            }
        },

        /**
         * 全选或者全不选
         */
        selectAll : function (e) {
            allSelectedFlag = this.checked;
            _.each($('.items-list:visible').find('.select'), function (item) {
                item.checked = allSelectedFlag;
            });

        },

        /**
         * 删除选中项目
         */
        deleteSelected : function (e) {
            var type = $(this).parents('.ops').data('type');
            var urls = [];
            var list = ref[type].container.find('.select');
            _.each(list, function (item) {
                if (item.checked) {
                    urls.push($(item).parents('li').data('url'));
                }
            });

            if (urls.length === 0) {
                return;
            }

            // log
            sendLog('FAVOR_ITEM_SELECTDEL_CLICK');

            var $confirmBox;
            var bundleDeleteBoxId = 'bundleDeleteBoxId';
            // 弹窗确认
            $confirmBox = new Box({
                'containerId' : bundleDeleteBoxId,
                'title' : '批量删除',
                'hasCancel' : true,
                'contentsHtmlString' : '<p>确定删除所选收藏商品？</p>'
            }, {
                'click .pop-out-btn-confirm' : function () {
                    msg.fire('deleteItems', urls, function () {
                        _.each(urls, function (url) {
                            view.deleteItem(url);
                        });
                    });
                    $confirmBox.remove();
                }
            });

        },

        /**
         *  删除当前条目
         */
        deleteCurItem : function (e) {
            var url = $(this).parents('li').data('url');

            var $confirmBox = undefined;
            var deleteBoxId = 'deleteBoxId';
            // 弹窗确认
            $confirmBox = new Box({
                'containerId' : deleteBoxId,
                'title' : '删除',
                'hasCancel' : true,
                'contentsHtmlString' : '<p>确定删除所选收藏商品？</p>',
                cbAfterCancel : function(cancelMethod) {
                    // 发送取消的log
                    sendLog('FAVOR_DALDEL_CANCEL_CLICK', undefined, cancelMethod);
                }
            }, {
                'click .pop-out-btn-confirm' : function () {
                    msg.fire('deleteItems', url, function () {
                        view.deleteItem(url);
                    });
                    $confirmBox.remove();
                    sendLog('FAVOR_DALDEL_CONFIRM_CLICK');

                }
            });
        },

        /**
         *  页码控制
         */
        goToPage : function (e) {
            e.preventDefault();

            // 删除选定状态
            allSelectedFlag = false;
            $('#allOps input').attr('checked', false);

            if($(this).hasClass('disable')) return;
            var pageInx = $(this).data('inx') || '#';

            var source = $(this).parents('.page-indecators-container').data('source');
            msg.fire('goToPage', pageInx, source);

        },

        modifyEmail : function (e) {
            e.preventDefault();
            var email = $(this).data('email');
            // 修改订阅邮箱
            drControl.modifyEmail(email);
        },

        cancelSubscribtion : function (e) {
            e.preventDefault();
            var curItem = $(this).parents('li');
            var subscriptionData = curItem.data();


            var $confirmBox;
            var deleteBoxId = 'deleteBoxId';
            // 弹窗确认
            $confirmBox = new Box({
                'containerId' : deleteBoxId,
                'title' : '删除',
                'hasCancel' : true,
                'contentsHtmlString' : '<p>确定删除所选订阅商品？</p>',
                cbAfterCancel : function(cancelMethod) {
                    // 发送取消的log
                    sendLog('PRICEALERT_DALDEL_CANCEL_CLICK', undefined, cancelMethod);
                }
            }, {
                'click .pop-out-btn-confirm' : function () {

                    sendLog('PRICEALERT_DALDEL_CONFIRM_CLICK');
                    drControl.cancelSubscribtion(subscriptionData, function () {
                        // 更新本地数据
                        msg.fire('deleteItems', subscriptionData.url, function () {

                            // 移除页面中的当前元素
                            curItem.remove();

                        })
                    });
                    $confirmBox.remove();
                }
            });

        },

        /**
         * 批量取消订阅
         */
        cancelBundledSubcribtion : function (e) {
            e.preventDefault();
            var datas = [];
            var list = $('#depricedReminderContainer .list .select');
            _.each(list, function (item) {
                if (item.checked) {
                    datas.push($(item).parents('li').data());
                }
            });

            if (datas.length === 0) {
                // 当前无选中元素
                return;
            }

            sendLog('PRICEALERT_SELECTITEM_DEL_CLICK');


            // 弹窗确认
            var $bundleCanelConfirmBox;
            var bundleCanelBoxId = 'bundleCanelBoxId';
            $bundleCanelConfirmBox = new Box({
                'containerId' : bundleCanelBoxId,
                'title' : '批量删除',
                'hasCancel' : true,
                'contentsHtmlString' : '<p>确定删除所选订阅商品？</p>',
                cbAfterCancel : function(cancelMethod) {
                    // 发送取消的log
                    sendLog('PRICEALERT_DALDEL_CANCEL_CLICK', undefined, cancelMethod);
                }
            }, {
                'click .pop-out-btn-confirm' : function () {

                    var items = _.where(datas, {
                        iscluster : false
                    });

                    var clusters = _.where(datas, {
                        iscluster : true
                    });

                    var itemsIds = _.pluck(items, 'id');
                    var clusterIds = _.pluck(clusters, 'id');
                    var urls = _.pluck(datas, 'url');

                    drControl.cancelBundledSubcribtion(itemsIds, clusterIds, function () {
                        msg.fire('deleteItems', urls);
                    });
                    $bundleCanelConfirmBox.remove();
                }
            });

        },

        slideControl : function () {
            var $btn = $(this);
            if ($btn.hasClass('prev-disable') || $btn.hasClass('next-disable')) {
                return;
            }

            var type = $btn.data('btn-type');

            var curContainer = $btn.parents('.items-recmds');
            var curContents = curContainer.find('.recom-contents');

            var length = curContents.find('.recom-content').length;
            var cur = curContainer.data('curInx') || 0;

            cur = ( type === 'next' ? cur + 3 : cur - 3);
            curContainer.find('.prev').toggleClass('prev-disable', cur === 0);
            curContainer.find('.next').toggleClass('next-disable', cur >= length - 3);

            curContainer.data('curInx', cur);
            curContents.animate({
                left : ((type === 'next') ? "-=" : "+=" ) + 3*130
            }, 500);

        }


    };

    var domEventsConf = {
        'click .select' : domEvents.selectSingleItem,
        'click .selectAll' : domEvents.selectAll,
        'click #deleteSelected' : domEvents.deleteSelected,
        'click #deleteCurItem' : domEvents.deleteCurItem,
        'click .page-btn' : domEvents.goToPage,
        'click .modify-depriced-reminder-email' : domEvents.modifyEmail,
        'click .cancel-subscription' : domEvents.cancelSubscribtion,
        'click .cancel-bundle-subscription' : domEvents.cancelBundledSubcribtion,

        'click .items-recmds .prev' : domEvents.slideControl,
        'click .items-recmds .next' : domEvents.slideControl,

        'click .go-top' : function () {
            $(document).scrollTop(0);
        },

        'click .retry' : function () {
            msg.fire('tryLoadPrevReq');
        }
    };

    _eventsBinder(domEventsConf, document);

    // test
    window.view = view;

});
