
'use strict';

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


class NewsService extends Service {

    /**
     * 资讯列表
     * @param {*} condition 
     */
    async getList(condition) {
        const { ctx } = this;
        let page = Number(condition.page) || 1;
        let limit = Number(condition.limit) || 20;
        let offset = (page - 1) * limit;
        let filter = {
            page,
            limit,
            offset,
            attributes: ['id', 'title', 'images', 'source', 'source_time', 'updated_at'],
            where: {
                valid: 1,
                status: 'pass',
            },
            order: [['top', 'desc'], ['source_time', 'desc']]
        }
        let list = await ctx.realestateModel.CdNews.findAndCountAll(filter);
        for (let i in list.rows) {
            if (list.rows[i].source_time === 'Invalid date') {
                list.rows[i].source_time = list.rows[i].updated_at;
            }
        }

        let ret = {
            list: list.rows,
            page: page,
            total_count: list.count,
            page_size: Math.ceil(list.count / limit)
        }
        return ret;
    }

    /**
     * 根据编号获取资讯信息
     * @param {integer} id 资讯id
     */
    async getNews(id) {
        const { ctx } = this;
        let ret = {
            title: '',
            source: '',
            source_time: '',
            content: '',
            author: '',
            read_num: '',
        }
        let filter = {
            attributes: ['title', 'source', 'source_time', 'content', 'author', 'initial_num', 'updated_at'],
            where: {
                id: id,
                valid: 1,
                status: 'pass',
            }
        }
        let news = await ctx.realestateModel.CdNews.findOne(filter);
        if (news) {
            ret.title = news.title;
            ret.source = news.source;
            ret.source_time = news.source_time === 'Invalid date' ? news.updated_at : news.source_time;
            ret.content = news.content;
            ret.author = news.author;
            ret.read_num = news.initial_num;
        }
        return ret;
    }



}

module.exports = NewsService;
