/**
 * 根据关键词获取作者和出版社数据
 * @param {string} keyword - 搜索关键词
 * @param {string} cookies - 用户cookies
 * @returns {Promise<{authors: string[], publishers: string[]}>} 返回作者和出版社数据
 */
export const getAuthorAndPublisher = async (keyword, cookies) => {
    try {
        const response = await new Promise((resolve, reject) => {
            uni.request({
                url: 'https://api.buzhiyushu.cn/zhishu/shopGoods/getAuthorAndPublisher',
                method: 'GET',
                data: {
                    keyword: keyword,
                    cookies: cookies
                },
                success: (res) => {
                    console.log('API原始响应:', JSON.stringify(res, null, 2));
                    resolve(res);
                },
                fail: (err) => {
                    console.error('API请求失败:', err);
                    reject(new Error(err.errMsg || '网络请求失败'));
                }
            });
        });

        // 检查响应数据
        if (!response.data || response.data.code !== 200) {
            console.log('API返回数据无效或请求失败');
            return { authors: [], publishers: [] };
        }

        const data = response.data.data || [];
        
        // 提取作者和出版社数据
        const authors = new Set();
        const publishers = new Set();

        data.forEach(item => {
            // 处理作者数据
            if (item.author) {
                const author = item.author.trim();
                if (author) {
                    authors.add(author);
                }
            }
            
            // 处理出版社数据
            if (item.press) {
                const press = item.press.trim();
                if (press) {
                    publishers.add(press);
                }
            }
        });

        // 转换为数组并过滤掉空值
        const authorArray = Array.from(authors).filter(Boolean).slice(0, 10);
        const publisherArray = Array.from(publishers).filter(Boolean).slice(0, 10);

        console.log('提取的作者列表(前10条):', authorArray);
        console.log('提取的出版社列表(前10条):', publisherArray);

        return {
            authors: authorArray,
            publishers: publisherArray
        };

    } catch (error) {
        console.error('获取作者和出版社数据出错:', error);
        return { authors: [], publishers: [] };
    }
};

/**
 * 导出所有函数
 */
export default {
    getAuthorAndPublisher
}; 