var { Config } = require("../lib/Config");
var request = require("request");
const fs = require('fs');
const path = require('path');

const get_access_token = () => {
    const appid = Config.appId;
    const secret = Config.appSecret;
    const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${secret}`;
    let option = {
        url: url,
        method: "GET",
        headers: {
            "content-type": "application/json",
        },
    };

    return new Promise((resolve, reject) => {
        request(option, function (error, response, body) {
            var data = JSON.parse(body);
            resolve(data);
            if (error) {
                console.error("Error fetching access token:", error);
                reject(error);
            }
        });
    });
};

const get_equipment_code = async (eqId) => {
    // 先检查本地是否已有该仪器的二维码图片
    const fileName = `qrcode_${eqId}.png`;
    const dirPath = path.join(__dirname, '../qrcodes');
    const filePath = path.join(dirPath, fileName);
    
    // 如果目录和文件都存在，直接返回URL
    if (fs.existsSync(dirPath) && fs.existsSync(filePath)) {
        const urlPath = `/qrcodes/${fileName}`;
        console.log("QR code already exists, URL:", urlPath);
        return { name: fileName };
    }
    
    const data = await get_access_token();
    const url = `https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=${data.access_token}`
    let option = {
        url: url,
        method: "post",
        json: {
            "page": "pages/index/index",
            "scene": `eqId=${eqId}`,  
        },
    };
    
    return new Promise((resolve, reject) => {
        request(option, function (error, response, body) {
            if (error) {
                console.error("Error fetching equipment code:", error);
                reject(error);
            } else {
                if (typeof body === 'object' && body.errcode) {
                    console.error("Error from WeChat API:", body);
                    reject(body);
                    return;
                }
                const fileName = `qrcode_${eqId}.png`;
                const dirPath = path.join(__dirname, '../qrcodes');
                const filePath = path.join(dirPath, fileName);
                if (!fs.existsSync(dirPath)) {
                    fs.mkdirSync(dirPath, { recursive: true });
                }
                fs.writeFile(filePath, body, (err) => {
                    if (err) {
                        console.error("Error saving QR code:", err);
                        reject(err);
                    } else {
                        // 返回URL路径
                        const urlPath = `/qrcodes/${fileName}`;
                        console.log("QR code saved, URL:", urlPath);
                        resolve({ name: fileName });
                    }
                });
            }
        });
    });
}



module.exports = { get_access_token,get_equipment_code };
