
'use strict';

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

class PresellHouseService 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', 'name', 'market_time', 'purpose'],
            where: {
                valid: 1,
                status: 'online',
            },
            order: [['market_time', 'desc']]
        }
        if (condition.name) {//关键词搜索 模糊查询
            //增加搜索历史
            await ctx.service.cd.presellSearchHistory.addSearchHistory(condition.name);
            filter.where.name = { $like: '%' + condition.name + '%' }
        }
        let list = await ctx.realestateModel.CdPresellHouse.findAndCountAll(filter);
        let ret = {
            list: list.rows,
            page: page,
            total_count: list.count,
            page_size: Math.ceil(list.count / limit)
        }
        if (ret.list.length > 0) {
            for (let i in ret.list) {
                ret.list[i].market_time = moment(ret.list[i].market_time).format('YYYY-MM-DD');
            }
        }
        return ret;
    }

    /**
     * 根据编号获取预售楼盘信息
     * @param {integer} id 资讯id
     */
    async getPresellHouse(id) {
        const { ctx } = this;
        let filter = {
            attributes: ['id', 'name', 'phone', 'presell_permit', 'purpose', 'presell_area', 'market_time'],
            where: {
                id: id,
                valid: 1,
                status: 'online',
            }
        }
        let presellHouse = await ctx.realestateModel.CdPresellHouse.findOne(filter);
        let ret = {
            name: presellHouse.name || '',
            phone: presellHouse.phone || '',
            presell_permit: presellHouse.presell_permit || '',
            purpose: presellHouse.purpose || '',
            presell_area: presellHouse.presell_area || '',
            market_time: presellHouse.market_time ? moment(presellHouse.market_time).format('YYYY-MM-DD') : '',
        }
        return ret;
    }



}

module.exports = PresellHouseService;
