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

const _ = require('lodash');

const pinyin = require('../models/province-pinyin');
const AddressApi = require('../models/address-api');

const worldSort = 'abcdefghijklmnopqrstuvwxyz';

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

    getAreaListData(id) {
        return new AddressApi(this.ctx).getAreaListAsync(id).then(result => {
            let list = _.get(result, 'data', []);

            if (id * 1 === 0 && list.length) {
                _.forEach(list, value => {
                    value.initial = pinyin[value.caption] || 'z';
                    value.pySort = _.indexOf(worldSort, value.initial);
                });
                result.data = list;
            }
            return result;
        });
    }

    getAddressListData(uid) {
        return new AddressApi(this.ctx).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;
                }

                dd.id = dd.address_id;

                delete dd.address_id;
                delete dd.uid; // 删除uid,用户数据保密
            });

            return result;
        });
    }

    delAddressById(uid, id) {
        return new AddressApi(this.ctx).delAddressAsync(uid, id);
    }

    saveAddressData(uid, info) {
        let addressApiModel = new AddressApi(this.ctx);

        if (info.id) {
            let id = info.id;

            return addressApiModel.updateAddressAsync(uid, id, info.consignee, info.areaCode, info.address,
                info.mobile, info.phone, info.zipCode, info.email);
        } else {
            return addressApiModel.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 = d.address_id;
                    delete d.address_id;
                    delete d.uid;
                }

                return result;
            });
        }

    }

    setDefaultAddress(uid, id) {
        return new AddressApi(this.ctx).setDefaultAddressAsync(uid, id);
    }
};