import axios from "axios";
import { fetchEventSource } from '@microsoft/fetch-event-source';
export const apiKey = process.env.INSCODE_API_KEY;

export const apiUrl = 'https://inscode-api.csdn.net/api/v1/gpt/';
export default {
    draw (config) {
        return new Promise(function(resolve,rejcet){
            const data = {
                prompt: config.prompt,
                steps: config?.steps??20,
                negative_prompt: config.negative_prompt?config.negative_prompt+',nfsw,no underwear,tits':'nfsw,no underwear,tits',
                width: config?.width??512,
                height: config?.height??512,
                cfg_scale: config.cfg_scale??6,
                seed : config.seed??-1,
                sampler_name: config.sampler_name??"DPM++ SDE Karras",
                sd_model_checkpoint:config.sd_model_checkpoint??"chilloutmix_NiPrunedFp32Fix"
            }
            const headers = {
                'content-type': 'application/json'
            };
            let api = 'https://gpu-pod65d1a546eb9c3114aef516a1-6006.node.inscode.run/sdapi/v1/txt2img'
            console.log('sd data',data)
            axios.post(api, data, { headers }).then(response => {
                if (response.status === 200 && response?.data?.images){
                    const image = response?.data?.images[0]
                    resolve('data:image/png;base64,' + image)
                }
            }).catch(err => {
                rejcet(err)
            });

        })
    },
    gpt(prompt){
        return new Promise(function(resolve,rejcet){
            const data = {
                'messages': [
                    {
                        'role': 'user',
                        'content': prompt
                    }],
                'stream_token': false,
                'apikey': apiKey
            }
            const headers = {
                'content-type': 'application/json'
            };
            axios.post(apiUrl, data, { headers }).then(response => {
                console.log('response.data',response.data)
                if(response.data.indexOf("升级 InsCode Pro 会员")>-1){
                    rejcet("您的 AI API 免费次数已经用完，已无法使用涉及 AI 的应用，升级 InsCode Pro 会员（inscode.csdn.net）后，可免费使用平台内全部 AI 应用。")
                }else if(response.data.indexOf("敏感")>-1){
                    rejcet("抱歉，该问题含有敏感词信息，请换一个问题")
                }else{
                    resolve(response.data)
                }
            }).catch(err => {
                rejcet(err)
            });

        })
    },
    gpt2(prompt){
        return new Promise(function(resolve,rejcet){
            const body = {
                messages: [
                    {
                        role: 'user',
                        content: prompt
                    }
                ],
                apikey: apiKey
            }
            fetchEventSource(apiUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(body),
                onopen: (response) => {
                    console.log('open',response)
                },
                onmessage: (msg) => {
                    if (msg.data === '[DONE]') {
                       // this.loading = false;
                        return;
                    };
                    const data = JSON.parse(msg.data);
                    const finish_reason = data.choices[0].finish_reason;
                    const finish = finish_reason === 'stop' || finish_reason === 'length';
                    const content = data.choices[0].delta.content;

                    if (finish) {
                       // this.loading = false;
                    } else if (content) {
                        console.log('gpt: response',content)
                        resolve(content)
                    }
                },
                onerror: (err) => {
                    rejcet(err)
                    console.log("error", err);
                }
            });
        })
    }
}
