// const BASE_URL = 'https://chtech.ncjti.edu.cn/carstop/carBuy'
const BASE_URL = 'https://car.meiyishuoo.com/ride-sharing/carBuy'

export function myRequest(options : any) {
	uni.showLoading({
		title: '加载中',
		mask: true,
	})
	// 当前时间
	const timestamp = new Date().getTime()
	// 将时间戳添加到URL中
	options.url += `${options.url.includes('?') ? '&' : '?'}timestamp=${timestamp}`

	return new Promise((resolve, reject) => {
		uni.request({
			url: BASE_URL + options.url,
			method: options.method || 'GET',
			data: options.data || {},
			header: options.header || {
				// token: uni.getStorageSync('auth').token || '',
			},
			success: (res : any) => {
				console.log(res);
				uni.hideLoading()
				if (res.data.code === 200) {
					resolve(res.data)
				}
				else {
					// 定义需要静默处理的code（如205代表“未查询到认证信息”，无需页面提示）
					const silentMessages = ["未查询到认证信息"];
					if (!silentMessages.includes(res.data.message) && res.data.code) {
					    // 非静默code且有message时，通过弹框提示（如uni.showToast）
					    uni.showToast({
					    	title: res.data.message || "接口报错",
					    	icon: 'none', 
					    })
						if (res.data.message=="未查到用户信息") {
						    uni.removeStorageSync('carUserInfo')
						}
					}
				} 
			},
			fail: (err) => {
				console.log(err)
				uni.hideLoading()
				uni.showToast({
					title: '请求数据失败',
					icon: 'none',
				})
				reject(err)
			},
		})
	})
}

// 新增 uni.uploadFile 封装
export function myUploadFile(options: {
  url: string;
  filePath: string;
  name: string;
  formData?: Record<string, any>;
  header?: Record<string, string>;
}) {
  uni.showLoading({ title: '上传中', mask: true });
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: BASE_URL + options.url,
      filePath: options.filePath,
      name: options.name,
      formData: options.formData || {},
      header: options.header || {
        // 可添加全局请求头，如 token
        // 'Authorization': uni.getStorageSync('auth').token || ''
      },
      success: (res) => {
        uni.hideLoading();
        const data = JSON.parse(res.data);
        if (data.code === 200) {
          resolve(data);
        } else {
          uni.showToast({ title: data.message || '上传失败', icon: 'none' });
          reject(data);
        }
      },
      fail: (err) => {
		  console.log(err)
        uni.hideLoading();    
        uni.showToast({ title: '网络异常', icon: 'none' });
        reject(err);
      }
    });
  });
}

export const uploadFile = (filePath: string) => {
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: BASE_URL +'/filesload.action', // 后端上传接口地址
      filePath,
      name: 'myFile',
      formData: { name: '认证图片' },
      success: (res) => {
		  console.log(res,'api中')
        const data = JSON.parse(res.data);
        if (data.code === 200) {
          resolve(data.data.url); // 返回上传后的图片链接
        } else {
          reject(data.message || '上传失败');
        }
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
};