import request from '../http'
import { URL, appid } from '../url'

// 用户登录
export const login = (data) => {
	return request({
		url: '/app/user/login',
		method: 'get',
		data
	})
}

// 用户退出登录
export const userLogout = (data) => {
	return request({
		url: '/auth/logout',
		method: 'post',
		data
	})
}

// 获取用户信息
export const getMyIndexInfo = (data) => {
	return request({
		url: '/app/user/userInfo',
		method: 'get',
		data,
	})
}

// 更新用户信息
export const updateUserInfo = (data) => {
	return request({
		url: '/app/user/updateUser',
		method: 'post',
		data
	})
}

// 更新用户余额
export const updateUserBalance = (orderId) => {
	return request({
		url: `/app/user/updateBalance/${orderId}`,
		method: 'post',
		hideLoading: true
	})
}

// 上传并更新用户头像（后端接口）
export const uploadUserAvatar = (filePath) => {
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: URL + '/app/user/uploadAvatar',
			filePath,
			name: 'file',
			header: {
				'appid': appid,
				'Authorization': 'Bearer ' + uni.getStorageSync('token'),
				'Clientid': uni.getStorageSync('client_id')
			},
			success: (res) => {
				try {
					const parsed = typeof res.data === 'string' ? JSON.parse(res.data) : res.data
					resolve(parsed)
				} catch (e) {
					reject(e)
				}
			},
			fail: (err) => {
				reject(err)
			}
		})
	})
}

// 文件上传到 OSS（若依后端）
export const uploadOssResource = (filePath) => {
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: URL + '/manager/upload',
			filePath,
			name: 'file',
			header: {
				'appid': appid,
				'Authorization': 'Bearer ' + uni.getStorageSync('token'),
				'Clientid': uni.getStorageSync('client_id')
			},
			success: (res) => {
				try {
					const parsed = typeof res.data === 'string' ? JSON.parse(res.data) : res.data
					const codeOk = (res.statusCode === 200 || res.statusCode === 201 || parsed?.code === 200)
					const url = parsed?.url || parsed?.data?.url || parsed?.data?.fileUrl || parsed?.fileUrl || parsed?.path || parsed?.data
					if (codeOk && url) {
						resolve(url)
						return
					}
					reject(parsed || res)
				} catch (e) {
					reject(e)
				}
			},
			fail: (err) => {
				reject(err)
			}
		})
	})
}

// 添加押金提现API
export const withdrawDeposit = (orderNo) => {
	return request({
		url: `/app/withdraw/add/${orderNo}`,
		method: 'get',
		hideLoading: true
	})
}

