const express = require('request-promise');
const user = require('../db/mongo/user');
const upstream = require('../db/mongo/upstream');
const moment = require('moment');
const UserAuth = require('../db/mongo/user-auto-auth');
const UpstreamUnbindHistory = require('../db/mongo/upstream-unbind-history');

const mongoose = require('mongoose');

exports.data = async (req,res,next) => {
	let {start,end} = req.body;
	const condition = {'$and': [{'createdAt': {'$gte': moment(start, 'YYYYMMDD').startOf('day').toDate()}}, {'createdAt': {'$lt': moment(end, 'YYYYMMDD').endOf('day').toDate()}}]};
	const basicCondition = {'createdAt': {'$lt': moment(start, 'YYYYMMDD').startOf('day').toDate()}};
	console.dir(condition['$and']);
	console.dir(basicCondition);
	const pipeline = [
        {'$match': condition},
        {'$project':
        	{
		        "year": { "$year": { "$add": [ "$createdAt", 8 * 60 * 60 * 1000 ] } }, 
		        "month": { "$month": { "$add": [ "$createdAt", 8 * 60 * 60 * 1000 ] } }, 
		        "day": { "$dayOfMonth": { "$add": [ "$createdAt", 8 * 60 * 60 * 1000 ] } } 
		    }
		},
        {
            '$group': {
                _id:{ month: '$month', day:'$day', year:'$year'},
                count: {$sum: 1}
            }
        }
    ];

    const userPromise = await user.aggregate(pipeline);
    const basicUserPromise = await user.count(basicCondition);
    const upstreamPromise =  await upstream.aggregate(pipeline);
    const basicUpstreamPromise = await upstream.count(basicCondition);

    let userResult = [];
    let upstreamsResult = [];
    let userCount = 0;
    let upCount = 0;
    await Promise.all([userPromise,basicUserPromise,upstreamPromise,basicUpstreamPromise]).then( ([users,userCon,upstreams,upCon]) => {
    	userResult = users;
    	upstreamsResult = upstreams;
    	userCount = userCon;
    	upCount = upCon;
    });
	res.send({result: 'ok' ,data: {userCount: userCount, upCount: upCount, users: userResult, upstreams: upstreamsResult, range:[start,end]}})
};

exports.count = async(req,res,next) => {

	const userPromise = await user.count({});
    const upstreamPromise =  await upstream.count({_id: {$exists: true}});
    const adminPromise =  await upstream.count({ creater:mongoose.Types.ObjectId('58afdd80aa96916a41598698') });
    let userCount= 0;
    let upstreamCount = 0;
    let adminCount = 0;
    await Promise.all([userPromise,upstreamPromise,adminPromise]).then( ([users,upstreams,admin]) => {
    	userCount = users;
    	upstreamCount = upstreams;
        adminCount = admin;
    });
    res.send({result: 'ok' ,data: {user: userCount, upstream: upstreamCount, admin: adminCount}})

}



exports.detail = async(req,res,next) => {
    let { limit = 30 , skip = 0} = req.body;
    try{ 
        const users = await user.find({},null,{limit: parseInt(limit),skip: parseInt(skip)*30}).sort({createdAt: -1});
        const total = await user.count({},null);
        let creaters = [];
        users.forEach( item => {
            creaters.push(item['_id'])
        });
        const pipeline = [
            {'$match': { creater: {'$in': creaters} }},
            {
                '$group': {
                    _id:{ creater: '$creater' },
                    count: { $sum: 1 }
                }
            }
        ];

        const unbindPipeline = [
            {'$match': { userId: {'$in': creaters} }},
            {
                '$group': {
                    _id:{ userId: '$userId' },
                    count: { $sum: 1 }
                }
            }
        ];

        const upstreamPromise =  await upstream.aggregate(pipeline);
        const authPromise = await UserAuth.find({userId: {'$in': creaters}}).limit(300);
        const upstreamUnbindHistoryPromise = await UpstreamUnbindHistory.aggregate(unbindPipeline);

        let upstreams = [];
        let auths = [];
        let unbindhistorys = 0
        await Promise.all([upstreamPromise, authPromise, upstreamUnbindHistoryPromise]).then( ([_upstreams, _auths, _unbindhistorys]) => {
            upstreams = _upstreams;
            auths = _auths;
            unbindhistorys = _unbindhistorys;
        });
        res.send({result: 'ok' ,data: { users: users.map(x => x.toJSON()), upstreams: upstreams,auths: auths,unbindhistorys: unbindhistorys, pagination:{ current:parseInt(skip)+1,total: total, pageSize:parseInt(limit)}}})
    } catch ( err ) {
        console.dir(err);
        res.status(400);
    }
}