import {
	useGlobalStore
} from '../stores/global.js';
import {
	storeToRefs
} from 'pinia';
import {
	HTTP_STATUS
} from './config.js'

const globalStore = useGlobalStore();
const {
	cuk
} = storeToRefs(globalStore);

// request.js
// 通常可以吧 baseUrl 单独放在一个 js 文件了
// const baseUrl = "http://172.16.224.178:7777/pmall";
// const baseUrl = "https://momclub-uat.feihe.com/pmall";//测试环境
const baseUrl = "https://momclub.feihe.com/pmall";//生产环境   

const request = (options = {}) => {
	// 在这里可以对请求头进行一些设置
	// 例如：
	// options.header = {
	//      "Content-Type": "application/x-www-form-urlencoded"
	// }
	// if(options.url == '/c/ai/chat/query'){
	// 	baseUrl = "https://docs.dui88.com/mock/1956";
	// }
	return new Promise((resolve, reject) => {
		uni
			.request({
				url: baseUrl + options.url || "",
				method: options.type || "GET",
				data: options.data || {},
				header: {
					...options.header,
					cuk: cuk.value || undefined
				},
			})
			.then((data) => {
				// console.log('request data ===>', data);
				if (data.statusCode !== HTTP_STATUS.SUCCESS) {
					uni.showToast({
						title: data.errMsg,
						icon: 'none'
					});
					reject(data);
					globalStore.setIsShowLoading(false);
				} else if (!data.data?.ok) {
					uni.showToast({
						title: data.data?.message,
						icon: 'none'
					});
					reject(data.data);
					globalStore.setIsShowLoading(false);
				} else {
					resolve(data.data);
				}
			})
			.catch((error) => {
				reject(error);
				globalStore.setIsShowLoading(false);
			});
	});
};

const get = (url, data, options = {}) => {
	options.type = "GET";
	options.data = data;
	options.url = url;
	return request(options);
};

const post = (url, data, options = {}) => {
	options.type = "POST";
	options.data = data;
	options.url = url;
	return request(options);
};

export default {
	request,
	api: {
		get,
		post
	}
};