const express = require('express');
const Mysql = require('../SQLPool')
const router = express.Router();


const ErrorCode = {
    USER_NOT_LOGIN: 70001
}

/* GET users listing. */
router.get('/getUser', function (req, res, next) {
    let {uid} = req.cookies
    if (!uid){
        uid = req.query.uid
    }
    // if (!uid) {
    //     res.send({
    //         success: false,
    //         code: ErrorCode.USER_NOT_LOGIN,
    //         data: '用户尚未登录'
    //     })
    //     return
    // }
    const SQL = 'SELECT * FROM `user` WHERE `user`.uid = ?'
    Mysql.query(SQL, [uid], (err, result) => {
        if (err || !result || !result.length) {
            res.send({
                success: false,
                err
            })
           return
        }
        console.log(result)
        const _result = result.slice()
        _result[0].follow = JSON.parse(_result[0].follow)
        res.send({
            success: true,
            data: {
                ..._result[0],
            }
        })
    })
});

router.get('/login', (req, res) => {
    const {uid} = req.query
    const SQL = 'SELECT * FROM `user` WHERE `user`.uid = ?'
    Mysql.query(SQL, [uid], (err, result) => {
        if (err) {
            res.send({
                success: false,
                err
            })
            throw err
        }
        if (!!result && result[0].uid) {
            res.cookie('uid', result[0].uid)
            res.send({
                success: true,
                data: '登录成功！'
            })
        } else {
            res.send({
                success: false,
                data: '登录失败，用户不存在'
            })
        }
    })
})

router.get('/follow', (req, res) => {
    const {follow, uid} = req.query
    const SQL = 'UPDATE user SET follow = ? WHERE uid = ?'
    Mysql.query(SQL, [follow, uid], (err, result) => {
        if (err) {
            res.send({
                success: false,
                err
            })
            return
        }
        res.send({
            success: true,
        })
    })
})

module.exports = router;
