const API = require("../../../lib/API")
const db = require("../../../plugin/DataBase/db")
const AccessControl = require("../../../lib/AccessControl")
const { BaseStdResponse } = require("../../../BaseStdResponse")
const { enrichLepaoRecordRow, stripInternalRecordId } = require("../../../plugin/jkes/formatRecordRow.js")

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

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

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

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

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

        const baseWhere = `
            FROM 
                lepao_record r
            LEFT JOIN 
                lepao_account a
            ON 
                r.lepao_account = a.student_num
            LEFT JOIN
                path_data p
            ON 
                r.path_id = p.id
            WHERE 
                (r.uuid = ? OR (a.create_user IS NOT NULL AND a.create_user = ?)) AND r.public_id = ?
        `
        let rows
        try {
            const sql = `
                SELECT 
                    r.id,
                    r.public_id,
                    r.time,
                    r.result,
                    r.state,
                    r.run_mode,
                    r.lepao_account,
                    r.path_id,
                    r.path_data AS run_path_data,
                    a.name,
                    p.data,
                    p.run_zone_name,
                    p.run_zone_name AS path_run_zone_name,
                    NULL AS path_distance
                ${baseWhere}
            `
            rows = await db.query(sql, [uuid, uuid, public_id])
        } catch (e) {
            if (!(e?.message || '').includes("Unknown column 'r.path_data'")) throw e
            const sql = `
                SELECT 
                    r.id,
                    r.public_id,
                    r.time,
                    r.result,
                    r.state,
                    r.run_mode,
                    r.lepao_account,
                    r.path_id,
                    r.point_data AS run_path_data,
                    a.name,
                    p.data,
                    p.run_zone_name,
                    p.run_zone_name AS path_run_zone_name,
                    NULL AS path_distance
                ${baseWhere}
            `
            rows = await db.query(sql, [uuid, uuid, public_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]
        let pathLine = []
        const rawRunPath = data.run_path_data
        if (rawRunPath != null) {
            let arr = rawRunPath
            if (typeof rawRunPath === 'string') {
                try {
                    arr = JSON.parse(rawRunPath)
                } catch {
                    arr = null
                }
            }
            if (Array.isArray(arr)) {
                pathLine = arr.map((point) => [point.longitude ?? point.o, point.latitude ?? point.a])
            }
        }
        if (!pathLine.length) {
            const rawPath = data.data
            if (rawPath != null) {
                let arr = rawPath
                if (typeof rawPath === 'string') {
                    try {
                        arr = JSON.parse(rawPath)
                    } catch {
                        arr = null
                    }
                }
                if (Array.isArray(arr)) {
                    pathLine = arr.map((point) => [point.o, point.a])
                }
            }
        }
        data.path_polyline = pathLine
        delete data.data
        delete data.run_path_data

        const enriched = await enrichLepaoRecordRow({
            id: data.id,
            state: data.state,
            result: data.result
        })
        data.jkes_record = enriched.jkes_record
        if (enriched.lepao_schedule != null) {
            data.lepao_schedule = enriched.lepao_schedule
        }
        if (enriched.schedule != null) {
            data.schedule = enriched.schedule
        }

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

module.exports.GetRecordDetail = GetRecordDetail
