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

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

        this.setPath("/QXS/GetBookList")
        this.setMethod("POST")

        this.UserAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x63090a13) UnifiedPCWindowsWechat(0xf254100e) XWEB/16283'
        this.Refer = 'https://servicewechat.com/wxeadc3e8bceec3d03/177/page-frame.html'
    }

    async qxsLogin(username, password) {
        const endpoint = "https://api.quxuanshu.com/pass/login"
        const reqData = {
            account: username,
            password,
            loginMethod: 0,
            isAutoLogin: "0",
            multiUserType: "0,1,2,3,4,5"
        }

        const res = await axios.post(endpoint, reqData, {
            proxy: false,
            headers: {
                "User-Agent": this.UserAgent,
                "Referer": this.Refer
            }
        })

        const data = res.data
        if (!data || data.code !== 0 || !data.data?.accessToken) {
            throw new Error(data?.msg ?? "请稍后再试")
        }
        return { accessToken: data.data.accessToken, userId: data.data.userId }
    }

    async qsxUserInfo(accessToken) {
        const endpoint = "https://api.quxuanshu.com/pass/loginInfo"
        const res = await axios.get(endpoint, {
            proxy: false,
            headers: {
                accessToken,
                "User-Agent": this.UserAgent,
                "Referer": this.Refer,
            }
        })
        const data = res.data
        if (!data || data.code !== 0 || !data.data) {
            throw new Error(data?.msg ?? "请稍后再试")
        }
        return { userInfo: data.data }
    }

    async qsxGetList(accessToken, termCode) {
        const endpoint = "https://api.quxuanshu.com/student/order/toOrder/list"
        const res = await axios.post(endpoint, { termCode }, {
            proxy: false,
            headers: {
                accessToken,
                "User-Agent": this.UserAgent,
                "Referer": this.Refer
            }
        })
        const data = res.data
        if (!data || data.code !== 0 || !data.data) {

            if (data.msg === '统一订购模式下无权限查看订购数据！') {
                const endpoint = "https://api.quxuanshu.com/student/order/orderInfo/list"
                const res = await axios.post(endpoint, { type: 0, termCode }, {
                    proxy: false,
                    headers: {
                        accessToken,
                        "User-Agent": this.UserAgent,
                        "Referer": this.Refer
                    }
                })
                const data = res.data
                if (!data || data.code !== 0 || !data.data || !data.data.list[0] || !data.data.list[0].orderItem) {
                    throw new Error(data?.msg ?? "请稍后再试")
                }

                return { bookList: data.data.list[0].orderItem ?? [] }
            }

            throw new Error(data?.msg ?? "请稍后再试")
        }
        return { bookList: data.data.list ?? [] }
    }

    async qsxGetBookDetail(accessToken, termCode, title, isbn) {
        const endpoint = "https://u.quxuanshu.com/api/teacher/textbook/textbookInfo/search"
        const queryData = {
            termCode,
            searchKey: title,
            platType: "3",
            curPage: 1,
            pageSize: 15,
            checkCode: "",
            awardTypeList: []
        }
        const res = await axios.post(endpoint, queryData, {
            proxy: false,
            headers: {
                "AccessToken": accessToken,
                "User-Agent": this.UserAgent,
                "Referer": this.Refer
            }
        })
        let data
        if (!res.data || !res.data.data || !res.data.data.list)
            return null
        else data = res.data.data.list
        const book = data.find(b => b.isbn === isbn)
        if (!book || !book.imgUrl)
            return null
        const imgUrl = await this.generateSignatureUrl(book.imgUrl)

        return imgUrl
    }

    async generateSignatureUrl(fileName) {
        // 获取预签名URL
        const client = await new OSS({
            accessKeyId: "LTAI5tB1ZicmzHDeS8KRsyRS",
            accessKeySecret: "sOtCbyJ3NdaAzizoxieN52VV1JkZYr",
            bucket: 'univ-common',
            region: 'oss-cn-hangzhou',
            secure: true,
            authorizationV4: true
        })

        return await client.signatureUrlV4('GET', 3600, {
            headers: {}
        }, fileName)
    }

    async onRequest(req, res) {
        const { username, password } = req.body

        if (!username || !password) {
            return res.json({
                ...BaseStdResponse.MISSING_PARAMETER,
                msg: "缺少用户名或密码"
            })
        }

        try {
            const { accessToken } = await this.qxsLogin(username, password)
            const { userInfo } = await this.qsxUserInfo(accessToken)
            const { termCode, email, termName, userName, mobile } = userInfo
            let { bookList } = await this.qsxGetList(accessToken, termCode)

            let teacherToken
            if (bookList.length > 0) {
                let { accessToken } = await this.qxsLogin('ctbu1991014', 'ctbu123456')
                teacherToken = accessToken

                await Promise.all(
                    bookList.map(async (book) => {
                        if (book.imgUrl) {
                            book.imgUrl = await this.generateSignatureUrl(book.imgUrl)
                        } else {
                            book.imgUrl = await this.qsxGetBookDetail(teacherToken, termCode, book.title, book.isbn)
                        }
                    })
                )
            }

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

            const time = Date.now()
            const sql = `
                INSERT INTO qsx_account 
                (username, password, create_time, book_list, realname, email, mobile, termName) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?)
            `
            await db.query(sql, [
                username,
                password,
                time,
                JSON.stringify(bookList),
                userName,
                email,
                mobile,
                termName
            ])
        } catch (error) {
            this.logger?.error(`${error.stack}`)
            return res.json({
                ...BaseStdResponse.ERR,
                msg: `${error.message ?? "请稍后再试"}`
            })
        }
    }
}

module.exports.GetBookList = GetBookList
