const express = require("express");
const joi = require("joi");
const router = express.Router();


router.get('/userId/:userId', (req, res) => {
    const userId = req.params.userId;
    const { error } = joi.number().validate(userId);
    if (error) {
        return res.status(400).send('Invalid userID');
    }
    res.send(`User Id is ${userId}`);
});

router.get('/userName', (req, res) => {
    const { name } = req.query;
    const schema = joi.object({
        name: joi.string().min(2).max(20).required()
    });
    const { error } = schema.validate({ name });
    if (error) {
        return res.status(400).send('Invalid user name');
    }
    res.send(`User name is ${name}`);
});


router.get('/profile', (req, res) => {
    res.send('This is the user profile page.');
});

router.get('/profile/settings', (req, res) => {
    res.send('This is the user profile settings page.');
});


const scores = [
    { name: 'zs', course: 'app', score: 90 },
    { name: 'zs', course: 'java', score: 80 },
    { name: 'ls', course: 'app', score: 89 },
    { name: 'ls', course: 'java', score: 99 },
    { name: 'ww', course: 'app', score: 78 },
    { name: 'ww', course: 'java', score: 88 },
];

router.get('/myScore', (req, res) => {
    const name = req.query.name;
    const result = scores.filter(s => s.name === name);
    res.json({ name, scores: result });
});

router.get('/showScore', (req, res) => {
    const sorted = [...scores].sort((a, b) => a.score - b.score);
    const avg = {};
    scores.forEach(s => {
        avg[s.name] = (avg[s.name] || { total: 0, count: 0 });
        avg[s.name].total += s.score;
        avg[s.name].count++;
    });
    const avgResult = Object.entries(avg).map(([name, data]) => ({
        name,
        average: data.total / data.count
    }));
    res.json({ "升序排列": sorted, "平均分": avgResult });
});

const moneys = [
    { name: '张三', mny: '9k' },
    { name: '李四', mny: 15000 },
    { name: '王五', mny: '1w' },
    { name: '随便', mny: 6666 }
];


router.get('/filterMoney', (req, res) => {
    const parse = (mny) => {
        if (typeof mny === 'number') return mny;
        if (mny.endsWith('k')) return parseFloat(mny) * 1000;
        if (mny.endsWith('w')) return parseFloat(mny) * 10000;
        return 0;
    };

    const result = moneys
        .map(item => ({ ...item, num: parse(item.mny) }))
        .filter(item => item.num >= 9000)
        .sort((a, b) => b.num - a.num);
    res.json(result);
});

module.exports = router;