/*
 * @Author: æ¸”ç�«Arcadia  https://github.com/yhArcadia
 * @Date: 2023-01-04 20:22:48
 * @LastEditors: æ¸”ç�«Arcadia
 * @LastEditTime: 2023-01-12 21:16:40
 * @FilePath: \Yunzai-Bot\plugins\ap-plugin\apps\tools.js
 * @Description: ä¸€äº›å°�å·¥å…·
 * 
 * Copyright (c) 2023 by æ¸”ç�«Arcadia 1761869682@qq.com, All Rights Reserved. 
 */

import plugin from '../../../lib/plugins/plugin.js'
import { parseImg } from '../utils/utils.js';
import cfg from "../../../lib/config/config.js";
import puppeteer from '../../../lib/puppeteer/puppeteer.js'
import Config from '../components/ai_painting/config.js';
import axios from 'axios';

const _path = process.cwd();

export class Tools extends plugin {
    constructor() {
        super({
            name: 'AP-å°�å·¥å…·',
            dsc: 'ap-pluginæ��ä¾›çš„ä¸€äº›å°�å·¥å…·',
            event: 'message',
            priority: 1009,
            rule: [
                {
                    reg: '^#?çœ‹?çœ‹å¤´åƒ�$',
                    fnc: 'ktx'
                },
                {
                    reg: '^#?å�–å›¾é“¾$',
                    fnc: 'getImgUrl'
                },
                {
                    reg: '^#?å›¾é“¾æ¨¡æ�¿$',
                    fnc: 'image_template'
                },
                {
                    reg: "^#?æ’¤å›�$",
                    fnc: "WithDraw",
                },
                {
                    reg: "^#?ap(å…¨å±€|æœ¬ç¾¤|æˆ‘çš„)è¯�äº‘$",
                    fnc: "apWordCloud",
                },
                {
                    reg: "^#?apæ�¥å�£çŠ¶æ€�$",
                    fnc: "apStatus",
                },
                {
                    reg: "^#?(å�–æ¶ˆ|å�œæ­¢)(ç»˜å›¾|å’�å”±|ç»˜ç”»|ç»˜ä¸–|ç»˜åˆ¶).*$",
                    fnc: "apCancel",
                }
            ]
        })
    }

    async ktx(e) {
        let qq = e.user_id
        if (e.at) qq = e.at
        if (e.atBot) qq = Bot.uin
        e.reply(segment.image(`https://q1.qlogo.cn/g?b=qq&s=0&nk=${qq}`))
        return true;
    }

    async getImgUrl(e) {
        e = await parseImg(e)
        if (e.img)
            e.reply(e.img[0])
        else
            e.reply('è¯·é™„å¸¦å›¾ç‰‡ï¼Œæˆ–å¯¹å›¾ç‰‡å›�å¤�')
        return true
    }

    async image_template(e) {
        e.reply('https://gchat.qpic.cn/gchatpic_new/0/0-0-æ›¿æ�¢/0?term=3&is_origin=0')
        return true
    }


    async WithDraw(e) {
        // æ²¡å¼•ç”¨åˆ™æ”¾è¡ŒæŒ‡ä»¤
        if (!e.source) return false;
        // å¦‚æ�œæ˜¯æ’¤å›�æœºå™¨äººçš„æ¶ˆæ�¯,åˆ™ä¸�å�šæ�ƒé™�åˆ¤æ–­
        if (e.source.user_id == Bot.uin) {
            await this.withdrawFn(e);
            return true;
        }
        let { botIs, senderIs, victim, victimIs } = await this.getPermissions(e);
        // æ�ƒé™�ä¸�å¤Ÿ
        if (botIs <= victimIs) {
            // e.replyç”Ÿè�‰å›¾ç‰‡
            return true;
        }
        // ä¸»äººå�¯å‘½ä»¤æ’¤å›�ä»»ä½•æ�ƒé™�å†…æ¶ˆæ�¯
        if (cfg.masterQQ.includes(e.user_id)) {
            await this.withdrawFn(e);
            return true;
        }
        // æœºå™¨äººæ— æ³•æ’¤å›�å�‘èµ·è€…çš„æ¶ˆæ�¯æ—¶;å¹³æ°‘æ²¡æœ‰æ�ƒé™�;è¦�æ’¤å›�ä¸»äººçš„æ¶ˆæ�¯æ—¶
        if (
            botIs <= senderIs ||
            senderIs == 1 ||
            cfg.masterQQ.includes(e.source.user_id)
        ) {
            e.reply(segment.image('https://gchat.qpic.cn/gchatpic_new/1761869682/2077086404-3170617512-116FDFF74709D345FAF0EACD13357D61/0?term=3&is_origin=0'))
            return true;
        }
        await this.withdrawFn(e);
        return true;
    }

    /**åˆ¤æ–­æ�ƒé™�ç­‰çº§*/
    async getPermissions(e) {
        let botIs = e.group.is_owner ? 3 : e.group.is_admin ? 2 : 1;
        let sender = await e.group.pickMember(e.sender.user_id);
        let senderIs =
            // e.isMaster      ? 4      :
            sender.is_owner ? 3 : sender.is_admin ? 2 : 1;
        // let target = await e.group.pickMember(e.source.user_id?e.source.user_id:e.at);
        let victim = await e.group.pickMember(e.at);
        let victimIs = victim.is_owner ? 3 : victim.is_admin ? 2 : 1;
        return {
            botIs: botIs,
            sender: sender,
            senderIs: senderIs,
            victim: victim,
            victimIs: victimIs,
        };
    }
    async withdrawFn(e) {
        try {
            e.group.recallMsg(e.source.seq, e.source.rand);
            e.group.recallMsg(e.message_id);
        } catch (err) { }
    }
    async apWordCloud(e) {
        if (e.at) e.user_id = e.at
        let type = e.msg.match(/(å…¨å±€|æœ¬ç¾¤|æˆ‘çš„)/)[1]
        if (!e.group_id && type == 'æœ¬ç¾¤') return e.reply('è¯·åœ¨ç›¸åº”ç¾¤è�Šä½¿ç”¨æœ¬æŒ‡ä»¤', true)
        let tags = await redis.get(`Yz:AiPainting:TagsUsage:${type == 'æˆ‘çš„' ? e.user_id : type == 'æœ¬ç¾¤' ? e.group_id : 'Global'}`)
        if (!tags) return e.reply('æš‚æ— æ•°æ�®', true)
        tags = JSON.parse(tags)
        let tagCloud = []
        for (let tag in tags) {
            tagCloud.push({
                word: tag,
                weight: tags[tag]
            })
        }
        tagCloud.sort((a, b) => b.value - a.value)
        let data = {
            quality: 90,
            tplFile: `./plugins/ap-plugin/resources/textrank/textrank.html`,
            pluResPath: `${_path}/plugins/ap-plugin/resources/`,
            chartData: JSON.stringify(tagCloud)
        }
        let img = await puppeteer.screenshot('textrank', data)
        e.reply(img)
        return true
    }

    async apStatus(e) {
        let apcfg = await Config.getcfg()
        if (apcfg.APIList.length == 0) {
            e.reply('å½“å‰�æš‚æ— å�¯ç”¨æ�¥å�£')
            return true
        }
        let msg = 'å…±æœ‰' + apcfg.APIList.length + 'ä¸ªæ�¥å�£'
        let res = await Promise.all(apcfg.APIList.map(async (item) => {
            let res = await axios.get(item.url, { timeout: 5000 }).catch(() => { })
            return res
        }))
        for (let i = 0; i < res.length; i++) {
            if (res[i]) {
                let header = {}
                if (apcfg.APIList[i].account_id && apcfg.APIList[i].account_password) {
                    header = {
                        'Authorization': 'Basic ' + Buffer.from(`${apcfg.APIList[i].account_id}:${apcfg.APIList[i].account_password}`).toString('base64'),
                        'User-Agent': `AP-Plugin`
                    }
                }
                let progress = await axios.get(`${apcfg.APIList[i].url}/sdapi/v1/progress`, { headers: header, timeout: 5000 }).catch(() => { })
                if (progress) {
                    if (progress.data.eta_relative == '0') {
                        msg += `\nâœ…æ�¥å�£${i + 1}[${res[i].status}]ï¼š${apcfg.APIList[i].remark} æœ�åŠ¡å™¨å¾ˆå¯‚å¯�...`
                    } else {
                        msg += `\nâœ…æ�¥å�£${i + 1}[${res[i].status}]ï¼š${apcfg.APIList[i].remark} [${(progress.data.progress * 100).toFixed(0)}%]é¢„è®¡å‰©ä½™${(progress.data.eta_relative).toFixed(2)}ç§’å®Œæˆ�`
                    }
                } else {
                    msg += `\nâœ…æ�¥å�£${i + 1}[${res[i].status}]ï¼š${apcfg.APIList[i].remark} æœªèƒ½è�·å�–è¿›åº¦`
                }
            } else {
                msg += `\nğŸš«æ�¥å�£${i + 1}[è¶…æ—¶]ï¼š${apcfg.APIList[i].remark}`
            }
        }
        e.reply(msg)
        return true
    }

    async apCancel(e) {
        let apcfg = await Config.getcfg()
        if (apcfg.APIList.length == 0) {
            e.reply('å½“å‰�æš‚æ— å�¯ç”¨æ�¥å�£')
            return true
        }
        let num = e.msg.match(/æ�¥å�£(\d+)/)
        if (num) {
            num = parseInt(num[1]) - 1
            if (num > apcfg.APIList.length) return e.reply('æ�¥å�£ä¸�å­˜åœ¨')
        } else {
            num = apcfg.usingAPI - 1
        }
        let url = apcfg.APIList[num].url + '/sdapi/v1/interrupt'
        let header = {}
        if (apcfg.APIList[num].account_id && apcfg.APIList[num].account_password) {
            header = {
                'Authorization': 'Basic ' + Buffer.from(`${apcfg.APIList[num].account_id}:${apcfg.APIList[num].account_password}`).toString('base64'),
                'User-Agent': `AP-Plugin`
            }
        }
        try {
            let res = await axios.post(url, { headers: header, timeout: 5000 })
            if (res) {
                e.reply(`æ�¥å�£${num + 1}ï¼š${apcfg.APIList[num].remark}å·²å�–æ¶ˆå½“å‰�ç»˜åˆ¶ä»»åŠ¡`)
            } else {
                e.reply(`æ�¥å�£${num + 1}ï¼š${apcfg.APIList[num].remark}å�–æ¶ˆä»»åŠ¡å¤±è´¥`)
            }
        } catch (err) {
            e.reply(`æ�¥å�£${num + 1}ï¼š${apcfg.APIList[num].remark}å�–æ¶ˆä»»åŠ¡å¤±è´¥`)
        }
        return true
    }
}
