
'use strict';

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

class OrderService extends Service {

    /**
     * 添加预约信息
     * @param {object} inputParams 
     */
    async addOrder(inputParams) {
        const { ctx } = this;
        if (!ctx.appUserId || !ctx.userId) {
            //如果没有登录就不做处理
            return false;
        }
        let filter = {
            where: {
                state: 1,
                user_id: ctx.userId,
                connect_id: inputParams.id,
                house_style: inputParams.type,
            },
            order: [['created_at', 'desc']],
        }
        let orderHistory = await ctx.realestateModel.Order.all(filter);
        if (orderHistory.length > 0) {
            let ret = {
                id: orderHistory[0].id,
                msg: '已经预约过',
            };
            return ret;
        }
        let data = {
            user_id: ctx.userId,
            app_user_id: ctx.appUserId,
            app_id: ctx.appId,
            app_type_id: ctx.appTypeId,
            house_style: inputParams.type,
            connect_id: inputParams.id,
            name: inputParams.name,
            phone: inputParams.phone,
            order_at: inputParams.time,
            state: 1,
        };
        let retId = await ctx.realestateModel.Order.add(data);
        return { id: retId, msg: '预约成功' };
    }

    /**
     * 获取预约列表  保留最近6个月的记录，条数不超过50条
     */
    async getOrderList() {
        const { ctx } = this;
        if (!ctx.userId) {
            return {
                results: [],
                count: 0
            };
        }
        let endDate = moment().subtract(6, 'months').format('YYYY-MM-DD HH:mm:ss');
        let filter = {
            page: 1,
            limit: 50,
            where: {
                state: 1,
                user_id: ctx.userId,
                created_at: { $gt: endDate }
            },
            order: [['id', 'desc']]
        }
        let list = [];
        let orderList = await ctx.realestateModel.Order.all(filter);
        if (orderList.length > 0) {
            //整理所有预约记录
            let taskList = [];
            for (let i in orderList) {
                if (orderList[i].house_style === 1) {
                    taskList[i] = ctx.realestateModel.NewHouse.one({ where: { id: orderList[i].connect_id } });
                } else {
                    taskList[i] = ctx.realestateModel.RentalHouse.one({ where: { id: orderList[i].connect_id } });
                }
            }
            let retList = await Promise.all(taskList).then(result => {
                return result;
            }).catch(error => {
                ctx.failed(error);
            });
            //数据整理
            for (let j in retList) {
                if (retList[j].status === 'offline' || Number(retList[j].valid) === 0) {
                    continue;
                }
                let type = orderList[j].house_style;
                let tmp = {
                    id: retList[j].id,
                    name: retList[j].name,
                    address: retList[j].address,
                    tags: retList[j].tags ? eval(retList[j].tags) : [],
                    image: retList[j].image,
                    area: type === 1 ? Number(retList[j].residential_house_area) : '',
                    price: type === 1 ? (Number(retList[j].reference_avg_price) === 0 ? '--' : Number(retList[j].reference_avg_price)) : Number(retList[j].price),
                    time: moment().format('YYYY-MM-DD') === moment(orderList[j].order_at).format('YYYY-MM-DD') ? '今天' : moment(orderList[j].order_at).format('YYYY-MM-DD'),
                    type: type === 1 ? 'new_house' : 'rental_house',
                    corner: type === 1 ? retList[j].corner : '',
                };
                list.push(tmp);
            }
        }
        let ret = {
            results: list,
            count: list.length
        };
        return ret;
    }

    /**
     * 我的-获取预约个数
     */
    async getOrderCount() {
        const { ctx } = this;
        if (!ctx.userId) {
            return { count: 0 };
        }
        let endDate = moment().subtract(6, 'months').format('YYYY-MM-DD HH:mm:ss');
        let filter = {
            page: 1,
            limit: 50,
            attributes: ['connect_id', 'house_style'],
            where: {
                state: 1,
                user_id: ctx.userId,
                created_at: { $gt: endDate },
            },
            order: [['id', 'desc']]
        }
        let list = await ctx.realestateModel.Order.findAll(filter);
        let count = 0;
        if (list.length > 0) {
            let newHouseId = [];
            let rentalHouseId = [];
            for (let i in list) {
                if (Number(list[i].house_style) === 1) {
                    newHouseId.push(list[i].connect_id);
                }
                if (Number(list[i].house_style) === 2) {
                    rentalHouseId.push(list[i].connect_id);
                }
            }
            let newHousefilter = {
                where: {
                    status: 'online',
                    valid: 1,
                    id: { $in: newHouseId },
                },
            }
            let newHouseCountTask = ctx.realestateModel.NewHouse.count(newHousefilter);
            let rentalHousefilter = {
                where: {
                    status: 'online',
                    valid: 1,
                    id: { $in: rentalHouseId },
                },
            }
            let rentalHouseCountTask = ctx.realestateModel.RentalHouse.count(rentalHousefilter);
            const retList = await Promise.all([newHouseCountTask, rentalHouseCountTask]).then(result => {
                return result;
            }).catch(error => {
                ctx.failed(error);
            });
            count = Number(retList[0]) + Number(retList[1]);
        }
        let ret = {
            count: count
        };
        return ret;
    }



}

module.exports = OrderService;
