
'use strict';

const Service = require('egg').Service;
const moment = require('moment');
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 NewHouseService extends Service {
    /**
     * 新房信息
     * @param {string} id 新房id
     */
    async getNewHouse(id) {
        const { ctx, service } = this;
        //房产基本信息
        let newHouseInfo = await service.houseCommon.newHouse.one(id);
        let newHouseFormat = await this.formatNewHouse(newHouseInfo);
        //图片
        let filter = {
            pageIndex: 1,
            pageSize: 999,
            queryConditions: [{
                key: "state",
                value: '1',
                operator: "equal"
            }, {
                key: "type",
                value: '1',
                operator: "equal"
            }, {
                key: "connectId",
                value: id,
                operator: "equal"
            }],
            orderConditions: [],
        }
        let newHouseImages = await service.houseCommon.houseImage.all(filter);

        let images = [];
        if (newHouseImages.rowCount > 0) {
            for (let i in newHouseImages.results) {
                let image = {
                    id: newHouseImages.results[i].id,
                    path: newHouseImages.results[i].path,
                    description: newHouseImages.results[i].description,
                }
                images.push(image);
            }
        }
        //户型信息
        let newHouseType = await this.formatNewHouseTypeList(newHouseInfo);
        //是否关注
        let collectionFilter = { type: 1, id: id }
        let collection = await service.house.collection.getCollection(collectionFilter);
        let ret = {
            house_basic: newHouseFormat,
            house_images: images,
            house_types: newHouseType,
            collection: collection.rowCount > 0 ? true : false,
        }
        await service.house.footPrint.addFootPrint({ id: id, type: 1 });//添加用户足迹记录

        return ret;
    }

    /**
     * 通过NewHouseId获取新房户型信息
     * @param {*} id 
     */
    async getNewHouseTypeList(id) {
        const { ctx, service } = this;
        let filter = {
            pageIndex: 1,
            pageSize: 999,
            queryConditions: [{
                key: "state",
                value: 1,
                operator: "equal"
            }, {
                key: "newHouseId",
                value: id,
                operator: "equal"
            }],
            orderConditions: [],
        }
        let newHouseTypeList = await service.houseCommon.newHouseType.all(filter);
        let ret = await formatNewHouseTypeList(newHouseTypeList);
        return ret;
    }

    /**
     * 新房数据整理
     * @param {object} data 
     */
    async formatNewHouse(data) {
        const { ctx, service } = this;
        const saleType = { 0: '未开售', 1: '售罄', 2: '预售', 3: '在售' };
        const decorationType = { 1: '毛坯', 2: '简装', 3: '精装' }
        const archType = { 1: '板楼', 2: '塔楼' };
        const houseType = { 1: '住宅', 2: '公寓' };
        let ret = {};
        if (Object.keys(data).length > 0) {
            //开发商整理
            let developer = [];
            let developerinfo = data.residential.residentialDeveloper
            for (let i in developerinfo) {
                developer.push(developerinfo[i].developer.name);
            }
            //将json格式字符串处理
            let nearBy = '';
            if (data.residential.nearBy.length > 0) {
                let temp = eval(data.residential.nearBy);
                for (let i in temp) {
                    let subTemp = '';
                    for (let j in temp[i]) {
                        subTemp += j + ':' + temp[i][j].join(',');
                    }
                    nearBy += subTemp + ';';
                }
            }
            //房型面积处理
            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 ? typeArea.min : typeArea.min + '-' + typeArea.max;

            //经纬度
            const city = await ctx.blockModel.City.one({ where: { code: data.residential.city } });
            const county = await ctx.blockModel.HouseDistrict.one({ where: { id: data.residential.county } });
            const region = await ctx.blockModel.HouseBizcircle.one({ where: { id: data.residential.region } });
            const city_name = city.name ? city.name : '';
            const county_name = county.name ? county.name : '';
            const region_name = region.name ? region.name : '';
            let address = city_name + county_name + region_name + data.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;
            }

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

            ret.info = {
                open_date: data.openDate,//开盘时间
                due_date: (data.dueDate === '0000-00-00 00:00:00' || data.dueDate === '') ? '--' : data.dueDate,//交房时间
                house_area: area,//建筑面积
                decoration: decorationType[data.decorationType] || '',//装修情况，1 毛坯，2简装，3精装
                green_ratio: data.greenRatio,//绿化
                area_ratio: data.areaRatio,//容积
                address: data.address,//地址
                longitude: longitude,//经度
                latitude: latitude,//纬度
            }
            ret.detail = {
                basic: {
                    reference_avg_price: data.referenceAvgPrice === 0 ? '--' : data.referenceAvgPrice,//均价
                    tags: data.tags ? eval(data.tags) : [],//项目特色
                    property_type: houseType[data.houseType] || '',//物业类型
                    property_right_years: data.residential.propertyRightYears,//产权年限
                    build_type: archType[data.residential.archType] || '',//建筑类型 1 板楼 2塔楼'
                    decoration: decorationType[data.decorationType] || '',//装修情况，1 毛坯，2简装，3精装
                },
                sale: {
                    sale_type: saleType[data.saleType] || '',//销售状态 0未开售，1售罄,2预售,3在售
                    address: data.address,//地址
                    sale_address: data.saleAddress,//售楼地址
                    developer: developer,//开发商
                    open_date: data.openDate,//开盘时间
                    due_date: (data.dueDate === '0000-00-00 00:00:00' || data.dueDate === '') ? '--' : data.dueDate,//交房时间
                },
                residential: {
                    land_area: data.residential.landArea,//占地面积
                    house_area: data.residential.houseArea,//建筑面积
                    area_ratio: data.areaRatio,//容积率
                    green_ratio: data.greenRatio,//绿化率
                    property_fee: data.residential.propertyFee,//物业费用
                    property_company: data.residential.propertyCompany,//物业公司
                    plan_rooms: data.planRooms,//规划户数
                    plan_parks: data.planParks,//车位情况
                    heat_supply_type: data.residential.heatSupplyType,//供暖方式
                    water_supply_type: data.residential.waterSupplyType,//供水方式
                    power_supply_type: data.residential.powerSupplyType,//供电方式
                    near_by: nearBy,//周边规划
                },
                permit: {
                    pre_sale_permit: data.preSalePermit,//预售证
                    pre_sale_permit_date: data.preSalePermitDate,//发证时间
                    building_numbers: data.buildingNumbers,//绑定楼栋
                }
            }
        }
        return ret;
    }

    /**
     * 对newHouseTypeList格式化
     * @param {object} newHouseTypeList 
     */
    async formatNewHouseTypeList(newHouseInfo) {
        const { ctx, service } = this;
        let newHouseTypeList = newHouseInfo.newHouseType;
        //数据格式化
        let retList = [];
        if (newHouseTypeList.length > 0) {
            let taskList = [];
            for (let i in newHouseTypeList) {
                newHouseTypeList[i].houseType = newHouseInfo.houseType;
                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;
        const saleType = { 0: '未开售', 1: '售罄', 2: '预售', 3: '在售' };
        const houseType = { 1: '住宅', 2: '公寓' };
        let ret = {};
        if (Object.keys(data).length > 0) {
            ret = {
                id: data.id,
                newHouseId: data.newHouseId,
                type: data.type,//类型，如三居、四居
                house_type: houseType[data.houseType] || '',
                image: data.image,
                apartment: data.apartment,//户型，如4室2厅3卫
                sale_type: saleType[data.saleType] || '',
                area: data.area,//面积
                orientation: data.orientation,//朝向
                num: data.num,//房源数量
                price: data.price === 0 ? '--' : data.price,//价格
                discount: data.discount,//折扣
                tag: data.tags ? eval(data.tags) : [],//特点
            }
        }
        return ret;
    }


    /**
     * 新房根据条件筛选
     * @param {*} condition 
     */
    async getNewHouseList(condition) {
        const { ctx, service } = 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 = {
            pageIndex: page,
            pageSize: pageSize,
            queryConditions: [{
                key: "state",
                value: 0,
                operator: "notEqual"
            }],
            orderConditions: [],
        }
        //根据筛选项增加不同的指定类型
        if (condition.hasOwnProperty('type') && condition.type !== '') {
            if (type === 'home') {
                //为您推荐只展示50条在售楼盘的数据，根据排序序号取数，数字小的排在前面，数字一样的情况下根据时间逆序排列，时间也一样的情况下随机排列；
                filter.pageSize = Number(condition.page_size) || 50;
                filter.orderConditions.push({
                    key: 'orderNum',
                    orderSequence: 'asc',
                }, {
                        key: 'createdAt',
                        orderSequence: 'desc',
                    });
            } else if (type === 'all') {
                filter.orderConditions.push({
                    key: 'saleType',
                    orderSequence: 'desc',
                });
            } else if (type === 'sale') {
                //点击在售楼盘进入列表页面且只展示当前销售状态为在售的楼盘
                filter.queryConditions.push({
                    key: "saleType",
                    value: '3',
                    operator: "equal"
                });
            } else if (type === 'open') {
                //只展示最近三个月内开盘的楼盘，往前追溯三个月,列表单次加载30条楼盘数据，滑到底部再次加载30条
                let endDate = moment().subtract(90, 'days').format('YYYY-MM-DD HH:mm:ss');
                filter.queryConditions.push({
                    key: "openDate",
                    value: endDate,
                    operator: "greater"
                });
                filter.orderConditions.push({
                    key: 'saleType',
                    orderSequence: 'desc',
                })
            } else if (type === 'favourable') {
                //点击优惠好盘只展示有优惠的楼盘,列表单次加载30条楼盘数据，滑到底部再次加载30条
                filter.queryConditions.push({
                    key: "favourableInfo",
                    value: false,
                    operator: "isnull"
                });
                filter.orderConditions.push({
                    key: 'saleType',
                    orderSequence: 'desc',
                });
            }
        }

        //是否有值来增加筛选项
        if (condition.unit_price && condition.unit_price.hasOwnProperty('min') && condition.unit_price.hasOwnProperty('max')) {//单价
            filter.queryConditions.push(
                {
                    key: 'referenceAvgPrice',
                    value: condition.unit_price.min,
                    operator: 'greaterEqual',
                },
                {
                    key: 'referenceAvgPrice',
                    value: condition.unit_price.max,
                    operator: 'lessEqual',
                }
            );
        }
        //里面的min和max也需要判断
        if (condition.total_price && condition.total_price.hasOwnProperty('min') && condition.total_price.hasOwnProperty('max')) {//总价
            filter.queryConditions.push(
                {
                    key: 'referenceTotalPrice',
                    value: condition.total_price.min,
                    operator: 'greaterEqual',
                },
                {
                    key: 'referenceTotalPrice',
                    value: condition.total_price.max,
                    operator: 'lessEqual',
                }
            );
        }
        if (condition.area && condition.area.hasOwnProperty('min') && condition.area.hasOwnProperty('max')) {//面积
            filter.queryConditions.push(
                {
                    key: 'area',
                    value: condition.area.min + ',' + condition.area.max,
                    operator: 'between',
                },
            );
        }
        if (condition.house_type) {//户型
            filter.queryConditions.push({
                key: 'type',
                value: condition.house_type,
                operator: 'equal',
            });
        }
        if (condition.name) {//关键词搜索 模糊查询
            //增加搜索历史
            let addHistory = {
                type: 1,
                key_word: condition.name
            };
            await service.house.searchHistory.addSearchHistory(addHistory);
            filter.queryConditions.push({
                key: 'name',
                value: condition.name,
                operator: 'contains',
            });
        }
        if (condition.area_code) {//城市\区域\商圈筛选
            if (condition.area_code.hasOwnProperty('city_code') && condition.area_code.city_code !== '') {
                filter.queryConditions.push({
                    key: 'city',
                    value: condition.area_code.city_code,
                    operator: 'equal',
                });
            }
            if (condition.area_code.hasOwnProperty('district_code') && condition.area_code.district_code !== '') {
                filter.queryConditions.push({
                    key: 'county',
                    value: condition.area_code.district_code,
                    operator: 'equal',
                });
            }
            if (condition.area_code.hasOwnProperty('bizcircle_code') && condition.area_code.bizcircle_code !== '') {
                filter.queryConditions.push({
                    key: 'region',
                    value: condition.area_code.bizcircle_code,
                    operator: 'equal',
                });
            }
        }
        let newHouseList = await service.houseCommon.newHouse.all(filter);
        let list = [];
        if (newHouseList.rowCount > 0) {
            for (let i in newHouseList.results) {
                let tmp = {
                    id: newHouseList.results[i].id,
                    name: newHouseList.results[i].name,
                    address: newHouseList.results[i].address,
                    tags: newHouseList.results[i].tags ? eval(newHouseList.results[i].tags) : [],
                    image: newHouseList.results[i].image,
                    price: newHouseList.results[i].referenceAvgPrice === 0 ? '--' : newHouseList.results[i].referenceAvgPrice,
                    corner: newHouseList.results[i].cornerMarker,
                };
                list.push(tmp);
            }
        }
        let ret = {
            results: list,
            count: newHouseList.rowCount
        };
        return ret;
    }

}

module.exports = NewHouseService;
