const dayjs = require('dayjs');
const db = require('./db')
const router = require('express').Router();

// 完整的请求接口地址： /api/comment/web/query
router.all('/web/query', async (req, res) => {
    let id = req.query['id']; // 获取要查询文章的编号
    if (!id || id < 1) {
        // 参数不正确 直接返回空数组
        res.send([])
    } else {
        const list = await db.query('select * from comment where article_id =? order by id desc', [id]);
        // 循环所有的列表 将ip->address
        Array.from(list).forEach(c => {
            c.address = getIpAddress(c.ip);
        });
        res.send(list)
    }
});
// 发表评论
router.post('/web/add', async (req, res) => {
    let commentData = req.body; // 获取到post的json数据 
    console.log(commentData)
    if (!commentData || !commentData.article_id || !commentData.content) {
        res.send({ status: false, message: "参数不对" })
    } else {
        try {
            // 发表时间
            commentData.publish_time = dayjs().format("YYYY-MM-DD HH:mm:ss")
            // 评论者ip
            commentData.ip = getIp(req.ip);
            console.log(commentData)
            await db.query('insert into comment set ?', commentData);
            db.query('update article set comment_count=comment_count + 1 where id=?',
            [commentData.article_id])
            res.send({ status: true })
        } catch (e) {
            console.log(e)
            res.send({ status: false, message: e.message })
        }
    }
});
function getIp(ip) {
    const ipPatch = ip.match(/\d+\.\d+\.\d+\.\d+/)
    if (ipPatch) return ipPatch[0]
    return ip;
}
// npm i ip2region 
const IP2Region = require("ip2region").default; // 引用依赖库
const query = new IP2Region(); // 实例化库
// 根据ip查询归属地
function getIpAddress(ip) {
    const result = query.search(ip);
    if (result.isp == '本机地址' || result.isp == '内网IP') {
        return '内部网络';
    }
    if (!result.province) return result.country;
    return (result.country != '中国' ? result.country + "-" : '') + result.province + "-" + result.city;
}


router.get('/ip', (req, res) => {
    res.send(getIp(req.ip))
})
module.exports = router