index.js 2.87 KB
import {
    SET_ENV,
    SET_TITLE,
    ROUTE_CHANGE,
    INIT_ROUTE_CHANGE,
    PAGE_INIT_VISIBLE,
    REPORT_YAS,
    YOHO_PAGE_VISIBLE,
} from './types';
import cookie from 'yoho-cookie';
import _ from 'lodash/core';

export function createYoho() {
    return {
        state: {
            title: '',
            env: {
                isApp: true,
                isiOS: false,
                isAndroid: false,
                isYohoBuy: false,
                channel: 'men',
                fs: true
            },
            visible: true,
            pageVisible: false,
            history: [],
            direction: 'forword'
        },
        mutations: {
            [SET_ENV](state, params) {
                Object.assign(state.env, params);
            },
            [SET_TITLE](state, params) {
                state.title = params.title;
            },
            [INIT_ROUTE_CHANGE](state, {routes}) {
                state.history = routes;
            },
            [ROUTE_CHANGE](state, {name, fullPath}) {
                let routeIndex;

                state.env.fs = false;
                _.each(state.history, (h, index) => {
                    if (h.name === name) {
                        routeIndex = index;
                        return false;
                    }
                });

                if (routeIndex >= 0) {
                    state.history = state.history.slice(0, routeIndex + 1);
                    state.direction = 'back';
                } else {
                    state.history.push({
                        name,
                        fullPath
                    });
                    state.direction = 'forword';
                }
            },
            [PAGE_INIT_VISIBLE](state, {visible}) {
                state.visible = visible;
            },
            [YOHO_PAGE_VISIBLE](state, {visible}) {
                state.pageVisible = visible;
            }
        },
        actions: {
            [REPORT_YAS]({state, dispatch}, {params: {appop, param}, asyncindx = false, repeat = true}) {
                if (window._yas && window._yas.sendCustomInfo) {
                    param = param || {};

                    if (!param.C_ID) {
                        const channel = {
                            men: 1,
                            women: 2
                        }[cookie.get('_Channel') || 'men'];

                        param.C_ID = channel;
                    }
                    window._yas.sendCustomInfo({
                        appop,
                        param: param ? JSON.stringify(param) : '{}'
                    }, asyncindx);
                } else if (repeat && state.env.isiOS) {
                    setTimeout(() => {
                        dispatch(REPORT_YAS, {params: {appop, param}, asyncindx: false, repeat: false});
                    }, 1000);
                }
            }
        }
    };
}