/*
 * @Author: Targaryen
 * @Date: 2017-04-26 17:19:19
 * @Last Modified by: Targaryen
 * @Last Modified time: 2017-05-02 14:40:52
 */
'use strict';

const lazyLoad = require('yoho-jquery-lazyload');

import {Controller} from 'js/yoho-mvc';
import {
    ListView
} from './view';
import {
    Guang
} from './model';

class IndexController extends Controller {
    constructor() {
        super();

        lazyLoad($('img.lazy'));

        this.listView = new ListView();
        this.guangModel = new Guang();

        this.page = 1;
        this.onLoading = false;

        this.listView.on('tabchange', this.tabChange.bind(this));
        this.listView.on('loadmore', this.loadMore.bind(this));
    }

    /**
     * Tab 切换
     * @param {*} e
     * @param {*} type
     */
    tabChange(e, type) {
        this.page = 1;
        this.onLoading = false;
        this.guangModel.fetchList({
            type: type,
            page: this.page
        }).then(result => {
            let $result = $(result);

            lazyLoad($result.find('img.lazy'));
            this.listView.listChange($result);
        });
    }

    /**
     * 加载更多
     */
    loadMore(e, type) {
        if (this.onLoading === false) {
            this.onLoading = true;
            this.guangModel.fetchList({
                type: type,
                page: ++this.page
            }).then(result => {
                let noResult = !result || result.length < 1 || (result.list && result.list.length < 1);

                if (noResult) {
                    this.listView.listAppend('<div class="search-divide">没有更多内容了...</div>');
                    return false;
                }

                let $result = $(result);

                lazyLoad($result.find('img.lazy'));
                this.listView.listAppend($result);

                this.onLoading = false;
            });
        }
    }
}

module.exports = IndexController;