
'use strict';

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

class OrderService extends Service {

    /**
     * 添加预约信息
     * @param {object} inputParams 
     */
    async addOrder(inputParams) {
        const { ctx, service } = this;

        let filter = {
            pageIndex: 1,
            pageSize: 999,
            queryConditions: [{
                key: "state",
                value: 1,
                operator: "equal"
            }, {
                key: "userId",
                value: ctx.userId,
                operator: "equal"
            }, {
                key: "connectId",
                value: inputParams.id,
                operator: "equal"
            }, {
                key: "houseStyle",
                value: inputParams.type,
                operator: "equal"
            },
            ],
            orderConditions: [{
                key: 'createdAt',
                orderSequence: 'desc',
            }],
        }
        let orderHistory = await service.houseCommon.order.all(filter);
        if (orderHistory.rowCount > 0) {
            let ret = {
                id: orderHistory.results[0].id,
                msg: '已经预约过',
            };
            return ret;
        }
        let data = {
            userId: ctx.userId,
            appUserId: ctx.appUserId,
            houseStyle: inputParams.type,
            connectId: inputParams.id,
            name: inputParams.name,
            phone: inputParams.phone,
            orderAt: inputParams.time,
            state: 1,
            remark: inputParams.remark || ''
        };
        let ret = await service.houseCommon.order.add(data);
        return { id: ret.id, msg: '预约成功' };
    }

    /**
     * 获取预约列表  保留最近6个月的记录，条数不超过50条
     */
    async getOrderList() {
        const { ctx, service } = this;
        if (!ctx.userId) {
            return {
                results: [],
                rowCount: 0
            };
        }
        let endDate = moment().subtract(180, 'days').format('YYYY-MM-DD HH:mm:ss');
        let filter = {
            pageIndex: 1,
            pageSize: 50,
            queryConditions: [{
                key: "state",
                value: 1,
                operator: "equal"
            }, {
                key: "userId",
                value: ctx.userId,
                operator: "equal"
            }, {
                key: "createdAt",
                value: endDate,
                operator: "greater"
            },
            ],
            orderConditions: [{
                key: 'createdAt',
                orderSequence: 'desc',
            },],
        }

        let list = [];
        let orderList = await service.houseCommon.order.all(filter);
        if (orderList.rowCount > 0) {
            //整理所有预约记录
            let taskList = [];
            for (let i in orderList.results) {
                if (orderList.results[i].houseStyle === 1) {
                    taskList[i] = service.houseCommon.newHouse.one(orderList.results[i].connectId);
                } else {
                    taskList[i] = service.houseCommon.rentalHouse.one(orderList.results[i].connectId);
                }
            }

            let retList = await Promise.all(taskList).then(result => {
                return result;
            }).catch(error => {
                ctx.failed(error);
            });
            //数据整理
            for (let j in retList) {
                let type = orderList.results[j].houseStyle;
                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 ? retList[j].houseArea : '',
                    price: type === 1 ? (retList[j].referenceAvgPrice === '' || retList[j].referenceAvgPrice === 0 ? '--' : retList[j].referenceAvgPrice) : retList[j].price,
                    time: moment().format('YYYY-MM-DD') === moment(orderList.results[j].orderAt).format('YYYY-MM-DD') ? '今天' : moment(orderList.results[j].orderAt).format('YYYY-MM-DD'),
                    type: type === 1 ? 'new_house' : 'rental_house',
                    corner: type === 1 ? retList[j].cornerMarker : '',
                };
                list.push(tmp);
            }
        }
        let ret = {
            results: list,
            count: list.length
        };
        return ret;
    }

    /**
     * 我的-获取预约个数
     */
    async getOrderCount() {
        const { ctx, service } = this;
        if (!ctx.userId) {
            return { count: 0 };
        }
        let endDate = moment().subtract(180, 'days').format('YYYY-MM-DD HH:mm:ss');
        let filter = {
            pageIndex: 1,
            pageSize: 50,
            queryConditions: [{
                key: "state",
                value: 1,
                operator: "equal"
            }, {
                key: "userId",
                value: ctx.userId,
                operator: "equal"
            }, {
                key: "createdAt",
                value: endDate,
                operator: "greater"
            },
            ],
            orderConditions: [{
                key: 'createdAt',
                orderSequence: 'desc',
            },],
        }

        let orderList = await service.houseCommon.order.all(filter);
        let ret = {
            count: orderList.rowCount
        };
        return ret;
    }



}

module.exports = OrderService;
