const API = require("../../../lib/API")
const db = require("../../../plugin/DataBase/db")
const AccessControl = require("../../../lib/AccessControl")
const { BaseStdResponse } = require("../../../BaseStdResponse")

class GetRecordDetail extends API {
    constructor() {
        super();

        this.setPath('/Lepao/GetRecordDetail')
        this.setMethod('GET')
    }

    async onRequest(req, res) {
        let {
            uuid,
            session,
            id
        } = req.query

        if ([uuid, session, id].some(value => value === '' || value === null || value === undefined))
            return res.json({
                ...BaseStdResponse.MISSING_PARAMETER
            })

        // 检查 session
        if (!await AccessControl.checkSession(uuid, session))
            return res.status(401).json({
                ...BaseStdResponse.ACCESS_DENIED
            })

        let sql = `
                SELECT 
                    r.time,
                    r.path_data,
                    r.area,
                    r.startTime,
                    r.endTime,
                    r.distance,
                    r.state,
                    r.lepao_account,
                    a.name
                FROM 
                    lepao_record r
                LEFT JOIN 
                    lepao_account a
                ON 
                    r.lepao_account = a.student_num
                WHERE 
                    (r.uuid = ? OR (a.create_user IS NOT NULL AND a.create_user = ?)) AND r.id = ? AND r.state = 1
            `
        let rows = await db.query(sql, [uuid, uuid, id])

        if (!rows)
            return res.json({
                ...BaseStdResponse.MISSING_FILE,
                msg: '获取记录数据失败！'
            })

        if(rows.length === 0) 
           return res.json({
                ...BaseStdResponse.MISSING_FILE,
                msg: '记录不存在或已被删除！'
            }) 

        let data = rows[0]
        data.distance = Number(data.distance).toFixed(2)

        res.json({
            ...BaseStdResponse.OK,
            data
        })
    }
}

module.exports.GetRecordDetail = GetRecordDetail