
'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 getRentalHouseByFilter_V2(condition) {

        const { ctx } = this;
        const { brand, price, house_type, area_code, name, } = condition;
        let where = {};
        if (brand) {
            const residentials = await ctx.service.house.residential.getResidentialByDeveloper({ developer_id: brand });
            const residentials_ids = R.pluck('id', residentials);
        }
        if (area_code) {

        }
        if (house_type) {

        }
        if (name) {
            where.name = { $like: `%${name}%` };
        }

    }

    async getRentalHousesByFilter(condition) {

        const { ctx } = this;

        const queryConditions = [];
        if (condition.brand) {
            queryConditions.push({
                key: 'developerid',
                value: parseInt(condition.brand),
                operator: 'equal',
            });
        }
        if (condition.price && condition.price.max) {
            queryConditions.push({
                key: 'price',
                value: condition.price.min,
                operator: 'greaterEqual',
            });
            queryConditions.push({
                key: 'price',
                value: condition.price.max,
                operator: 'lessEqual',
            });
        }
        if (condition.house_type) {
            queryConditions.push({
                key: 'type',
                value: parseInt(condition.house_type),
                operator: 'equal',
            });
        }
        if (condition.area_code) {//城市\区域\商圈筛选
            if (condition.area_code.hasOwnProperty('city_code') && condition.area_code.city_code !== '') {
                queryConditions.push({
                    key: 'city',
                    value: condition.area_code.city_code,
                    operator: 'equal',
                });
            }
            if (condition.area_code.hasOwnProperty('district_code') && condition.area_code.district_code !== '') {
                queryConditions.push({
                    key: 'county',
                    value: condition.area_code.district_code,
                    operator: 'equal',
                });
            }
            if (condition.area_code.hasOwnProperty('bizcircle_code') && condition.area_code.bizcircle_code !== '') {
                queryConditions.push({
                    key: 'region',
                    value: condition.area_code.bizcircle_code,
                    operator: 'equal',
                });
            }
        }
        if (condition.name) {
            await ctx.service.house.searchHistory.addSearchHistory({ type: 2, key_word: condition.name });//增加搜索历史
            queryConditions.push({
                key: 'name',
                value: condition.name,
                operator: 'contains',
            });
        }
        queryConditions.push({
            key: "state",
            value: 0,
            operator: "notEqual"
        });
        const pageSize = parseInt(condition.page_size) ? parseInt(condition.page_size) : 30;
        const page = parseInt(condition.page) ? parseInt(condition.page) : 1;
        const filter = {
            pageSize: pageSize,
            pageIndex: page,
            queryConditions: queryConditions,
            orderConditions: [{
                key: 'price',
                orderSequence: 'asc',
            },],
        }
        const rental_houses_results = await ctx.service.houseCommon.rentalHouse.all(filter);

        let rental_houses = await this.formatRentalHouseBasic(rental_houses_results.results);
        rental_houses = R.project(['id', 'image', 'name', 'address', 'price', 'tags', 'favourable_info'])(rental_houses);
        return { results: rental_houses, count: rental_houses_results.rowCount };
    }

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

        const { ctx } = this;
        //获取房源基本信息
        let house_basic_result = await ctx.service.houseCommon.rentalHouse.one(rental_house_id);
        if (!house_basic_result || !house_basic_result.id) {
            ctx.failed('house not found');
        }

        rental_house_id = house_basic_result.id;

        //获取房源图片信息
        const p_house_images = this.getRentalHouseImages(rental_house_id);

        //获取房源类型
        const p_house_types = this.formatRentHouseTypes(house_basic_result.rentalHouseType);

        const p_ret = await Promise.all([p_house_images, p_house_types]).then(result => {//等待所有异步内容获取完成
            return result;
        }).catch(error => {
            ctx.failed(error);
        });

        const house_images = p_ret[0];
        const house_types = p_ret[1];

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

        //是否关注
        const collectionFilter = { type: 2, id: rental_house_id }
        const collection = await ctx.service.house.collection.getCollection(collectionFilter);

        ctx.service.house.footPrint.addFootPrint({ id: rental_house_id, type: 2 });//添加用户足迹记录
        const city = await ctx.blockModel.City.one({ where: { code: house_basic_result.residential.city } });
        const county = await ctx.blockModel.HouseDistrict.one({ where: { id: house_basic_result.residential.county } });
        const region = await ctx.blockModel.HouseBizcircle.one({ where: { id: house_basic_result.residential.region } });
        const city_name = (city && city.name) ? city.name : '';
        const county_name = (county && county.name) ? county.name : '';
        const region_name = (region && region.name) ? region.name : '';
        let address = city_name + county_name + region_name + house_basic.address;
        let gps_result = await ctx.helper.getGPS(address, city_name);
        if (!gps_result.lat || !gps_result.lng) {
            address = city_name + county_name + region_name;
            gps_result = await ctx.helper.getGPS(address, city_name);
        }
        let longitude = 0;
        let latitude = 0;
        if (gps_result) {
            longitude = gps_result.lng;
            latitude = gps_result.lat;
        }
        house_basic.longitude = longitude;
        house_basic.latitude = latitude;
        return { house_basic, house_images, house_types, collection: collection.rowCount > 0 ? true : false, };
    }

    //获取房源画册
    async getRentalHouseImages(rental_house_id) {

        const { ctx } = this;

        const house_image_filter = {
            pageSize: 10000,
            queryConditions: [
                {
                    key: 'state',
                    value: 1,
                    operator: 'equal'
                },
                {
                    key: 'type',
                    value: 0,
                    operator: 'equal'
                },
                {
                    key: 'connectId',
                    value: rental_house_id,
                    operator: 'equal'
                },
            ],

        };
        const house_images_results = await ctx.service.houseCommon.houseImage.all(house_image_filter);
        const house_images = R.project(['id', 'path', 'description'])(house_images_results.results);

        return house_images;
    }

    //格式化户型数据
    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.state === 0) {
                continue;
            }
            const house_type_image_filter = {
                pageSize: 10000,
                queryConditions: [
                    {
                        key: 'state',
                        value: 1,
                        operator: 'equal'
                    },
                    {
                        key: 'type',
                        value: 3,
                        operator: 'equal',
                    },
                    {
                        key: 'connectId',
                        value: house_type.id,
                        operator: 'equal',
                    }
                ],

            };
            const house_type_images_results = await ctx.service.houseCommon.houseImage.all(house_type_image_filter);

            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_results.results),
            });
            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,//详细地址
                price: rental_house.price,//价格
                discount: rental_house.discount,//折扣
                // business_license: rental_house.businessLicense,
                tags: rental_house.tags ? eval(rental_house.tags) : [],//房源特点
                favourable_info: rental_house.favourableInfo,//优惠信息
                introduce: rental_house.description || `该社区亮点：
                1、房源介绍：精装公寓，家电齐全，独立卫生间，南通北透，独门独户。
                2、房型说明：独门独户，拎包入住，满足各种需求，采光
                3、社区配套：健身房、休憩区、小影院、娱乐室、商务区、无人商店、快递柜。            
                4、房间配套：空调、Wifi、洗衣机、热水器、冰箱、床、衣柜、电脑桌、沙发。`,
                room_configuration: ctx.helper.JsonParse(rental_house.roomConfiguration),//房间配置
                // room_configuration: rental_house.roomConfiguration,//房间配置
                notice: rental_house.notice,//入住须知
            };
            ret.push(temp_rental_house);
        }

        return ret;
    }

}

module.exports = RentalHouseService;
