const axios = require('axios');
const db = require('../../plugin/DataBase/db')
const config = require('../../config.json')

class IC {
    constructor() {
        this.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
            'Accept': 'image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8'
        }
    }

    async getCookie(username, password) {
        return new Promise(async (resolve, reject) => {
            try {
                let sql = `SELECT ic_cookie FROM jw_account WHERE username = ? AND state = 1`
                let r = await db.query(sql, [username])
                if (!r || r.length !== 1)
                    reject(new Error('获取统一身份认证账号失败！'))
                if (!r[0].ic_cookie) {
                    let cookie = await this.resetCookie(username, password)
                    resolve(cookie)
                }
                else
                    resolve(r[0].ic_cookie);
            } catch (error) {
                reject(error)
            }
        });
    }

    async resetCookie(username, password) {
        return new Promise(async (resolve, reject) => {
            const url = config.url2 + '/login'
            try {
                console.log('begin')
                const res = await axios.post(url, { username, password })
                console.log(res)
                if (!res || res.data.code !== 0 || !res.data.ic_cookie) {
                    if (res.data && res.data.code === 401) {
                        let sql = 'UPDATE jw_account SET state = 2 WHERE username = ?'
                        await db.query(sql, [username])

                        return reject(new Error('用户名或密码错误，请核对后再试！'))
                    }

                    if (res.data && res.data.code === 400) {
                        try {
                            return await this.resetCookie(username, password)
                        } catch (error) {
                            reject(error)
                        }
                    }

                    return reject(new Error(res.data.msg || '更新登录令牌失败！'))
                }
                const cookie = res.data.ic_cookie
                let sql = 'UPDATE jw_account SET ic_cookie = ? WHERE username = ?'
                let r = await db.query(sql, [cookie, username])
                if (!r || r.affectedRows !== 1)
                    reject(new Error('更新登录令牌失败！数据库错误'))
                resolve(cookie);
            } catch (error) {
                reject(error)
            }
        })
    }

    async getMyOrder(cookie, data) {
        return new Promise(async (resolve, reject) => {
            const { beginDate, endDate, page, pageNum } = data

            try {
                const url = `https://ic.ctbu.edu.cn/ic-web/reserve/resvInfo?beginDate=${beginDate}&endDate=${endDate}&needStatus=150&page=${page}&pageNum=${pageNum}&orderKey=gmt_create&orderModel=desc`
                const res = await axios.get(url, {
                    headers: {
                        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
                        'Cookie': cookie,
                        'Accept-Language': 'zh-CN,zh;q=0.9'
                    }
                })

                if (!res || res.data.code !== 0) {
                    if (res.data.code === 300)
                        return resolve(res.data)

                    reject(new Error(`获取信息失败！${res.data.message || ''}`))
                }

                resolve(res.data);
            } catch (error) {
                reject(error)
            }
        });
    }

    async orderSeat(cookie, data) {
        return new Promise(async (resolve, reject) => {
            try {
                const user = await this.getUserInfo(cookie)
                if (user.code === 300)
                    return resolve(user)
                if (!user.accNo || !user.token)
                    return reject(new Error('获取用户信息失败！'))

                const accNo = user.accNo
                const captcha = await this.getCaptcha(cookie)
                data = { ...data, captcha, resvMember: [accNo], appAccNo: accNo, sysKind: 8, memberKind: 1, testName: '', resvProperty: 0, memo: '' }

                const url = `https://ic.ctbu.edu.cn/ic-web/reserve`

                const res = await axios.post(url, data, {
                    headers: {
                        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
                        'Cookie': cookie,
                        'Token': user.token,
                        'Accept-Language': 'zh-CN,zh;q=0.9'
                    }
                });

                if (!res || res.data.code !== 0) {
                    if (res.data.code === 300)
                        return resolve(res.data)
                    if (res.data.message === '请求参数错误')
                        return reject(new Error(`预约失败！请检查预约时间是否符合规定`))
                    if (res.data.message === '验证码错误') {
                        return resolve(await this.orderSeat(cookie, data));
                    }

                    reject(new Error(`预约失败！${res.data.message || ''}`))
                }

                resolve(res.data);
            } catch (error) {
                reject(error)
            }
        });
    }

    async deleteSeat(cookie, uuid) {
        return new Promise(async (resolve, reject) => {

            const url = 'https://ic.ctbu.edu.cn/ic-web/reserve/delete'

            try {
                const res = await axios.post(url, { uuid }, {
                    headers: {
                        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
                        'Cookie': cookie,
                        'Accept-Language': 'zh-CN,zh;q=0.9'
                    }
                });

                if (!res || res.data.code !== 0) {
                    if (res.data.code === 300)
                        return resolve(res.data)

                    return reject(new Error(`取消预约失败！${res.data.message || ''}`))
                }

                resolve(res.data);
            } catch (error) {
                reject(error)
            }
        });
    }

    async endAhead(cookie, uuid) {
        return new Promise(async (resolve, reject) => {

            const url = 'https://ic.ctbu.edu.cn/ic-web/reserve/endAhaed'

            try {
                const res = await axios.post(url, { uuid }, {
                    headers: {
                        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
                        'Cookie': cookie,
                        'Accept-Language': 'zh-CN,zh;q=0.9'
                    }
                });

                if (!res || res.data.code !== 0) {
                    if (res.data.code === 300)
                        return resolve(res.data)

                    return reject(new Error(`提前结束失败！${res.data.message || ''}`))
                }

                resolve(res.data);
            } catch (error) {
                reject(error)
            }
        });
    }


    async getCaptcha(cookie) {
        return new Promise(async (resolve, reject) => {
            const url = `https://ic.ctbu.edu.cn/ic-web/captcha?id=${new Date().getTime()}`

            try {
                const res = await axios.get(url, {
                    headers: {
                        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
                        'Cookie': cookie,
                        'Accept': 'image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8'
                    },
                    responseType: 'arraybuffer'
                })

                if (!res)
                    return reject(new Error(`获取验证码失败！`))

                const buffer = Buffer.from(res.data);
                const base64Image = buffer.toString('base64');
                const authUrl = config.url2 + '/recognize'
                const authRes = await axios.post(authUrl, { image: base64Image })
                if (!authRes || authRes.data.code !== 0)
                    return reject(new Error(`获取验证码失败！${authRes.msg || ''}`))
                const authcode = authRes.data.captcha

                resolve(authcode);
            } catch (error) {
                reject(error)
            }
        });
    }

    async getUserInfo(cookie) {
        return new Promise(async (resolve, reject) => {
            const url = 'https://ic.ctbu.edu.cn/ic-web/auth/userInfo';

            try {
                const res = await axios.get(url, {
                    headers: {
                        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
                        'Cookie': cookie,
                        'Accept-Language': 'zh-CN,zh;q=0.9'
                    }
                });

                if (!res || res.data.code !== 0 || !res.data.data) {
                    if (res.data.code === 300)
                        return resolve(res.data)

                    return reject(new Error(`获取用户信息失败！${res.data.message || ''}`))
                }

                resolve(res.data.data);
            } catch (error) {
                reject(error)
            }
        });
    }

    async getSeatMenu(cookie) {
        return new Promise(async (resolve, reject) => {
            const url = 'https://ic.ctbu.edu.cn/ic-web/seatMenu';

            try {
                const res = await axios.get(url, {
                    headers: {
                        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
                        'Cookie': cookie,
                        'Accept-Language': 'zh-CN,zh;q=0.9'
                    }
                });

                if (!res || res.data.code !== 0 || !res.data.data) {
                    if (res.data.code === 300)
                        return resolve(res.data)

                    return reject(new Error(`获取座位信息失败！${res.data.message || ''}`))
                }

                resolve(res.data.data);
            } catch (error) {
                reject(error)
            }
        });
    }

    async getOpenScope(cookie, roomId) {
        return new Promise(async (resolve, reject) => {
            const url = `https://ic.ctbu.edu.cn/ic-web/seatRoom/openScope?roomId=${roomId}`;

            try {
                const res = await axios.get(url, {
                    headers: {
                        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
                        'Cookie': cookie,
                        'Accept-Language': 'zh-CN,zh;q=0.9'
                    }
                });

                if (!res || res.data.code !== 0 || !res.data.data) {
                    return reject(new Error(`获取开放时间失败！${res.data.message || ''}`))
                }

                resolve(res.data.data);
            } catch (error) {
                reject(error)
            }
        });
    }

    async getSeatInfo(cookie, roomId, date) {
        return new Promise(async (resolve, reject) => {
            const url = `https://ic.ctbu.edu.cn/ic-web/reserve?roomIds=${roomId}&resvDates=${date}&sysKind=8`;

            try {
                const res = await axios.get(url, {
                    headers: {
                        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
                        'Cookie': cookie,
                        'Accept-Language': 'zh-CN,zh;q=0.9'
                    }
                });

                if (!res || res.data.code !== 0 || !res.data) {
                    if (res.data.code === 300)
                        return resolve(res.data)
                    return reject(new Error(`获取座位详情失败！${res.data.message || ''}`))
                }

                resolve(res.data.data);
            } catch (error) {
                reject(error)
            }
        });
    }
}

const ic = new IC();
module.exports.IC = ic
