address.js 2.53 KB
/**
 * address model
 * @author: yyq<yanqing.yang@yoho.cn>
 * @date: 2016/09/27
 */
'use strict';

const _ = require('lodash');
const pinyin = require('pinyin');

const crypto = global.yoho.crypto;

const addressApi = require('../models/address-api');

const worldSort = 'abcdefghijklmnopqrstuvwxyz';

const getAreaListData = (id) => {
    return addressApi.getAreaListAsync(id).then(result => {
        let list = _.get(result, 'data', []);

        if (id * 1 === 0 && list.length) {
            _.forEach(list, value => {
                value.initial = _.get(pinyin(value.caption, {
                    style: pinyin.STYLE_FIRST_LETTER
                }), '[0][0]', 'w');
                value.pySort = _.indexOf(worldSort, value.initial);
            });
            result.data = list;
        }

        return result;
    });
};

const getAddressListData = (uid) => {
    return addressApi.getAddressListAsync(uid).then(result => {
        if (result.code !== 200) {
            return result;
        }

        let d = result.data;

        _.forEach(d, dd => {
            if (dd.is_default === 'Y') {
                dd.default = true;
            }

            // 地址加密
            let id = dd.address_id;

            dd.id = crypto.encryption('', `${id}`);
            delete dd.address_id;
            delete dd.uid; // 删除uid,用户数据保密
        });

        return result;
    });
};

const delAddressById = (uid, id) => {
    id = crypto.decrypt('', `${id}`);

    return addressApi.delAddressAsync(uid, id);
};

const saveAddressData = (uid, info) => {
    if (info.id) {
        let id = crypto.decrypt('', `${info.id}`);

        return addressApi.updateAddressAsync(uid, id, info.consignee, info.areaCode, info.address,
            info.mobile, info.phone, info.zipCode, info.email);
    } else {
        return addressApi.addAddressAsync(uid, info.consignee, info.areaCode, info.address, info.mobile,
            info.phone, info.zipCode, info.email).then(result => {
                if (result.code === 200) {
                    let d = result.data;

                    d.id = crypto.encryption('', `${d.address_id}`);
                    delete d.address_id;
                    delete d.uid;
                }

                return result;
            });
    }

};

const setDefaultAddress = (uid, id) => {
    id = crypto.decrypt('', `${id}`);

    return addressApi.setDefaultAddressAsync(uid, id);
};

module.exports = {
    getAreaListData,
    getAddressListData,
    delAddressById,
    saveAddressData,
    setDefaultAddress
};