
'use strict';

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

class HotQuestionAnswerService extends Service {

    /**
     * 回答
     * @param {object} inputParams 
     */
    async addAnswer(inputParams) {
        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,
            question_id: inputParams.question_id,
            answer: inputParams.answer,
            city: inputParams.city_code,
            status: 'wait',
        };
        let retId = await ctx.realestateModel.HotQuestionAnswer.add(data);
        return { id: retId };
    }

    /**
     * 回答列表
     * @param {*} condition 
     */
    async answerList(condition) {
        const { ctx } = this;
        let filter = {
            page: condition.page || 1,
            limit: condition.limit || 10,
            where: {
                question_id: Number(condition.question_id),
                status: 'pass',
            },
            order: [['created_at', 'desc']]
        }
        let res = await ctx.realestateModel.HotQuestionAnswer.list(filter);

        let taskList = [];
        for (let i in res.rows) {
            taskList[i] = this.formatAnswer(res.rows[i]);
        }
        let retList = await Promise.all(taskList).then(result => {
            return result;
        }).catch(error => {
            ctx.failed(error);
        });
        let ret = {
            results: retList,
            count: res.count
        }
        return ret;
    }


    /**
     * 获取该回答的点赞数量
     * 用户头像昵称
     * 本人是否点赞
     * @param {*} data 
     */
    async formatAnswer(data) {
        const { ctx } = this;
        //回答的用户信息
        let answerUserInfo = await ctx.service.house.v2.mine.getAppUserInfo(data.app_user_id);
        //点赞的数量
        let LikeCount = await ctx.service.house.v2.answerLike.getLikeCount(Number(data.id));
        //本人是否点赞
        let isLike = await ctx.service.house.v2.answerLike.isLike(Number(data.id));

        let ret = {
            id: data.id,
            answer: data.answer,
            time: data.created_at,
            avatar: answerUserInfo.avatar || '',
            nickname: answerUserInfo.nickname || '',
            like: isLike,
            count: LikeCount,
        }
        return ret;
    }






}

module.exports = HotQuestionAnswerService;
