students.js 9.15 KB
/**
 * 学生营销数据处理
 * @date: 2016-08-06 14:24:04
 * @author: name<emial@yoho.cn>
 */

'use strict';
const utils = '../../../utils';
const queryString = require('querystring');
const Promise = require('bluebird');
const _ = require('lodash');

const StudentsApiModel = require('./students-api');
const SearchApiModel = require('./search-api');

const stuHandler = require('./students-handler');
const helpers = global.yoho.helpers;
const crypto = global.yoho.crypto;
const HeaderModel = require('../../../doraemon/models/header');

const productProcess = require(`${utils}/product-process`);
const searchHandler = require('./search-handler');
const needParams = ['query', 'msort', 'misort', 'gender', 'shelveTime'];

// 学生营销资源码
const studentsCode = '989396a17443bf61e3e269702e51ef04'; // h5 a83b7d55324fb65f96c1f85a3387ebd8
// const studentsCode = 'a83b7d55324fb65f96c1f85a3387ebd8'; // h5 a83b7d55324fb65f96c1f85a3387ebd8

/**
 * 获取学生营销页面数据
 * @params channel Object 频道
 * @return name returnType 返回值描述
 */
function getStudentsData(channel, req) {
    let apiMethod = [
        this.headerModel.requestHeaderData(channel),

        // 资源位数据
        this.get({
            url: 'operations/api/v5/resource/get',
            data: {
                content_code: studentsCode
            },
            api: global.yoho.ServiceAPI
        }),

        // 认证总数
        this.studentsApi.getVerifiedTotal(),

        // 商品数据
        this.studentsApi.getStuProducts()
    ];

    let params = {};

    if (req.user.uid && req.query.collegeName && req.query.educationDegree &&
        req.query.enrollmentYear && req.query.sign) {
        params = {
            uid: req.user.uid,
            provName: req.query.provName,
            birthDay: req.query.birthDay,
            sex: req.query.sex,
            collegeName: req.query.collegeName,
            educationDegree: req.query.educationDegree,
            enrollmentYear: req.query.enrollmentYear
        };
        apiMethod.push(
            this.studentsApi.verifyStudent(req.user.uid, req.query.collegeName,
                req.query.educationDegree, req.query.enrollmentYear)
        );
    }
    return Promise.all(apiMethod).then(result => {
        let responseData = {
            module: 'product',
            page: 'students',
            realData: {
                sortItem: [
                    {title: '学生权益介绍', href: 'stu-rights'},
                    {title: '我要验证身份', href: 'stu-identity'},
                    {title: '学生热门单品', href: 'stu-good'},
                    {title: '更多活动推荐', href: 'stu-activity'}
                ],
                identityObj: {
                    identityItem: {
                        stuNum: []
                    }
                }
            },

            footerTop: true
        };

        // 头部数据
        Object.assign(responseData, result[0]);

        // 资源位数据
        if (result[1].code === 200) {
            Object.assign(responseData.realData, stuHandler.studentResource(result[1].data));
        }

        if (result[2].code === 200) {
            responseData.realData.identityObj.identityItem.stuNum = stuHandler.studentsNum(result[2].data);
        }

        if (result[3].code === 200) {
            let proList = result[3].data.product_list,
                proIdList = [];

            for (let i = 0; i < proList.length; i++) {
                proIdList.push(proList[i].product_id);
            }
            Object.assign(responseData.realData, {proObj: {}});
            Object.assign(responseData.realData.proObj, {proIds: proIdList.join(',')});
            Object.assign(responseData.realData.proObj, {proItem: stuHandler.stuProducts(proList)});
        }

        if (result[4]) {
            Object.assign(responseData.realData.identityObj, {verifyRusult: stuHandler.stuVerify(result[4], params)});
        }

        return responseData;
    });
}

/**
 * 身份验证
 * @params areaCode int 地区码
 * @return Object 接口数据
 */
function verifyIdentity(uid, params) {
    let pageUrl = helpers.urlFormat('/product/students?') +
        queryString.stringify({
            provName: params.provName,
            birthDay: params.certNo.substr(6, 8),
            sex: params.certNo.substr(16, 1),
            collegeName: params.collegeName,
            educationDegree: params.educationDegree,
            enrollmentYear: params.enrollmentYear
        }) + '&';

    return this.studentsApi.verifyIdentity(uid, params.certNo, params.name, pageUrl);
}

/**
 * 学生验证
 * @params areaCode int 地区码
 * @return Object 接口数据
 */
function verifyStudents(params) {
    return this.studentsApi
        .verifyStudent(params.uid, params.collegeName, params.educationDegree, params.enrollmentYear);
}

/**
 * 获取优惠券领取状态
 * @params
 * @return
 */
function userAcquireStatus(uid, couponIds) {
    let ids = couponIds.map(coupon => crypto.decrypt(null, coupon)).join(',');

    return this.studentsApi.userAcquireStatus(uid, ids).then(result => {
        if (result.code === 200) {
            _.forEach(result.data, (value) => {
                value.couponId = crypto.encryption(null, value.couponId + '');
            });
        }
        return result;
    });
}

/**
 * 获取学生返币专享商品列表数据
 */
function getStudentsList(params, channel) {
    let standard = [];

    _.forEach(params, (value, key) => {
        let s = _.split(key, 'parameter_', 2);

        if (s.length > 1) {
            standard.push(`${s[1]}_${value}`);
            _.unset(params, `${key}`);
        }
    });

    if (standard.length) {
        params.standard = standard.join(',');
    }

    let searchParams = searchHandler.getSearchParams(params);

    // 调用接口
    let apiMethod = [
        this.headerModel.requestHeaderData(channel),
        this.searchApi.getSortList(Object.assign({}, {msort: '', misort: ''})),
        this.studentsApi.getStudentsProduct(searchParams)
    ];

    return Promise.all(apiMethod).then(result => {
        let finalResult = {
            module: 'product',
            page: 'list',
            headerData: Object.assign(result[0].headerData, {
                header: true
            }),
            list: {
                leftContent: {}
            }
        };

        // 获取左侧类目数据
        if (result[1].code === 200) {
            let dps = {};

            _.forEach(needParams, (value) => {
                if (params[value]) {
                    dps[value] = params[value];
                }
            });

            finalResult.list = Object.assign(
                searchHandler.handlePathNavData(result[1].data, params, 'sort', channel), {
                    leftContent: searchHandler.handleSortData(result[1].data, dps, params)
                });
        }

        // 获取商品数据和顶部筛选条件
        if (result[2].code === 200) {
            // 删掉student_price,不让页面显示
            _.forEach(result[2].data.product_list, goods => {
                delete goods.student_price;
            });
            Object.assign(finalResult.list, {
                filters: searchHandler.handleFilterDataAll(result[2].data, params),
                opts: searchHandler.handleOptsData(params, result[2].data.total, result[2].data.filter),
                totalCount: result[2].data.total,
                footPager: searchHandler.handlePagerData(result[2].data.total, params),
                goods: productProcess.processProductList(result[2].data.product_list,
                    Object.assign({showDiscount: false}, params, {
                        from: {type: 'list', params: params}
                    })),
                hasNextPage: searchHandler.handleNextPage(params, result[2].data.total),

                // 最近浏览记录
                latestWalk: 6
            });
        }

        finalResult.criteo = {skn: searchHandler.getCriteo(_.get(finalResult.list, 'goods'))};
        return Object.assign({}, finalResult);
    });
}

module.exports = class extends global.yoho.BaseModel {
    constructor(ctx) {
        super(ctx);

        this.studentsApi = new StudentsApiModel(ctx);
        this.searchApi = new SearchApiModel(ctx);
        this.headerModel = new HeaderModel(ctx);

        /**
         * 获取学校地区数据
         * @return Object 接口数据
         */
        this.getSchoolArea = this.studentsApi.getArea.bind(this.studentsApi);

        /**
         * 根据地区码查询学校列表
         * @params areaCode int 地区码
         * @return Object 接口数据
         */
        this.getSchoolList = this.studentsApi.getSchool.bind(this.studentsApi);

        /**
         * 学历层次
         * @params areaCode int 地区码
         * @return Object 接口数据
         */
        this.getEduLevel = this.studentsApi.getEduLevelList.bind(this.studentsApi);

        this.getStudentsData = getStudentsData.bind(this);

        this.verifyIdentity = verifyIdentity.bind(this);

        this.verifyStudents = verifyStudents.bind(this);

        this.userAcquireStatus = userAcquireStatus.bind(this);


        this.getStudentsList = getStudentsList.bind(this);

    }
};