
'use strict';

const Service = require('egg').Service;
const moment = require('moment');
const _ = require('lodash');
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, },
]
const SaleType = { 0: '未开售', 1: '售罄', 2: '预售', 3: '在售' };

class NewHouseService extends Service {
    /**
     * 新房信息
     * @param {string} id 新房id
     */
    async getNewHouse(id) {
        const { ctx } = this;
        //新房楼盘基本信息
        let newHouseInfo = await ctx.realestateModel.NewHouse.one({ where: { id: id } });
        if (newHouseInfo === null) {
            return {};
        }
        //开发商信息
        let developerInfoTask = ctx.realestateModel.Developer.one({ where: { id: newHouseInfo.developer_id } });
        //新房的户型信息
        let houseTypeFilter = {
            where: {
                new_house_id: newHouseInfo.id,
                status: 'online',
                valid: 1
            }
        }
        let newHouseTypeInfoTask = ctx.realestateModel.NewHouseType.all(houseTypeFilter);
        //图片
        let filter = {
            pageIndex: 1,
            pageSize: 999,
            where: {
                status: 'online',
                valid: 1,
                type: 1,
                connect_id: id,
            }
        }
        let newHouseImagesTask = ctx.realestateModel.HouseImage.all(filter);
        //是否关注
        let collectionTask = ctx.service.house.v2.collection.getCollection({ type: 1, id: id });

        //获取每个任务的数据
        const retList = await Promise.all([developerInfoTask, newHouseTypeInfoTask, newHouseImagesTask, collectionTask]).then(result => {
            return result;
        }).catch(error => {
            ctx.failed(error);
        });
        let developerInfo = retList[0];
        let newHouseTypeInfo = retList[1];
        let newHouseImages = retList[2];
        let collection = retList[3];

        newHouseInfo.developer = developerInfo;
        newHouseInfo.newHouseType = newHouseTypeInfo;
        //对楼盘信息进行整理
        let newHouseFormat = await this.formatNewHouse(newHouseInfo);

        //图片信息整理
        let images = [];
        if (newHouseImages.length > 0) {
            for (let i in newHouseImages) {
                let image = {
                    id: newHouseImages[i].id,
                    path: newHouseImages[i].path,
                    description: newHouseImages[i].description,
                }
                images.push(image);
            }
        } else {
            //bugclose7894
            images.push({
                id: 1,
                path: newHouseInfo.image,
                description: ''
            });
        }
        //整理户型信息
        let newHouseType = await this.formatNewHouseTypeList(newHouseInfo);

        let ret = {
            house_basic: newHouseFormat,
            house_images: images,
            house_types: newHouseType,
            collection: collection.length > 0 ? true : false,
        }
        await ctx.service.house.v2.footPrint.addFootPrint({ id: id, type: 1 });//添加用户足迹记录

        return ret;
    }

    /**
     * 通过NewHouseId获取新房户型信息
     * @param {*} id 
     */
    async getNewHouseTypeList(id) {
        const { ctx } = this;
        let filter = {
            pageIndex: 1,
            pageSize: 999,
            where: {
                status: 'online',
                valid: 1,
                new_house_id: id,
            }
        }
        let newHouseTypeList = await ctx.realestateModel.NewHouseType.all(filter);
        let ret = await formatNewHouseTypeList(newHouseTypeList);
        return ret;
    }

    /**
     * 新房数据整理
     * @param {object} data 
     */
    async formatNewHouse(data) {
        const { ctx } = this;
        const decorationType = { 1: '毛坯', 2: '简装', 3: '精装' }
        const archType = { 1: '板楼', 2: '塔楼', 3: '别墅', 4: '塔板结合', 5: '高层', 6: '花园洋房', 7: '多层' };
        let ret = {};
        if (Object.keys(data).length > 0) {
            let nearBy = '';
            if (data.residential_nearby !== null && data.residential_nearby.length > 0) {
                if (/^\[(.*?)\]$/.test(data.residential_nearby)) {//粗略的匹配
                    //将json格式字符串处理
                    let temp = JSON.parse(data.residential_nearby);
                    for (let i in temp) {
                        let subTemp = '';
                        for (let j in temp[i]) {
                            subTemp += j + ':' + temp[i][j].join(',');
                        }
                        nearBy += subTemp + ';';
                    }
                } else {
                    nearBy = data.residential_nearby;
                }
            }
            //房型面积处理
            let newHouseTypeList = data.newHouseType;
            let typeArea = {
                min: 0,
                max: 0
            };
            if (newHouseTypeList.length > 0) {
                for (let i in newHouseTypeList) {
                    typeArea.min = typeArea.min === 0 ? newHouseTypeList[i].area : (newHouseTypeList[i].area < typeArea.min ? newHouseTypeList[i].area : typeArea.min);
                    typeArea.max = typeArea.max === 0 ? newHouseTypeList[i].area : (newHouseTypeList[i].area > typeArea.max ? newHouseTypeList[i].area : typeArea.max);
                }
            }
            let area = typeArea.min === typeArea.max ? Number(typeArea.min) : Number(typeArea.min) + '-' + Number(typeArea.max);

            //经纬度
            let longitude = 0;
            let latitude = 0;
            if (data.gps.length > 0) {
                let gpsInfo = data.gps.split(',').slice(0, 2);
                longitude = gpsInfo[1];
                latitude = gpsInfo[0];
            } else {
                let addressDecode = await this.addressDecode({ city: data.option_city_code, district: data.option_district_code, bizicircle: data.option_bizicircle_code });
                let address = addressDecode.city + addressDecode.county + addressDecode.region + data.address;
                let gps_result = await ctx.helper.getGPS(address, addressDecode.city);
                if (!gps_result.lat || !gps_result.lng) {
                    gps_result = await ctx.helper.getGPS(addressDecode, addressDecode.city);
                }
                if (gps_result) {
                    longitude = gps_result.lng;
                    latitude = gps_result.lat;
                }
                let gpsFilter = {
                    params: { gps: latitude + ',' + longitude },
                    where: { id: data.id }
                }
                await ctx.realestateModel.NewHouse.edit(gpsFilter);
            }

            ret.basic = {
                id: data.id,
                name: data.name,//标题
                description: data.description || '',//描述
                tags: data.tags ? eval(data.tags) : [],//项目特色
                favourable_info: data.favourable_info || '',//优惠
                reference_avg_price: Number(data.reference_avg_price) === 0 ? '--' : Number(data.reference_avg_price),//均价
                reference_total_price: Number(data.reference_total_price) === 0 ? '--' : Number(data.reference_total_price),//总价
                property_type: data.house_type.split(',').slice(0, 2),//物业类型
            }

            ret.info = {
                open_date: data.open_date,//开盘时间
                due_date: ['0000-00-00 00:00:00', '', undefined, 'Invalid date'].includes(data.due_date) ? '--' : data.due_date,//交房时间
                house_area: area,//建筑面积包含各个户型的面积
                decoration: decorationType[data.decoration_type] || '',//装修情况，1 毛坯，2简装，3精装
                green_ratio: Number(data.residential_green_ratio),//绿化
                area_ratio: Number(data.residential_area_ratio),//容积
                address: data.address,//地址
                longitude: longitude,//经度
                latitude: latitude,//纬度
            }
            ret.detail = {
                basic: {
                    reference_avg_price: data.reference_avg_price === 0 ? '--' : Number(data.reference_avg_price),//均价
                    tags: data.tags ? eval(data.tags) : [],//项目特色
                    property_type: data.house_type.split(',').slice(0, 2),//物业类型
                    property_right_years: data.residential_property_right_years,//产权年限
                    build_type: archType[data.residential_arch_type] || '',//建筑类型 1 板楼 2塔楼'
                    decoration: decorationType[data.decoration_type] || '',//装修情况，1 毛坯，2简装，3精装
                },
                sale: {
                    sale_type: SaleType[data.sale_type] || SaleType[3],//销售状态 0未开售，1售罄,2预售,3在售
                    address: data.address,//地址
                    sale_address: data.sale_address,//售楼地址
                    developer: data.developer ? data.developer.name : '',//开发商
                    open_date: data.open_date,//开盘时间
                    due_date: ['0000-00-00 00:00:00', '', undefined, 'Invalid date'].includes(data.due_date) ? '--' : data.due_date,//交房时间
                },
                residential: {
                    land_area: Number(data.residential_land_area),//占地面积
                    house_area: Number(data.residential_house_area),//建筑面积
                    area_ratio: Number(data.residential_area_ratio),//容积率
                    green_ratio: Number(data.residential_green_ratio),//绿化率
                    property_fee: data.residential_property_fee,//物业费用
                    property_company: data.residential_property_company,//物业公司
                    plan_rooms: data.plan_rooms,//规划户数
                    plan_parks: data.plan_parks,//车位情况
                    heat_supply_type: data.residential_heat_supply_type,//供暖方式
                    water_supply_type: data.residential_water_suppler_type,//供水方式
                    power_supply_type: data.residential_power_suppler_type,//供电方式
                    near_by: nearBy,//周边规划
                },
                //2.2版本是新拉的数据是多个售卖资格
                permit: (data.selling_qualification === null || !data.selling_qualification) ? [] : JSON.parse(data.selling_qualification)
                // permit: {
                //     pre_sale_permit: data.pre_sale_permit,//预售证
                //     pre_sale_permit_date: data.pre_sale_permit_date,//发证时间
                //     building_numbers: data.building_numbers,//绑定楼栋
                // }

            }
        }
        return ret;
    }

    /**
     * 对newHouseTypeList格式化
     * @param {object} newHouseTypeList 
     */
    async formatNewHouseTypeList(newHouseInfo) {
        const { ctx } = this;
        let newHouseTypeList = newHouseInfo.newHouseType;
        //数据格式化
        let retList = [];
        if (newHouseTypeList.length > 0) {
            let taskList = [];
            for (let i in newHouseTypeList) {
                newHouseTypeList[i].house_type = newHouseInfo.house_type;
                taskList[i] = this.formatNewHouseType(newHouseTypeList[i]);
            }

            retList = await Promise.all(taskList).then(result => {
                return result;
            }).catch(error => {
                ctx.failed(error);
            });
        }
        //将楼盘的户型按照户型分组
        let typeFormat = {};
        for (let i in retList) {
            let type = retList[i].type;
            if (!typeFormat.hasOwnProperty(type)) {
                typeFormat[type] = {
                    name: HOUSE_TYPE[type].name,
                    results: [],
                    count: 0
                };
            }
            typeFormat[type].results.push(retList[i]);
            typeFormat[type].count++;
        }

        let classification = [];
        for (let i in typeFormat) {
            classification.push(typeFormat[i]);
        }
        let ret = {
            all: {
                name: '全部',
                results: retList,
                count: retList.length
            },
            classification: classification
        };
        return ret;
    }

    /**
     * newHouseType数据整理
     * @param {object} data 
     */
    async formatNewHouseType(data) {
        const { ctx } = this;
        let ret = {};
        if (Object.keys(data).length > 0) {
            ret = {
                id: data.id,
                new_house_id: data.new_house_id,
                type: data.type,//类型，如三居、四居
                house_type: data.house_type.split(',').slice(0, 2),
                image: data.image ? eval(data.image) : [],
                apartment: data.apartment,//户型，如4室2厅3卫
                sale_type: SaleType[data.sale_type] || '',
                area: Number(data.area),//面积
                orientation: data.orientation,//朝向
                num: data.num,//房源数量
                price: data.price === 0 ? '--' : data.price,//价格
                discount: Number(data.discount),//折扣
                tag: data.tags ? eval(data.tags) : [],//特点
            }
        }
        return ret;
    }


    /**
     * 新房根据条件筛选
     * @param {*} condition 
     */
    async getNewHouseList(condition) {
        const { ctx } = this;
        let types = ['all', 'sale', 'open', 'favourable', 'home'];
        let type = (condition.hasOwnProperty('type') && types.includes(condition.type)) ? condition.type : '';
        let page = Number(condition.page) || 1;
        let pageSize = Number(condition.page_size) || 30;
        let filter = {
            page: page,
            limit: pageSize,
            where: {
                status: 'online',
                valid: 1
            },
            order: [['sale_type', 'desc']],
            // order: [],
        }
        //根据筛选项增加不同的指定类型
        // if (condition.hasOwnProperty('type') && condition.type !== '') {
        //     if (type === 'home') {
        //         //为您推荐只展示50条在售楼盘的数据，根据排序序号取数，数字小的排在前面，数字一样的情况下根据时间逆序排列，时间也一样的情况下随机排列；
        //         filter.limit = Number(condition.page_size) || 50;
        //         // filter.order.push(['order_id', 'desc'], ['created_at', 'desc']);拿掉排序，跟默认排序重复了 2019-6-28 14:06:00 lisk
        //     } else if (type === 'all') {
        //         filter.order.push(['sale_type', 'desc']);
        //     } else if (type === 'sale') {
        //         //点击在售楼盘进入列表页面且只展示当前销售状态为在售的楼盘
        //         filter.where.sale_type = 3;
        //     } else if (type === 'open') {
        //         //只展示最近三个月内开盘的楼盘，往前追溯三个月,列表单次加载30条楼盘数据，滑到底部再次加载30条
        //         let endDate = moment().subtract(180, 'days').format('YYYY-MM-DD HH:mm:ss');
        //         filter.where.open_date = { $gt: endDate };
        //         filter.order.push(['sale_type', 'desc']);
        //     } else if (type === 'favourable') {
        //         //点击优惠好盘只展示有优惠的楼盘,列表单次加载30条楼盘数据，滑到底部再次加载30条
        //         filter.where.favourable_info = { $not: null };
        //         filter.order.push(['sale_type', 'desc']);
        //     }
        // }

        //是否有值来增加筛选项
        if (condition.unit_price && condition.unit_price.hasOwnProperty('min') && condition.unit_price.hasOwnProperty('max')) {//单价
            filter.where.reference_avg_price = { $between: [condition.unit_price.min, condition.unit_price.max] };
        }
        //里面的min和max也需要判断
        if (condition.total_price && condition.total_price.hasOwnProperty('min') && condition.total_price.hasOwnProperty('max')) {//总价
            filter.where.reference_total_price = { $between: [condition.total_price.min, condition.total_price.max] };
        }
        //根据户型的面积筛选 
        //根据户型筛选
        if ((condition.area && condition.area.hasOwnProperty('min') && condition.area.hasOwnProperty('max')) || condition.house_type) {
            let newHouseTypeFilter = {
                attributes: ['new_house_id'],
                where: {
                    status: 'online',
                    valid: 1
                }
            }
            //v2.1去掉户型筛选,替换为贷款方式
            // if (condition.house_type) {
            //     newHouseTypeFilter.where.type = condition.house_type;
            // }
            if ((condition.area && condition.area.hasOwnProperty('min') && condition.area.hasOwnProperty('max'))) {
                newHouseTypeFilter.where.area = { $between: [condition.area.min, condition.area.max] };
            }
            let newHouseIds = await ctx.realestateModel.NewHouseType.all(newHouseTypeFilter);
            let matchIds = _.uniq(_.map(newHouseIds, 'new_house_id'));
            filter.where.id = { $in: matchIds };
        }

        //贷款方式
        if (condition.loan_type && Number(condition.loan_type) !== 0) {
            filter.where.loan_type = Number(condition.loan_type);
        }

        if (condition.name) {//关键词搜索 模糊查询
            //增加搜索历史
            let addHistory = {
                type: 1,
                key_word: condition.name
            };
            await ctx.service.house.v2.searchHistory.addSearchHistory(addHistory);
            filter.where.name = { $like: '%' + condition.name + '%' }
        }
        if (condition.area_code) {//城市\区域\商圈筛选
            if (condition.area_code.hasOwnProperty('city_code') && condition.area_code.city_code !== '') {
                filter.where.option_city_code = condition.area_code.city_code;
            }
            if (condition.area_code.hasOwnProperty('district_code') && condition.area_code.district_code !== '') {
                filter.where.option_district_code = condition.area_code.district_code;
            }
            if (condition.area_code.hasOwnProperty('bizcircle_code') && condition.area_code.bizcircle_code !== '') {
                filter.where.option_bizicircle_code = condition.area_code.bizcircle_code;
            }
        }
        filter.order.push(['order_id', 'desc'], ['id', 'desc']);//添加默认排序 2019-6-28 14:05:25 lisk
        let newHouseList = await ctx.realestateModel.NewHouse.list(filter);
        let list = [];
        if (newHouseList.count > 0) {
            for (let i in newHouseList.rows) {
                let tmp = await this.formatNewHouseBasic(newHouseList.rows[i]);
                list.push(tmp);
            }
        }
        let ret = {
            results: list,
            count: newHouseList.count
        };
        return ret;
    }


    async formatNewHouseBasic(newHouseInfo) {
        const { ctx } = this;
        let ret = {
            id: newHouseInfo.id,
            name: newHouseInfo.name,
            address: newHouseInfo.address,
            tags: newHouseInfo.tags ? eval(newHouseInfo.tags) : [],
            image: newHouseInfo.image,
            price: Number(newHouseInfo.reference_avg_price) === 0 ? '--' : Number(newHouseInfo.reference_avg_price),
            corner: newHouseInfo.corner || '',
            sale_type: SaleType[newHouseInfo.sale_type] || SaleType[3],//销售状态 0未开售，1售罄,2预售,3在售
            property_type: newHouseInfo.house_type.split(',').slice(0, 2),//物业类型
        }
        return ret;
    }

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

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

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

        if (total_price) {
            where.reference_total_price = { $ne: 0 };
            order.push(['reference_total_price', total_price]);
        }
        order.push(['order_id', 'desc']);
        let new_houses_rows = await ctx.realestateModel.NewHouse.list({ page: page, limit: limit, where: where, order: order });
        const similar_list = [];
        for (let i in new_houses_rows.rows) {
            const new_house = new_houses_rows.rows[i];
            const temp_house = await this.formatNewHouseBasic(new_house);
            temp_house.can_gjj_loan = new_house.corner ? 1 : 0;
            similar_list.push(temp_house);
        }

        return similar_list;
    }

    /**
     * 根据市区商圈的城市编码获取地址
     * @param {*} code 
     */
    async addressDecode(code) {
        const { ctx } = this;
        let taskList = [
            ctx.blockModel.City.one({ where: { code: code.city } }),
            ctx.blockModel.HouseDistrict.one({ where: { id: code.district } }),
            ctx.blockModel.HouseBizcircle.one({ where: { id: code.bizicircle } }),
        ];
        let retList = await Promise.all(taskList).then(result => {
            return result;
        }).catch(error => {
            ctx.failed(error);
        });

        const city = retList[0] !== null && retList[0].name ? retList[0].name : '';
        const county = retList[1] !== null && retList[1].name ? retList[1].name : '';
        const region = retList[2] !== null && retList[2].name ? retList[2].name : '';

        return { city, county, region };
    }

    /**
     * 新房支持的城市
     */
    async getNewHouseCity() {
        const { ctx } = this;
        //所有支持的城市编码
        let filter = {
            attributes: ['code'],
            where: {
                valid: 1
            }
        }
        let cityCode = await ctx.realestateModel.NewHouseCityPrice.findAll(filter);
        let ret = { results: [] };
        if (cityCode !== undefined && cityCode.length > 0) {
            let cityCodes = _.uniq(_.map(cityCode, 'code'));
            let cityFilter = {
                where: { code: { $in: cityCodes } }
            }
            let cityName = await ctx.blockModel.City.findAll(cityFilter);
            ret.results = cityName !== undefined ? cityName : [];
        }
        return ret;
    }
    /**
     * 新房城市对应的价格显示
     */
    async getNewHouseCityPrice() {
        const { ctx } = this;
        //所有支持的城市编码
        let filter = {
            attributes: ['city', 'code', 'price'],
            where: {
                valid: 1
            }
        }
        let ret = await ctx.realestateModel.NewHouseCityPrice.findAll(filter);
        if (ret === undefined && ret.length === 0) {
            return [];
        }
        return ret;
    }





}

module.exports = NewHouseService;
