
'use strict';

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

class PresellSearchHistoryService extends Service {

    /**
     * 添加搜索历史
     * @param {string} keyWord 
     */
    async addSearchHistory(keyWord) {
        const { ctx } = this;
        if (!ctx.appUserId || !ctx.userId) {
            //如果没有登录就不做处理
            return false;
        }
        let data = {
            user_id: ctx.userId,
            app_user_id: ctx.appUserId,
            app_id: ctx.appId,
            app_type_id: ctx.appTypeId,
            key_word: keyWord,
            state: 1,
        };
        let ret = await ctx.realestateModel.CdPresellSearchHistory.create(data);
        return { id: ret.id };
    }

    /**
     * 获取搜索历史
     * 通过输入的关键字搜索楼盘
     * 历史记录取用户最近6个月的搜索记录，去重处理，条数不超过50条
     * 排序根据搜索时间逆序排列，距离当前时间近的排在前面，重复搜索的关键词取最近一次的搜索时间进行排序
     * 如果没有搜索记录的就不显示搜索词
     */
    async getSearchHistory() {
        const { ctx } = this;
        let ret = {
            list: [],
            count: 0
        };
        if (!ctx.appUserId || !ctx.userId) {
            //如果没有登录就返回
            return ret;
        }
        //用户的搜索记录
        let endDate = moment().subtract(6, 'months').format('YYYY-MM-DD HH:mm:ss');
        let filter = {
            limit: 50,
            attributes: ['key_word'],
            where: {
                state: 1,
                user_id: ctx.userId,
                created_at: { $gt: endDate }
            },
            order: [['created_at', 'desc']],
        }
        let searchHistoryList = await ctx.realestateModel.CdPresellSearchHistory.findAll(filter);
        let list = _.uniq(_.map(searchHistoryList, 'key_word'));
        ret.list = list;
        ret.count = list.length;
        return ret;
    }


    /**
     * 用户点击清除搜索记录
     */
    async cleanSearchHistory() {
        const { ctx } = this;
        let ret = { status: true };
        if (!ctx.appUserId || !ctx.userId) {
            //如果没有登录就不做处理
            return ret;
        }
        let params = { state: 0 };
        let where = {
            user_id: ctx.userId
        }
        await ctx.realestateModel.CdPresellSearchHistory.update(params, { where: where });
        return ret;
    }

}

module.exports = PresellSearchHistoryService;
