
'use strict';

const Service = require('egg').Service;
const moment = require('moment');

class CollectionService extends Service {

    /**
     * 添加关注
     * @param {object} inputParams 
     */
    async addCollection(inputParams) {
        const { ctx } = this;
        if (!ctx.appUserId || !ctx.userId) {
            //如果没有登录就不做处理
            return false;
        }

        let filter = {
            where: {
                state: 1,
                house_style: inputParams.type,
                connect_id: inputParams.id,
                user_id: ctx.userId,
            }
        }
        let collectionHistory = await ctx.realestateModel.Collection.all(filter);
        if (collectionHistory.length > 0) {
            ctx.failed('已经关注过啦');
        }
        let data = {
            user_id: ctx.userId,
            app_user_id: ctx.appUserId,
            app_id: ctx.appId,
            app_type_id: ctx.appTypeId,
            house_style: inputParams.type,
            connect_id: inputParams.id,
            state: 1,
        }
        let retId = await ctx.realestateModel.Collection.add(data);
        return { id: retId };
    }

    /**
     * 取消关注
     * @param {object} inputParams 
     */
    async unCollection(inputParams) {
        const { ctx } = this;
        let ret = { status: true };
        if (!ctx.appUserId || !ctx.deviceId || !ctx.deviceLoginId || !ctx.userId) {
            //如果没有登录就不做处理
            return ret;
        }
        let filter = {
            where: {
                state: 1,
                house_style: inputParams.type,
                connect_id: inputParams.id,
                user_id: ctx.userId,
            }
        }
        let collectionHistory = await ctx.realestateModel.Collection.all(filter);
        if (collectionHistory.length > 0) {
            let filter = {
                params: { state: 0 },
                where: { connect_id: inputParams.id }
            }
            await ctx.realestateModel.Collection.edit(filter);
        }
        return ret;
    }

    /**
     * 获取用户关注信息
     * @param {object} inputParams 
     */
    async getCollection(inputParams) {
        const { ctx } = this;
        if (!inputParams.hasOwnProperty('type')) {
            ctx.failed("empty house type");
        }
        if (!inputParams.hasOwnProperty('id')) {
            ctx.failed("empty house id");
        }
        if (!ctx.userId) {
            return [];
        }
        let filter = {
            where: {
                state: 1,
                house_style: inputParams.type,
                connect_id: inputParams.id,
                user_id: ctx.userId,
            }
        }
        let ret = await ctx.realestateModel.Collection.all(filter);
        return ret;
    }


    /**
     * 获取关注列表  保留最近6个月的记录，条数不超过50条
     * @param {object} condition 
     */
    async getCollectionList() {
        const { ctx } = this;
        let endDate = moment().subtract(6, 'months').format('YYYY-MM-DD HH:mm:ss');
        let filter = {
            page: 1,
            limit: 50,
            where: {
                state: 1,
                user_id: ctx.userId,
                created_at: { $gt: endDate },
            },
            order: [['id', 'desc']]
        }
        let list = [];
        let collectionList = await ctx.realestateModel.Collection.all(filter);
        if (collectionList.length > 0) {
            //整理所有收藏
            let taskList = [];
            for (let i in collectionList) {
                if (collectionList[i].house_style === 1) {//1新房2租房 后续根据情况添加
                    taskList[i] = ctx.realestateModel.NewHouse.one({ where: { id: collectionList[i].connect_id } });
                } else {
                    taskList[i] = ctx.realestateModel.RentalHouse.one({ where: { id: collectionList[i].connect_id } });
                }
            }
            let retList = await Promise.all(taskList).then(result => {
                return result;
            }).catch(error => {
                ctx.failed(error);
            });
            //数据整理
            for (let j in retList) {
                if (retList[j].status === 'offline' || Number(retList[j].valid) === 0) {
                    continue;
                }
                let type = collectionList[j].house_style;
                let tmp = {
                    id: retList[j].id,
                    name: retList[j].name,
                    address: retList[j].address,
                    tags: retList[j].tags ? eval(retList[j].tags) : [],
                    image: retList[j].image,
                    area: type === 1 ? Number(retList[j].residential_house_area) : '',
                    price: type === 1 ? (['', 0].includes(Number(retList[j].reference_avg_price)) ? '--' : Number(retList[j].reference_avg_price)) : Number(retList[j].price),
                    type: type === 1 ? 'new_house' : 'rental_house',
                    corner: type === 1 ? retList[j].corner : '',
                };
                list.push(tmp);
            }
        }
        let ret = {
            results: list,
            count: list.length
        };
        return ret;
    }


    /**
     * 给我的页面使用 只需要count
     */
    async getCollectionCount() {
        const { ctx } = this;
        if (!ctx.userId) {
            return { count: 0 };
        }
        let endDate = moment().subtract(6, 'months').format('YYYY-MM-DD HH:mm:ss');
        let filter = {
            page: 1,
            limit: 50,
            attributes: ['connect_id', 'house_style'],
            where: {
                state: 1,
                user_id: ctx.userId,
                created_at: { $gt: endDate },
            },
            order: [['id', 'desc']]
        }
        let list = await ctx.realestateModel.Collection.findAll(filter);
        let count = 0;
        if (list.length > 0) {
            let newHouseId = [];
            let rentalHouseId = [];
            for (let i in list) {
                if (Number(list[i].house_style) === 1) {
                    newHouseId.push(list[i].connect_id);
                }
                if (Number(list[i].house_style) === 2) {
                    rentalHouseId.push(list[i].connect_id);
                }
            }
            let newHousefilter = {
                where: {
                    status: 'online',
                    valid: 1,
                    id: { $in: newHouseId },
                },
            }
            let newHouseCountTask = ctx.realestateModel.NewHouse.count(newHousefilter);
            let rentalHousefilter = {
                where: {
                    status: 'online',
                    valid: 1,
                    id: { $in: rentalHouseId },
                },
            }
            let rentalHouseCountTask = ctx.realestateModel.RentalHouse.count(rentalHousefilter);
            const retList = await Promise.all([newHouseCountTask, rentalHouseCountTask]).then(result => {
                return result;
            }).catch(error => {
                ctx.failed(error);
            });
            count = Number(retList[0]) + Number(retList[1]);
        }
        let ret = {
            count: count
        };
        return ret;
    }

}

module.exports = CollectionService;
