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

router.get("/userId/:userId", (req, res) => {
    const userId = req.params.userId;
    const { err } = joi.number().validate(userId);
    if (err) {
        return res.status(400).send("Invaild 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("Invaild UserName");
    }
    res.send(`User name is ${name}`)
})

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

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

// 提升部分一
const data = [
    { 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("/myScoure", (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("Invaild Name.");
    }

    const dataGroup = lodash(data).groupBy("name").get(name)
    res.send(dataGroup)
})

router.get("/showScoure", (req, res) => {
    const dataOrder = lodash.orderBy(data, ["score"], orders = "desc");
    console.log("排序输出: \n", dataOrder);
    const dataGroup = lodash(data).groupBy("name").map((a) => {
        return {
            name: a[0].name,
            avg: lodash.mean(a.map(e => e.score)),
        }
    })

    res.send(dataGroup);
})

// 提升部分二
router.get("/mny", (_req, res) => {
    const mnyData = [
        { name: '张三', mny: '9k' },
        { name: '随便', mny: 6666 },
        { name: '王五', mny: '1w' },
        { name: '李四', mny: 15000 },
    ]
    const fixData = mnyData.map((d) =>
        typeof d.mny === "string"
            ? {
                name: d.name,
                mny: parseInt(d.mny = d.mny.endsWith("w") ?
                    parseInt(d.mny) * 10000 :
                    d.mny.endsWith("k") ?
                        parseInt(d.mny) * 1000 :
                        parseInt(d.mny))
            }
            : {
                name: d.name,
                mny: parseInt(d.mny)
            }
    )

    const finalData = fixData.filter(d => lodash.gte(d.mny, 9000));

    res.send(finalData)
})

module.exports = {
    router
}

