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

class GetBookImg extends API {
    constructor() {
        super()

        this.setPath("/QXS/GetBookImg")
        this.setMethod("GET")

        this.key = '5a01e72642f02bd0721a56a2bc1dd81a'
    }

    async getImg(isbn) {
        const endpoint = `https://api.tanshuapi.com/api/isbn_base/v1/index?key=${this.key}&isbn=${isbn}`
        const res = await axios.get(endpoint, {
            proxy: false
        })

        const data = res.data
        if (!data || data.code !== 1) {
            if(data?.msg === '查无记录')
                return { img: '', pubdate: '', summary: '' }
            throw new Error(data?.msg ?? "请稍后再试")
        }
        const { img, pubdate, summary } = data.data
        return { img, pubdate, summary }
    }

    async onRequest(req, res) {
        const { isbn } = req.query

        if (!isbn || isbn.length !== 13) {
            return res.json({
                ...BaseStdResponse.MISSING_PARAMETER,
                msg: "请提供正确的ISBN号"
            })
        }

        try {
            let sql = 'SELECT img, pubdate, summary FROM book_img WHERE isbn = ?'
            let rows = await db.query(sql, [isbn])

            let img, pubdate, summary
            if (!rows || rows.length === 0) {
                ({ img, pubdate, summary } = await this.getImg(isbn))

                const time = Date.now()
                sql = 'INSERT INTO book_img SET isbn = ?, img = ?, pubdate = ?, summary = ?, create_time = ?'
                await db.query(sql, [isbn, img ?? '', pubdate ?? '', summary ?? '', time])
            }
            else
                ({ img, pubdate, summary } = rows[0])

            res.json({
                ...BaseStdResponse.OK,
                data: { img, pubdate, summary }
            })
        } catch (error) {
            this.logger?.error(`${error.stack}`)
            return res.json({
                ...BaseStdResponse.ERR,
                msg: `${error.message ?? "请稍后再试"}`
            })
        }
    }
}

module.exports.GetBookImg = GetBookImg
