
'use strict';

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

class CollectionService extends Service {

    /**
     * 添加关注
     * @param {object} inputParams 
     */
    async addCollection(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: [],
        }
        let collectionHistory = await service.houseCommon.collection.all(filter);
        if (collectionHistory.rowCount > 0) {
            ctx.failed('已经关注过啦');
        }
        let data = {
            userId: ctx.userId,
            appUserId: ctx.appUserId,
            houseStyle: inputParams.type,
            connectId: inputParams.id,
            state: 1,
            remark: inputParams.remark || ''
        }
        let ret = await service.houseCommon.collection.add(data);
        return { id: ret.id };
    }

    /**
     * 取消关注
     * @param {object} inputParams 
     */
    async unCollection(inputParams) {
        const { ctx, service } = this;
        let ret = { status: true };
        if (!ctx.appUserId || !ctx.deviceId || !ctx.deviceLoginId || !ctx.userId) {
            //如果没有登录就不做处理
            return ret;
        }
        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: [],
        }
        let collectionHistory = await service.houseCommon.collection.all(filter);
        if (collectionHistory.rowCount > 0) {
            await service.houseCommon.collection.delete(collectionHistory.results[0].id);
        }

        return ret;
    }

    /**
     * 获取用户关注信息
     * @param {object} inputParams 
     */
    async getCollection(inputParams) {
        const { ctx, service } = this;
        if (!inputParams.hasOwnProperty('type')) {
            ctx.failed("empty house type");
        }
        if (!inputParams.hasOwnProperty('id')) {
            ctx.failed("empty house id");
        }
        if (!ctx.userId) {
            return {
                results: [],
                rowCount: 0
            };
        }
        let userId = ctx.userId;
        let filter = {
            pageIndex: 1,
            pageSize: 999,
            queryConditions: [{
                key: "state",
                value: '1',
                operator: "equal"
            }, {
                key: "houseStyle",
                value: inputParams.type,
                operator: "equal"
            }, {
                key: "connectId",
                value: inputParams.id,
                operator: "equal"
            }, {
                key: "userId",
                value: userId,
                operator: "equal"
            }],
            orderConditions: [],
        }
        let ret = await service.houseCommon.collection.all(filter);
        return ret;
    }


    /**
     * 获取关注列表  保留最近6个月的记录，条数不超过50条
     * @param {object} condition 
     */
    async getCollectionList() {
        const { ctx, service } = this;
        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 collectionList = await service.houseCommon.collection.all(filter);
        if (collectionList.rowCount > 0) {
            //整理所有收藏
            let taskList = [];
            for (let i in collectionList.results) {
                if (collectionList.results[i].houseStyle === 1) {//1新房2租房 后续根据情况添加
                    taskList[i] = service.houseCommon.newHouse.one(collectionList.results[i].connectId);
                } else {
                    taskList[i] = service.houseCommon.rentalHouse.one(collectionList.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 = collectionList.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,
                    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;
    }


    /**
     * 给我的页面使用 只需要count
     */
    async getCollectionCount() {
        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 collectionList = await service.houseCommon.collection.all(filter);
        let ret = {
            count: collectionList.rowCount
        };
        return ret;
    }

}

module.exports = CollectionService;
