
'use strict';

const Service = require('egg').Service;
const R = require('ramda');

const HOUSE_TYPE = [
    { name: '不限', min: 0, max: 0, value: 0, },
    { name: '1室', min: 1, max: 1, value: 1, },
    { name: '2室', min: 2, max: 2, value: 2, },
    { name: '3室', min: 3, max: 3, value: 3, },
    { name: '4室', min: 4, max: 4, value: 4, },
    { name: '5室', min: 4, max: 4, value: 5, },
    { name: '5室以上', min: 5, max: 10000, value: 6, },
    { name: '别墅', min: 10000, max: 10000000, value: 7, },
]
class RentalHouseService extends Service {


    //租房条件过滤
    async getRentalHousesByFilter(condition) {

        const { ctx } = this;
        let { brand, name, price, house_type, area_code, page, page_size } = condition;

        page = page ? page : 1;
        let limit = page_size ? page_size : 30;

        let where = { status: 'online', valid: 1 };
        if (brand) {
            // where.developer_id = brand;
            where.developer_id = { $in: brand };
        }
        if (name) {
            //增加搜索历史
            ctx.service.house.v2.searchHistory.addSearchHistory({ type: 2, key_word: name });
            where.name = { $like: `%${name}%` };
        }
        if (price && price.max) {
            where.price = { $between: [price.min, price.max] };
        }
        if (area_code && Object.keys(area_code).length !== 0) {

            if (area_code.city_code && area_code.city_code !== '') {
                where.option_city_code = area_code.city_code;
            }
            if (area_code.district_code && area_code.district_code !== '') {
                where.option_district_code = area_code.district_code;
            }
            if (area_code.bizcircle_code && area_code.bizcircle_code !== '') {
                where.option_bizicircle_code = area_code.bizcircle_code;
            }
        }
        if (house_type) {
            const house_types = await ctx.realestateModel.RentalHouseType.all({ where: { type: house_type, status: 'online', valid: 1 } });
            const rental_houses_ids = R.pluck('rental_house_id', house_types);
            let match_ids = new Set(rental_houses_ids);
            match_ids = [...match_ids];
            // if (Array.isArray(match_ids) && match_ids.length !== 0) {
            //     where.id = { $in: match_ids };
            // }
            where.id = { $in: match_ids };
        }

        const rental_houses_results = await ctx.realestateModel.RentalHouse.list({ page: page, limit: Number(limit), where: where, order: [['order_id', 'desc'], ['id', 'desc']] });
        let rental_houses = await this.formatRentalHouseBasic(rental_houses_results.rows);
        rental_houses = R.project(['id', 'image', 'name', 'address', 'price', 'surplus_amount', 'tags', 'favourable_info'])(rental_houses);

        return { page: page, count: rental_houses_results.count, results: rental_houses };

    }

    //房源详细信息
    async getRentalHouse(rental_house_id) {

        const { ctx } = this;
        //获取房源基本信息
        const rental_house_info = await ctx.realestateModel.RentalHouse.one({ where: { id: rental_house_id } });
        if (!rental_house_info || !rental_house_info.id) {
            ctx.failed('rental house not found');
        }

        //楼盘图片信息和房型信息
        const house_types_rets = await ctx.realestateModel.RentalHouseType.all({ where: { rental_house_id: rental_house_id, status: 'online', valid: 1 } });
        const p_house_images = ctx.service.house.v2.houseImage.getAll({ type: 0, connect_id: rental_house_id }, ['id', 'path', 'description']);
        const p_house_types = this.formatRentHouseTypes(house_types_rets);
        const p_collection = await ctx.service.house.v2.collection.getCollection({ type: 2, id: rental_house_id });
        const p_ret = await Promise.all([p_house_images, p_house_types, p_collection]).then(result => {//等待所有异步内容获取完成
            return result;
        }).catch(error => {
            ctx.failed(error);
        });
        const house_images = p_ret[0];
        const house_types = p_ret[1];
        const collection = p_ret[2];//是否关注

        //处理房源基本信息格式
        let house_basic = await this.formatRentalHouseBasic([rental_house_info]);
        house_basic = house_basic[0];

        //添加用户足迹
        ctx.service.house.v2.footPrint.addFootPrint({ type: 2, id: rental_house_id });

        let gps_info = {};
        if (!rental_house_info.gps) {
            const city_codes = [rental_house_info.province, rental_house_info.city, rental_house_info.area];
            const cities = await ctx.blockModel.City.all({ where: { code: { $in: city_codes } } });
            const city = (cities && cities[1] && cities[1].name) ? cities[1].name : '';
            const address = R.pluck('name', cities).join('') + rental_house_info.address;
            console.info(address);
            gps_info = await ctx.helper.getGPS(address, city);
            ctx.realestateModel.RentalHouse.edit({ where: { id: rental_house_id }, params: { gps: `${gps_info.lat},${gps_info.lng}` } });
        } else {
            const gps_str = ctx.helper.checkGps(rental_house_info.gps);
            const gps_array = gps_str.split(',');
            gps_info = {
                lng: gps_array[1],
                lat: gps_array[0],
            }
        }

        house_basic.longitude = gps_info.lng;
        house_basic.latitude = gps_info.lat;

        return { house_basic, house_images, house_types, collection: collection.length > 0 ? true : false, };
    }

    //格式化户型数据
    async formatRentHouseTypes(house_types) {

        if (!Array.isArray(house_types) || house_types.length === 0) {
            return [];
        }
        const { ctx } = this;
        let house_types_tmp = {};

        for (let i in house_types) {
            const house_type = house_types[i];
            if (house_type.status === 'offline' || house_type.valid === 0) {
                continue;
            }

            const house_type_images = await ctx.service.house.v2.houseImage.getAll({ type: 3, connect_id: house_type.id });

            const type = house_type.type || 1;
            const house_type_value = HOUSE_TYPE[type];
            if (!house_types_tmp[type]) {
                house_types_tmp[type] = {
                    name: house_type_value.name,
                    results: [],
                    count: 0,
                }
            }
            house_types_tmp[type].results.push({
                id: house_type.id,
                name: house_type.name,
                area: house_type.area,
                price: house_type.price,
                images: R.project(['id', 'path', 'description'])(house_type_images),
            });
            house_types_tmp[type].count++;
        }

        const ret = [];
        for (let i in house_types_tmp) { ret.push(house_types_tmp[i]) }
        return ret;

    }


    async formatRentalHouseBasic(rental_houses) {

        const { ctx } = this;
        if (!rental_houses || !Array.isArray(rental_houses) || rental_houses.length === 0) {
            return [];
        }
        const ret = [];
        for (let i in rental_houses) {
            const rental_house = rental_houses[i];
            const temp_rental_house = {
                id: rental_house.id,
                name: rental_house.name,//房源名称
                image: rental_house.image,//列表展示图片
                // residential_id: rental_house.residentialId,//小区id
                address: rental_house.address,//详细地址
                gps: rental_house.gps,//项目地址经纬度
                price: rental_house.price,//价格
                discount: rental_house.discount,//折扣
                // business_license: rental_house.businessLicense,
                tags: rental_house.tags,//房源特点
                rental_type: rental_house.rental_type,//租房类型 1整租 2合租 3独栋公寓
                surplus_amount: rental_house.surplus_amount,//剩余数量 目前如果为0则展示 "满租"，其他情况不展示
                favourable_info: rental_house.favourable_info,//优惠信息
                introduce: rental_house.description || `该社区亮点：
                1、房源介绍：精装公寓，家电齐全，独立卫生间，南通北透，独门独户。
                2、房型说明：独门独户，拎包入住，满足各种需求，采光
                3、社区配套：健身房、休憩区、小影院、娱乐室、商务区、无人商店、快递柜。            
                4、房间配套：空调、Wifi、洗衣机、热水器、冰箱、床、衣柜、电脑桌、沙发。`,
                room_configuration: rental_house.room_configuration,//房间配置
                // room_configuration: rental_house.roomConfiguration,//房间配置
                notice: rental_house.notice,//入住须知
            };
            ret.push(temp_rental_house);
        }

        return ret;
    }

    //获取推荐楼盘 目前推荐逻辑条件少 后面扩展
    async getRecommendRentalHouses(condition) {

        const { ctx } = this;
        //推荐楼盘
        let { city_code, page, limit, price } = condition;
        page = page ? page : 1;
        limit = limit ? limit : 3;

        let where = { status: 'online', valid: 1 };
        let order = [];
        if (city_code) {
            where.option_city_code = city_code;

        }
        if (price) {
            where.price = { $ne: 0 };
            order.push(['price', price]);
        }

        order.push(['order_id', 'desc']);
        let rental_houses_rows = await ctx.realestateModel.RentalHouse.list({ page, limit, where, order });
        const recommend_list = await this.formatRentalHouseBasic(rental_houses_rows.rows);
        const recommend_result = R.project(['id', 'image', 'name', 'address', 'price', 'surplus_amount', 'tags', 'favourable_info'])(recommend_list);

        return recommend_result;
    }

}

module.exports = RentalHouseService;
