// store/friendStore.js
import { TERMINAL_TYPE } from '../common/enums.js'

const friendModule = {
	namespaced: true,

	state: () => ({
		friends: [],
		timer: null
	}),

	mutations: {
		SET_FRIENDS(state, friends) {
			friends.forEach(f => {
				f.online = false
				f.onlineWeb = false
				f.onlineApp = false
			})
			state.friends = friends
		},
		UPDATE_FRIEND(state, friend) {
			const f = state.friends.find(item => item.id === friend.id)
			if (f) {
				const copy = JSON.parse(JSON.stringify(f))
				Object.assign(f, friend)
				f.online = copy.online
				f.onlineWeb = copy.onlineWeb
				f.onlineApp = copy.onlineApp
			}
		},
		REMOVE_FRIEND(state, id) {
			state.friends.filter(f => f.id === id).forEach(f => f.deleted = true)
		},
		ADD_FRIEND(state, friend) {
			state.friends.unshift(friend)
		},
		SET_ONLINE_STATUS(state, onlineTerminals) {
			state.friends.forEach(f => {
				const userTerminal = onlineTerminals.find(o => o.userId === f.id)

				if (userTerminal) {
					f.online = true
					f.onlineWeb = userTerminal.terminals.indexOf(TERMINAL_TYPE.WEB) >= 0
					f.onlineApp = userTerminal.terminals.indexOf(TERMINAL_TYPE.APP) >= 0
				} else {
					f.online = false
					f.onlineWeb = false
					f.onlineApp = false
				}
			})
		},
		SET_TIMER(state, timer) {
			state.timer = timer
		},
		CLEAR(state) {
			if (state.timer) {
				clearTimeout(state.timer)
				state.timer = null
			}
			state.friends = []
		}
	},

	actions: {
		setFriends({ commit }, friends) {
			commit('SET_FRIENDS', friends)
		},
		updateFriend({ commit }, friend) {
			commit('UPDATE_FRIEND', friend)
		},
		removeFriend({ commit }, id) {
			commit('REMOVE_FRIEND', id)
		},
		addFriend({ commit, state }, friend) {
			const exists = state.friends.some(f => f.id === friend.id)
			if (exists) {
				commit('UPDATE_FRIEND', friend)
			} else {
				commit('ADD_FRIEND', friend)
			}
		},
		setOnlineStatus({ commit }, onlineTerminals) {
			commit('SET_ONLINE_STATUS', onlineTerminals)
		},

		// 异步刷新在线状态（使用 await uni.$http.get）
		async refreshOnlineStatus({ state, commit, dispatch }) {
			const userIds = state.friends.filter(f => !f.deleted).map(f => f.id)

			if (userIds.length === 0) return

			// 调用接口：GET /user/terminal/online?userIds=xxx
			const onlineTerminals = await uni.$http.get('/api/friend/terminal/online', {
				userIds: userIds.join(',')
			})
			dispatch('setOnlineStatus', onlineTerminals.data.data)

			// 清除旧定时器
			if (state.timer) {
				clearTimeout(state.timer)
			}
			// 设置新定时器（30s后再次刷新）
			const timer = setTimeout(() => {
				dispatch('refreshOnlineStatus')
			}, 30000)
			commit('SET_TIMER', timer)
		},

		// 清空
		clear({ commit, state }) {
			if (state.timer) {
				clearTimeout(state.timer)
			}
			commit('CLEAR')
		},

		// 加载好友列表
		async loadFriend({ dispatch }) {
			try {
				const friends = await uni.$http.get('/api/friend/list')

				if (friends.data.data.all){

					dispatch('setFriends', friends.data.data.all)
					dispatch('refreshOnlineStatus')
				}

			} catch (error) {
				// 可在此处理错误，原代码 reject，此处转为 throw
				throw error
			}
		}
	},

	getters: {
		isFriend: (state) => (userId) => {
			return state.friends.filter(f => !f.deleted).some(f => f.id === userId)
		},
		findFriend: (state) => (id) => {

			return state.friends.find(f => f.id === id)
		}
	}
}

export default friendModule
