// 云端基础URL
// const BASE_URL = 'https://cloud.yuxindazhineng.com'
const BASE_URL = 'https://cloudtest.yuxindazhineng.com'
// const BASE_URL = 'https://yxdpqj.yuxindazhineng.com'

// 登录请求
export const login = async (username, password) => {
	return new Promise((resolve, reject) => {
		uni.request({
			url: `${BASE_URL}/login`,
			method: "POST",
			data: {
				"username": username,
				"password": password,
				"login_type": "phone"
			},
			header: {
				'Content-Type': 'application/json'
			},
			success: (res) => {
				if (res.statusCode === 200) {
					const token = res.data.access_token
					if (token) {
						uni.setStorageSync('token', token)
						resolve(token)
					} else {
						const msg = res.data.error || '检查用户名和密码'
						reject(msg)
					}
				} else {
					reject(`请求失败：${res.statusCode}`)
				}
			},
			fail: (err) => {
				const msg = err.errMsg || '网络错误'
				reject(msg)
			}
		})
	})
}

// 历史会话请求
export const getUserConversations = async (token) => {
	return new Promise((resolve, reject) => {
		uni.request({
			url: `${BASE_URL}/get_user_conversations`,
			method: "POST",
			data: {
				"access_token": token
			},
			header: {
				'Content-Type': 'application/json'
			},
			success: (res) => {
				if (res.statusCode === 200) {
					const conversations = res.data.conversations
					resolve(conversations)

				} else {
					reject(`请求失败：${res.statusCode}`)
				}
			},
			fail: (err) => {
				const msg = err.errMsg || '网络错误'
				reject(msg)
			}
		})
	})
}

// 获取与AI的对话内容
export const getConversationMessages = async (token, conversatio_id) => {
	return new Promise((resolve, reject) => {
		uni.request({
			url: `${BASE_URL}/get_conversation_messages`,
			method: 'POST',
			data: {
				"access_token": token,
				"conversation_id": conversatio_id
			},
			header: {
				'Content-Type': 'application/json'
			},
			success: (res) => {
				if (res.statusCode === 200) {
					const messagesInfo = res.data
					if (messagesInfo) {
						console.log("工作区id为：", messagesInfo.workspace_id);
						uni.setStorageSync('workspace_id', messagesInfo.workspace_id)
						resolve(messagesInfo.messages)
					} else {
						const msg = res.data.error || '获取消息出错啦'
						reject(msg)
					}
				} else {
					reject(`请求失败：${res.statusCode}`)
				}

			},
			fail: (err) => {
				const msg = err.errMsg || '网络错误'
				reject(msg)
			}
		})
	})
}

// 用户发送消息（ai不接收/回复）
export const addMessageDict = async (token, role, conversation_id, message) => {
	return new Promise((resolve, reject) => {
		uni.request({
			url: `${BASE_URL}/add_message_dict`,
			method: "POST",
			data: {
				"access_token": token,
				"conversation_id": conversation_id,
				"message": {
					"role": role,
					"content": message
				}
			},
			header: {
				'Content-Type': 'application/json'
			},
			success: (res) => {
				if (res.statusCode === 200) {
					const message_id = res.data.message_id
					if (message_id) {
						resolve(message_id)
					} else {
						const msg = res.data.error || '用户发送消息出错啦'
						reject(msg)
					}
				} else {
					reject(`用户发送失败：${res.statusCode}`)
				}
			},
			fail: (err) => {
				const msg = err.errMsg || '网络错误'
				reject(msg)
			}
		})
	})
}

// 获取工作区消息（非内容）
export const getWorkspaceByConversation = async (token, conversation_id) => {
	return new Promise((resolve, reject) => {
		uni.request({
			url: `${BASE_URL}/get_workspace_by_conversation`,
			method: "POST",
			data: {
				"access_token": token,
				"conversation_id": conversation_id
			},
			header: {
				'Content-Type': 'application/json'
			},
			success: (res) => {
				if (res.statusCode === 200) {
					const workspaceInfo = res.data
					if (workspaceInfo?.success) {
						resolve(workspaceInfo.workspace_id)
					} else {
						const msg = res.data.error || '获取工作区消息出错啦'
						reject(msg)
					}
				} else {
					reject(`获取工作区消息失败：${res.statusCode}`)
				}
			},
			fail: (err) => {
				const msg = err.errMsg || '网络错误'
				reject(msg)
			}
		})


	})
}


// 创建工作区id
export const createWorkspace = async (token, name) => {
	return new Promise((resolve, reject) => {
		uni.request({
			url: `${BASE_URL}/create_workspace`,
			method: "POST",
			data: {
				"access_token": token,
				"name": name
			},
			header: {
				'Content-Type': 'application/json'
			},
			success: (res) => {
				if (res.statusCode === 200) {
					const workspaceId = res.data.workspace_id
					if (workspaceId) {
						resolve(workspaceId)
					} else {
						const msg = res.data.error || '创建工作区id出错啦'
						reject(msg)
					}
				} else {
					reject(`创建工作区id失败：${res.statusCode}`)
				}
			},
			fail: (err) => {
				const msg = err.errMsg || '网络错误'
				reject(msg)
			}
		})
	})
}

// 创建新对话
export const createConversation = async (token, workspaceId, title, sender) => {
	return new Promise((resolve, reject) => {
		uni.request({
			url: `${BASE_URL}/create_conversation`,
			method: "POST",
			data: {
				"access_token": token,
				"workspace_id": workspaceId,
				"title": title,
				"sender": sender
			},
			header: {
				'Content-Type': 'application/json'
			},
			success: (res) => {
				if (res.statusCode === 200) {
					const conversationId = res.data.conversation_id
					if (conversationId) {
						resolve(conversationId)
					} else {
						const msg = res.data.error || '创建新对话id出错啦'
						reject(msg)
					}
				} else {
					reject(`创建新对话失败：${res.statusCode}`)
				}
			}
		})
	})
}


// 删除会话
export const deleteConversation = async (token, conversation_ids) => {
	return new Promise((resolve, reject) => {
		uni.request({
			url: `${BASE_URL}/delete_conversation`,
			method: "POST",
			data: {
				"access_token": token,
				"conversation_ids": conversation_ids
			},
			header: {
				'Content-Type': 'application/json'
			},
			success: (res) => {
				if (res.statusCode === 200) {
					const respond = res.data
					if (respond?.success) {
						resolve(respond.message)
					} else {
						const msg = respond.failed_ids.error || '删除对话出错啦'
						reject(msg)
					}
				} else {
					reject(`删除对话失败：${res.statusCode}`)
				}
			},
			fail: (err) => {
				const msg = err.errMsg || '网络错误'
				reject(msg)
			}
		})
	})
}

// 获取用户信息
export const getUserInfo = async (token) => {
	return new Promise((resolve, reject) => {
		uni.request({
			url: `${BASE_URL}/get_user_info`,
			method: "POST",
			header: {
				'Content-Type': 'application/json'
			},
			data: {
				"access_token": token
			},
			success: (res) => {
				if (res.statusCode === 200) {
					const respond = res.data
					if (respond?._id) {
						uni.setStorageSync('userId', respond._id)
						resolve(respond)
					} else {
						const msg = respond?.detail?.[0]?.msg || '获取用户信息出错啦'
						reject(msg)
					}
				} else {
					reject(`获取用户信息失败：${res.statusCode}`)
				}
			},
			fail: (err) => {
				const msg = err.errMsg || '网络错误'
				reject(msg)
			}
		})
	})
}

// 获取用户头像（自己or好友组）
export const getUserAvatar = (token, userIds) => {
	return new Promise((resolve, reject) => {
		uni.request({
			url: `${BASE_URL}/cloud_api/get_user_avatar`,
			method: "POST",
			header: {
				'Content-Type': 'application/json'
			},
			data: {
				"access_token": token,
				"user_ids": userIds
			},
			success: (res) => {
				if (res.statusCode === 200) {
					const respond = res.data
					if (respond.success) {
						resolve(respond.users)
					} else {
						const msg = respond?.error || '获取用户头像出错啦'
						reject(msg)
					}
				} else {
					reject(`获取用户头像失败：${res.statusCode}`)
				}
			},
			fail: (err) => {
				const msg = err.errMsg || '网络错误'
				reject(msg)
			}
		})
	})
}


// 通过用户名或邮箱来去查询用户
export const searchUsers = (token, keyword) => {
	return new Promise((resolve, reject) => {
		uni.request({
			url: `${BASE_URL}/cloud_api/search_users`,
			method: "POST",
			header: {
				'Content-Type': 'application/json'
			},
			data: {
				"access_token": token,
				"keyword": keyword
			},
			success: (res) => {
				if (res.statusCode === 200) {
					const respond = res.data
					if (respond.success) {
						resolve(respond.users)
					} else {
						const msg = respond?.error || '通过用户名或邮箱来去查询用户出错啦'
						reject(msg)
					}
				} else {
					reject(`通过用户名或邮箱来去查询用户失败：${res.statusCode}`)
				}
			},
			fail: (err) => {
				const msg = err.errMsg || '网络错误'
				reject(msg)
			}
		})
	})
}

// 获取工作区文件目录
export const getWorkspaceList = (token, workspacesId) => {
	return new Promise((resolve, reject) => {
		uni.request({
			url: `${BASE_URL}/cloud_api/phone/workspace/list`,
			method: "POST",
			header: {
				'Content-Type': 'application/json'
			},
			data: {
				"access_token": token,
				"workspaces_id": workspacesId,
				"format": "tree",
				"parent_path": "",
				"filter_type": ""
			},
			success: (res) => {
				if (res.statusCode === 200) {
					const respond = res.data
					if (respond.success) {
						resolve(respond.data)
					} else {
						const msg = respond?.error || '获取工作区文件目录出错啦'
						reject(msg)
					}
				} else {
					reject(`获取工作区文件目录失败：${res.statusCode}`)
				}
			},
			fail: (err) => {
				const msg = err.errMsg || '网络错误'
				reject(msg)
			}
		})
	})
}