
'use strict';

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

class searchHistoryService extends Service {

    /**
     * 添加搜索历史
     * @param {object} inputParams 
     */
    async addSearchHistory(inputParams) {
        const { ctx, service } = this;
        if (!ctx.userId) {
            return false;
        }
        let data = {
            userId: ctx.userId,
            appUserId: ctx.appUserId,
            keyWord: inputParams.key_word,
            houseStyle: inputParams.type,
            state: 1,
        };
        let ret = await service.houseCommon.searchHistory.add(data);
        return { id: ret.id };
    }

    /**
     * 获取搜索历史
     * 历史记录取用户最近6个月的搜索记录，去重处理，条数不超过50条
     * 排序根据搜索时间逆序排列，距离当前时间近的排在前面，重复搜索的关键词取最近一次的搜索时间进行排序
     * 如果没有搜索记录的就不显示搜索词
     */
    async getSearchHistoryList(type) {
        const { ctx, service } = this;
        let ret = {
            results: [],
            count: 0
        };
        if (!ctx.appUserId || !ctx.deviceId || !ctx.deviceLoginId || !ctx.userId) {
            //如果没有登录就返回空
            return ret;
        }
        let endDate = moment().subtract(180, 'days').format('YYYY-MM-DD HH:mm:ss');
        let filter = {
            pageIndex: 1,
            pageSize: 50,
            queryConditions: [{
                key: "state",
                value: 1,
                operator: "equal"
            }, {
                key: "userId",
                value: ctx.userId,
                operator: "equal"
            },
            {
                key: "createdAt",
                value: endDate,
                operator: "greater"
            },
            ],
            orderConditions: [{
                key: 'createdAt',
                orderSequence: 'desc',
            },],
        }
        if (type) {
            let typeCondition = {
                key: "houseStyle",
                value: type,
                operator: "equal"
            };
            filter.queryConditions.push(typeCondition);
        }
        let list = [];
        let searchHistoryList = await service.houseCommon.searchHistory.all(filter);
        if (searchHistoryList.rowCount > 0) {
            for (let i in searchHistoryList.results) {
                if (list.indexOf(searchHistoryList.results[i].keyWord) === -1) {
                    list.push(searchHistoryList.results[i].keyWord);
                }
            }
        }
        ctx.logger.info(list);

        ret = {
            results: list,
            count: list.length
        };
        return ret;
    }


    /**
     * 用户点击清除搜索记录
     */
    async cleanSearchHistory(type) {
        const { ctx, service } = this;
        let ret = { status: true };
        if (!ctx.appUserId || !ctx.deviceId || !ctx.deviceLoginId || !ctx.userId) {
            //如果没有登录就不做处理
            return ret;
        }
        let filter = {
            pageIndex: 1,
            pageSize: 50,
            queryConditions: [{
                key: "state",
                value: 1,
                operator: "equal"
            }, {
                key: "userId",
                value: ctx.userId,
                operator: "equal"
            }, {
                key: "houseStyle",
                value: type,
                operator: "equal"
            }],
            orderConditions: [],
        }
        let searchHistoryList = await service.houseCommon.searchHistory.all(filter);

        if (searchHistoryList.rowCount > 0) {
            let taskList = [];
            for (let i in searchHistoryList.results) {
                taskList[i] = service.houseCommon.searchHistory.delete(searchHistoryList.results[i].id);
            }

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


    }

}

module.exports = searchHistoryService;
