
'use strict';

const Service = require('egg').Service;
const _ = require('lodash');
const moment = require('moment');
const ConfigType = {
    1: 'new_house',
    2: 'rental_house',
    4: 'abroad_house',
}

class FootPrintService extends Service {

    /**
     * 添加足迹
     * @param {object} inputParams {id: XX, type: XX, remark: XX}
     */
    async addFootPrint(inputParams) {

        const { ctx } = this;
        const user_id = ctx.userId;
        const app_user_id = ctx.appUserId;
        if (!user_id || !app_user_id) {
            return false;
        }

        const data = {
            user_id: user_id,
            app_user_id: app_user_id,
            app_id: ctx.appId,
            app_type_id: ctx.appTypeId,
            house_style: inputParams.type,
            connect_id: inputParams.id,
            state: 1,
            remark: inputParams.remark || '',
        }
        let ret = await ctx.realestateModel.FootPrint.create(data);
        return { id: ret.id };
    }


    /**
     * 获取用户足迹列表  保留最近6个月的记录，条数不超过50条
     * @param {object} condition 
     */
    async getFootPrintList() {

        const { ctx } = this;
        const user_id = ctx.userId;
        const app_type_id = ctx.appTypeId;

        if (!user_id || !app_type_id) {
            return {
                results: [],
                count: 0
            };
        }
        let endDate = moment().subtract(6, 'months').format('YYYY-MM-DD HH:mm:ss');
        const filter = {
            page: 1,
            limit: 50,
            where: {
                user_id: user_id,
                state: 1,
                created_at: { $gt: endDate },
            },
            order: [['id', 'desc']]
        };
        const foot_prints_rows = await ctx.realestateModel.FootPrint.list(filter);
        const foot_prints = foot_prints_rows.rows;
        const p_houses = [];
        for (let i in foot_prints) {
            let foot_print = foot_prints[i];
            if (foot_print.house_style === 1) {//获取房源信息
                p_houses[i] = ctx.realestateModel.NewHouse.one({ attributes: ['id', 'name', 'status', 'valid'], where: { id: foot_print.connect_id } });
            } else if (foot_print.house_style === 2) {
                p_houses[i] = ctx.realestateModel.RentalHouse.one({ attributes: ['id', 'name', 'status', 'valid'], where: { id: foot_print.connect_id } });
            } else if (foot_print.house_style === 4) {
                p_houses[i] = ctx.realestateModel.AbroadHouse.findOne({ attributes: ['id', 'name', 'url', 'status', 'valid'], where: { id: foot_print.connect_id } });
            }

        }
        const houses = await Promise.all(p_houses).then(result => {//等待所有异步内容获取完成
            return result;
        }).catch(error => {
            ctx.failed(error);
        });

        const now_time = moment(new Date()).format('X');
        //处理足迹数据
        const foot_print_records = [];
        for (let j in houses) {
            if (houses[j] === null || houses[j].status === 'offline' || Number(houses[j].valid) === 0) {
                continue;
            }
            const house = houses[j];
            const foot_print = foot_prints[j];
            const type = ConfigType[foot_print.house_style];
            const create_time = moment(foot_print.created_at).format('X');
            let time = moment(foot_print.created_at).format('YYYY-MM-DD');
            const du_time = now_time - create_time;
            if (du_time < 86400) {
                const hours = parseInt(du_time / 3600);
                const mins = parseInt(du_time / 60);
                time = hours ? `${hours}小时前` : (mins > 5 ? `${mins}分钟前` : '刚刚');
            }

            foot_print_records.push({
                id: foot_print.id,
                house_id: house.id,
                name: house.name,
                time: time,
                type: type,
                url: type === 'abroad_house' ? house.url : '',
            });
        }

        return { results: foot_print_records, count: foot_print_records.length };
    }


    /**
     * 我的-获取用户足迹个数
     */
    async getFootPrintCount() {
        const { ctx } = this;
        if (!ctx.userId) {
            return { count: 0 };
        }
        let endDate = moment().subtract(6, 'months').format('YYYY-MM-DD HH:mm:ss');
        const filter = {
            limit: 50,
            attributes: ['connect_id', 'house_style'],
            where: {
                state: 1,
                user_id: ctx.userId,
                created_at: { $gt: endDate },
            },
            order: [['created_at', 'desc']]
        }
        const list = await ctx.realestateModel.FootPrint.findAll(filter);
        let count = 0;
        if (list.length > 0) {
            let newIds = [];
            let rentalIds = [];
            let abroadIds = [];
            for (let i in list) {
                if (Number(list[i].house_style) === 1) {
                    newIds.push(list[i].connect_id);
                }
                if (Number(list[i].house_style) === 2) {
                    rentalIds.push(list[i].connect_id);
                }
                if (Number(list[i].house_style) === 4) {
                    abroadIds.push(list[i].connect_id);
                }
            }
            let newTaskFilter = {
                attributes: ['id'], where: { status: 'online', valid: 1, id: { $in: newIds } }
            }
            let rentalTaskFilter = {
                attributes: ['id'], where: { status: 'online', valid: 1, id: { $in: rentalIds } }
            }
            let abroadTaskFilter = {
                attributes: ['id'], where: { status: 'online', valid: 1, id: { $in: abroadIds } }
            }
            let taskList = [
                ctx.realestateModel.NewHouse.findAll(newTaskFilter),
                ctx.realestateModel.RentalHouse.findAll(rentalTaskFilter),
                ctx.realestateModel.AbroadHouse.findAll(abroadTaskFilter),
            ];

            const retList = await Promise.all(taskList).then(result => {
                return result;
            }).catch(error => {
                ctx.failed(error);
            });

            let validNewIds = _.map(retList[0], 'id');
            let validRentalIds = _.map(retList[1], 'id');
            let validAbroadIds = _.map(retList[2], 'id');
            for (let i in list) {
                if (Number(list[i].house_style) === 1 && validNewIds.includes(Number(list[i].connect_id))) {
                    count++;
                }
                if (Number(list[i].house_style) === 2 && validRentalIds.includes(Number(list[i].connect_id))) {
                    count++;
                }
                if (Number(list[i].house_style) === 4 && validAbroadIds.includes(Number(list[i].connect_id))) {
                    count++;
                }
            }
        }
        let ret = {
            count: count
        };
        return ret;
    }


}

module.exports = FootPrintService;
