
'use strict';

const Service = require('egg').Service;
class MineService extends Service {

    /**
     * 获取我的信息
     */
    async getMineInfo() {
        const { ctx, service } = this;
        let ret = {
            login: false,
            user: {
                nickname: '',
                avatar: '',
                phone: ''
            },
            classification: {
                foot_print: {
                    count: 0,
                    name: '浏览足迹'
                },
                collection: {
                    count: 0,
                    name: '关注的房产'
                },
                order: {
                    count: 0,
                    name: '预约记录'
                },
            }
        }
        if (!ctx.userId) {
            return ret;
        }
        let appUserInfo = await this.getAppUserInfo();
        ctx.logger.info('appUserInfo:' + JSON.stringify(appUserInfo));
        let footPrintList = await service.house.footPrint.getFootPrintCount();
        let collectionList = await service.house.collection.getCollectionCount();
        let orderList = await service.house.order.getOrderCount();

        let phone = appUserInfo.user.phone || '';
        if (phone.length > 0) {
            phone = phone.substring(0, 3) + '****' + phone.substring(7, 11);
        }
        ret.login = true;
        ret.user.nickname = appUserInfo.nickname || '';
        ret.user.avatar = appUserInfo.avatar || '';
        ret.user.phone = phone;
        ret.classification.foot_print.count = footPrintList.count;
        ret.classification.collection.count = collectionList.count;
        ret.classification.order.count = orderList.count;

        return ret;

    }

    /**
     * 获取用户信息
     */
    async getAppUserInfo() {
        const { ctx } = this;
        let appUserId = ctx.appUserId;
        const result = await ctx.helper.send_request(this.config.USER_CENTER_API_URI + '/v1/appusers/' + appUserId, {}, { method: 'GET', dataType: 'json' });
        const ret = result.status === 200 ? result.data : {};
        if (ret.avatar && ret.avatar.indexOf('http') === -1) {
            ret.avatar = this.config.CDN_BASE_URL + ret.avatar;
        }
        if (ret.avatar && ret.avatar !== null) {
            ret.avatar = ret.avatar.replace(/^(?=^.{3,255}$)(http(s)?:\/\/)?(www\.)?[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+(:\d+)*(\/\w+\.\w+)*/i, 'https://r.51gjj.com');
        }
        return ret;
    }



}

module.exports = MineService;
