// src/stores/key.js
import { defineStore } from 'pinia';
import { ref } from 'vue';
import request from '@/utils/request';

export const useKeyStore = defineStore('key', () => {
    const loading = ref(false);
    const error = ref(null);
    const totalKeys = ref(0);
    const keys = ref([]);
    const key = ref(null);

    const fetchKeys = async (pageSize = 20, page = 1, active) => {
        loading.value = true;
        error.value = null;
        try {
            const response = await request.get('/keys', {
                params: {
                    pageSize,
                    page,
                    active,
                },
            });
            
            keys.value = response.data.data?.keys;
            totalKeys.value = response.data.data?.total;
        } catch (err) {
            error.value = err.response?.data?.error || '获取ApiKeys失败';
            throw error
        } finally {
            loading.value = false;
        }
    };

    const fetchKey = async (id) => {
        if (keys.value.length > 0) {
            const findkey = keys.value.find(item => item.id === id)
            if (findkey) {
                key.value = findkey;
                return;
            }
        }
        loading.value = true;
        error.value = null;
        // const findkey = keys.find(item=>item.id === id)
        // console.log('findkey',findkey)
        try {
            const response = await request.get(`/keys/${id}`);
            key.value = response.data.data;
            if (key.value.support_models.length < 3) {
                key.value.support_models = key.value.support_models_array ? JSON.stringify(key.value.support_models) : ''
            }
            if (!key.value.support_models_array) {
                key.value.support_models_array = key.value.support_models ? JSON.parse(key.value.support_models) : []
            }

        } catch (err) {
            error.value = err.response?.data?.error || '获取ApiKey失败';
            throw error
        } finally {
            loading.value = false;
        }
    };

    const refreshKey = async (id) => {
        loading.value = true;
        error.value = null;
        try {
            const response = await request.get(`/keys/${id}`);
            key.value = response.data.data;
            if (key.value.support_models.length < 3) {
                key.value.support_models = key.value.support_models_array ? JSON.stringify(key.value.support_models) : ''
            }
            if (!key.value.support_models_array) {
                key.value.support_models_array = key.value.support_models ? JSON.parse(key.value.support_models) : []
            }
        } catch (err) {
            error.value = err.response?.data?.error || '获取ApiKey失败';
            throw error
        } finally {
            loading.value = false;
        }
    }

    const createKey = async (data) => {
        loading.value = true;
        error.value = null;
        try {
            const response = await request.post('/keys', data);
            return response;
        } catch (err) {
            error.value = err.response?.data?.error || '创建ApiKey失败';
            throw error
        } finally {
            loading.value = false;
        }
    }

    const updateKey = async (key) => {
        loading.value = true;
        error.value = null;
        try {
            const response = await request.put(`/keys/${key.id}`, key);
            return response;
        } catch (err) {
            error.value = err.response?.data?.error || '更新ApiKey失败';
            throw error
        } finally {
            loading.value = false;
        }
    }

    const keyOption = async (option, ids) => {
        loading.value = true;
        error.value = null;
        try {
            const response = await request.post(`/keys/batch/${option}`, { ids });

            return response
        } catch (err) {
            error.value = err.response?.data?.error || '操作失败';
            throw err;
        } finally {
            loading.value = false;
        }
    }
    //todo 更新 批量操作

    return {
        loading, error,
        key, keys, totalKeys,
        fetchKeys,
        fetchKey,
        refreshKey,
        createKey,
        updateKey,
        keyOption,
    }
});

