view.js 10.4 KB
const tip = require('plugin/tip');

require('common');

import {EventEmitter, api} from './store';
import appBridge from 'yoho-app';


const LeaveMSGView = function(elem) {
    this.$elem = $(elem);
    this.$input = this.$elem.find('.leave-text');
    this.$doc = $(document);
    this.bindEvents();
    this.isSending = false;
};

LeaveMSGView.prototype = $.extend({}, EventEmitter.prototype, {
     /**
     * 绑定事件
     * 1. 提交按钮事件
     **/
    bindEvents() {
        let self = this;

        this.$elem
            .on('click', '.chat-page-back', function(event) {
                event.stopPropagation();
                self.toggleHide(true);
            })
            .on('click.LeavseMSG.submit', '.leave-submit', function() {
                event.stopPropagation();
                self.submit();
            });

        this.on('show.LeaveMSGView', $.proxy(this.toggleHide, this, false));
    },

    /**
    * method: show/hide 留言
    * @param boolean show;
    */
    toggleHide(willHide) {
        this.$elem.toggleClass('chat-page-hide', willHide);

        return false;
    },

    /**
     * 提交留言的hanlder
    */
    submit() {
        if (this.isSending) {
            tip.show('正在发送..');
            return;
        }

        this.isSending = true;

        let self = this;
        let content = $.trim(this.$input.val());

        if (!content) {
            return;
        }

        api.leaveMsg(content)
            .done(function(res) {
                if (res && res.code === 401) {
                    window.location.href = '//m.yohobuy.com/signin.html?refer=' + window.location.href;
                }
                self.trigger('save.LeaveMSGView', '留言成功');
                self.$input.val('');
            })
            .fail(function() {
                self.trigger('save.LeaveMSGView', '留言失败');
            })
            .always(function() {
                self.isSending = false;
            });

        self.toggleHide(true);
    }
});

LeaveMSGView.prototype.constructer = LeaveMSGView;


/*
    评价view
*/
const RatingView = function(elem, cmEntity) {
    this.elem = $(elem);
    this.$ranks = this.elem.find('.stars i');
    this.$label = this.elem.find('.rank');
    this.$more = this.elem.find('.more-comment');
    this.cmEntity = cmEntity;
    this.rank = 3;
    this.bindEvents();
    this.isSending = false;
    this.reasonsRendered = false;
};

RatingView.prototype = $.extend({}, EventEmitter.prototype, {

    bindEvents() {
        const self = this;

        this.elem
            .on('click.RatingView.rating', '.stars i', function(event) {
                event.stopPropagation();

                let starVal = $(this).index();

                self.rating(starVal);
            })
            .on('click.RatingView.close', '.close', $.proxy(this.toggle, this, false))
            .on('moreComment.toggle', '.more-comment', function(event, starVal) {
                let $this = $(this);
                let visible = $this.is(':visible');

                if (starVal < 3 && visible) {
                    return;
                }

                $this.find('.words-to-say').val('');
                $this.find('.cause span').removeClass('select');

                if (starVal < 3) {
                    return self.renderReasons();
                }

                $this.hide();
            })
            .on('click.CauseItem.SelectToggle', '.cause span', function() {
                let $this = $(this);

                $this.toggleClass('select');
            });
    },

    renderReasons() {
        const self = this;
        const YOHO_CS = 2; // 1:企业端 2:YOHO在线客服 3:BLK在线客服 4:MARS在线客服 5:机器人

        if (self.reasonsRendered) {
            self.$more.show();
            return;
        }

        // 评价原因渲染
        api.queryReasons({
            type: YOHO_CS
        })
        .done(res => {
            if (res && res.code === 401) {
                window.location.href = '//m.yohobuy.com/signin.html?refer=' + window.location.href;
            }

            if (res && res.code === 200) {
                let $html;
                let cause = [];

                res.data.forEach((item) => {
                    cause.push(`<span data-id="${item.id}">${item.content}</span>`);
                });

                $html = cause.join('');
                self.$more.find('.cause').append($html);
                self.reasonsRendered = true;
                self.$more.show();
                return;
            }
        })
        .fail(()=> {
            tip.show('拉取评价原因失败');
        });
    },

    rating(starVal) {
        const rankMap = {
            0: '非常不满意',
            1: '不满意',
            2: '一般',
            3: '满意',
            4: '非常满意',
        };

        this.rank = starVal;
        this.rankText = rankMap[starVal] || rankMap[3];
        this.$label.text(this.rankText);

        this.$ranks.removeClass('rated');
        this.$ranks.toggleClass(index => {
            return index <= starVal ? 'rated' : null;
        });

        // added for customer service v1.2 optimization
        this.$more.trigger('moreComment.toggle', starVal);
    },

    post(data) {
        var params;

        if (this.isSending) {
            tip.show('正在发送..');
            return;
        }
        this.isSending = true;

        const self = this,
            elem = this.elem;

        params = {
            stars: ++this.rank,
            promoter: 1,
            reasonIds: '',
            reasonMsg: elem.find('.words-to-say').val().trim(),
        };

        let temp = [];
        let $select = self.$more.find('.cause span.select');

        [].forEach.call($select, (item) => {
            temp.push($(item).data('id'));
        });
        params.reasonIds = temp.join(':');

        Object.assign(params, data);

        api.saveEvalute(params)
            .done(res => {
                if (res && res.code === 401) {
                    window.location.href = '//m.yohobuy.com/signin.html?refer=' + window.location.href;
                }

                if (res && res.code === 200) {
                    elem.hide();
                    elem.trigger('rating-success', [self.rankText]);

                    return;
                }

                tip.show(res.message);
            })
            .fail(()=> {
                tip.show('评价失败');
            })
            .always(() => {
                self.isSending = false;
            });
    },

    toggle(willShow) {
        if (willShow === this.elem.is(':visible')) {
            return;
        }
        this.elem.toggle(willShow);
        this.rating(4);

        return false;
    }
});

RatingView.prototype.constructer = RatingView;

const OrderListView = function(elem) {
    this.$elem = $(elem);
    this.orderListT = require('service/chat/orders.hbs');

    this.$localOrders = this.$elem.find('[data-tab=local]');
    this.$globalOrders = this.$elem.find('[data-tab=global]');

    // 分页数据
    this.state = {
        global: {
            curCount: 0,
            totalCount: null
        },
        order: {
            curCount: 0,
            totalCount: null
        }
    };

    this.bindEvents();

    // this.fetchOrders();
};

OrderListView.prototype = $.extend({}, EventEmitter.prototype, {
    bindEvents: function() {
        const self = this;

        this.$elem
            .on('click.OrderListView.back', '.chat-page-back', function(event) {
                event.stopPropagation();
                self.toggleHide(true);
            })
            .on('click.OrderListView.select', '[data-action=select]', function(event) {
                event.stopPropagation();
                self.selectOrder($(event.target));
            });

        // 被通知显示,执行显示
        this.on('show.OderListView', (event, type) => {
            self.toggleHide(false, type);
        });
    },

    /**
     *  method: 选择订单,然后关闭
     */
    selectOrder: function($btn) {
        let $order = $btn.closest('.order-page');

        // 订单数据
        let data = {
            imgSrc: $order.find('.thumb').attr('src'),
            orderCode: $order.find('[data-id]').attr('data-id'),
            cost: $order.find('.sum-cost').text(),
            createTime: $order.find('.js-create-time').val(),
            orderStatus: $order.find('.order-status').text()
        };

        // 通知chat,订单列表已选择订单
        this.trigger('selectOrder.OrderListView', [data]);

        // 关闭
        this.toggleHide(true);
    },

    /**
    * method: show/hide 订单列表
    * @param boolean willHide;
    * @return this
    */
    toggleHide: function(willHide, type) {
        this.$elem.toggleClass('chat-page-hide', willHide);

        if (!willHide) {
            let orderState = this.state[type];
            let {totalCount} = orderState;

            totalCount === null && this.fetchOrderByType(type, orderState);

            if (type === 'global') {
                this.$globalOrders.show();
                this.$localOrders.hide();
            } else if (type === 'order') {
                this.$globalOrders.hide();
                this.$localOrders.show();
            }
        } else {
            this.$globalOrders.hide();
            this.$localOrders.hide();
        }



        return this;
    },

    fetchOrderByType: function(type, orderState) {
        let self = this;
        let $order = type === 'global' ? this.$globalOrders : this.$localOrders;

        let {totalCount} = orderState;

        // TODO: 分页
        if (totalCount === null) { // 还未加载数据
            api.fetchOrders(type).done(
                result => {
                    if (result && result.code === 401) {
                        window.location.href = '//m.yohobuy.com/signin.html?refer=' + window.location.href;
                    }

                    let html = self.orderListT({
                        orders: result.data,
                        isApp: appBridge.isApp,
                        isGlobal: type === 'global'
                    });

                    orderState.totalCount = result.data.length;
                    orderState.curCount = result.data.length;

                    $order.append(html);
                }
            );
        }
    }
});

OrderListView.prototype.constructer = OrderListView;

export {RatingView, LeaveMSGView, OrderListView};