
'use strict';

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

class AnswerLikeService extends Service {

    /**
     * 回答
     * @param {object} inputParams 
     */
    async like(id) {
        const { ctx } = this;
        if (!ctx.appUserId || !ctx.userId) {
            //如果没有登录就不做处理
            return false;
        }
        let filter = {
            where: {
                answer_id: id,
                user_id: ctx.userId,
                state: 1
            }
        }
        let likeInfo = await ctx.realestateModel.AnswerLike.one(filter);
        if (likeInfo !== null) {
            return { id: likeInfo.id };
        }
        let data = {
            user_id: ctx.userId,
            app_user_id: ctx.appUserId,
            app_id: ctx.appId,
            app_type_id: ctx.appTypeId,
            answer_id: id,
            state: 1,
        };
        let retId = await ctx.realestateModel.AnswerLike.add(data);
        return { id: retId };
    }

    /**
     * 取消点赞
     * @param {*} inputParams 
     */
    async unLike(id) {
        const { ctx } = this;
        let filter = {
            params: {
                state: 0
            },
            where: {
                answer_id: id,
                user_id: ctx.userId,
                state: 1
            }
        }
        let res = await ctx.realestateModel.AnswerLike.edit(filter);
        return { status: true };
    }

    /**
     * 是否点赞某个回答
     * @param {*} id 
     */
    async isLike(id) {
        const { ctx } = this;
        let isLike = false;
        if (!ctx.userId) {
            return isLike;
        }
        let filter = {
            where: {
                answer_id: id,
                state: 1,
                user_id: ctx.userId
            }
        }
        let likeInfo = await ctx.realestateModel.AnswerLike.all(filter);
        isLike = likeInfo.length > 0 ? true : false;
        return isLike;
    }

    /**
     * 获取某个回答被点赞的数量
     * @param {*} id 
     */
    async getLikeCount(id) {
        const { ctx } = this;
        let likeFilter = {
            attributes: ['id'],
            where: {
                answer_id: Number(id),
                state: 1
            }
        }
        let answerLikeList = await ctx.realestateModel.AnswerLike.all(likeFilter);
        return answerLikeList.length;
    }

}

module.exports = AnswerLikeService;
