import { navigateToLogin } from '@/common/checkLogin.js'

let baseUrl = '';
if (process.env.NODE_ENV === 'development') {
	baseUrl = 'http://192.168.1.6:8080'; // 开发环境
	// baseUrl = 'http://192.168.1.222:8080';
} else {
	baseUrl = 'https://wuyeapi.ckdzkj.com'; // 生产环境
}

export default function request(url, data = {}, method = "GET") {
	return new Promise((resolve, reject) => {
		// uni.showLoading({
		// 	title: '请求中...',
		// 	mask: true
		// });

		const token = uni.getStorageSync("token") || "";
		const header = {
			"clientid": "resident",
			'content-type': 'application/json'
		}; 
		if (token) {
			header["Authorization"] = "Bearer " + token;
		}

		uni.request({
			url: baseUrl + url,
			data: data,
			method: method,
			header,
			success: (res) => {
				// uni.hideLoading();

				// HTTP 失败
				if (res.statusCode !== 200) {
					reject({ msg: `请求异常 ${res.statusCode}`, code: res.statusCode });
					return;
				}

				const resData = res.data || {};

				// token 过期：仅在有 token 且过期时跳转登录页（无 token 用户正常浏览首页，由点击拦截处理）
				if (resData.code === 401) {
					if (token) {
						uni.clearStorageSync('token');
						navigateToLogin({ method: 'reLaunch' });
					}
					reject({ msg: '登录过期', code: 401 });
					return;
				}

				// 成功
				if (resData.code === 200) {
					resolve(resData);
				}
				// 业务失败
				else {
					reject({ msg: resData.msg || '请求失败', code: resData.code, data: resData });
				}
			},
			fail: (err) => {
				// uni.hideLoading();
				reject({ msg: '网络异常', code: -1, raw: err });
			}
		});
	});
}

export const get = (url, data = {}) => request(url, data, 'GET');
export const post = (url, data) => request(url, data, 'POST');
export const deleteMethod = (url, data) => request(url, data, 'DELETE');
export const putMethod = (url, data) => request(url, data, 'PUT');

// 上传
export const upload = (filePath, url) => {
	return new Promise((resolve, reject) => {
		const t = uni.getStorageSync("token") || "";
		const uploadHeader = {
			"clientid": "resident"
		};
		if (t) {
			uploadHeader["Authorization"] = "Bearer " + t;
		}

		uni.uploadFile({
			url: baseUrl + url,
			filePath: filePath,
			name: 'file',
			header: uploadHeader,
			success: (res) => {
				try {
						const data = JSON.parse(res.data);
						resolve(data.data || ''); // 直接返回图片地址
					} catch (e) {
						resolve('');
					}
			},
			fail: (err) => {
				reject(err);
			}
		});
	});
};