// 店铺客服聊天模块
import Vue from 'vue'
import {
	getChatLists,
	delChatSession,
	clearChatUnread,
	readAllChat
} from '@/features/mall/gateway/im'
import { STORAGE } from '@/core/constants/storage-keys'

export default {
	namespaced: true,
	state: {
		list: [],
		ischat: {
			notice: true,
			number: 0
		}
	},
	mutations: {
		setIschat(state, payload) {
			for (let i in payload) {
				for (let j in state.ischat) {
					if (i === j) {
						state.ischat[j] = payload[i]
					}
				}
			}
		}
	},
	actions: {
		async get({ state, dispatch }) {
			try {
				const res = await getChatLists()
				const rows = Array.isArray(res.data) ? res.data : (res.data && res.data.rows) || []
				state.list = rows
				let count = 0
				rows.forEach(item => { count += Number(item.count) || 0 })
				dispatch('storage', { type: 'statis', number: count })
			} catch (e) {
				console.error('[chat] get failed:', e)
			}
		},
		async del({ state, dispatch }, index) {
			const list = state.list
			const row = list[index]
			if (!row) return
			dispatch('storage', { type: 'del', number: row.count })
			uni.removeStorage({
				key: STORAGE.chatMsgPrefix + row.user_id,
				success: () => {}
			})
			try {
				await delChatSession({ id: row.user_id })
			} catch (e) {
				console.error('[chat] del failed:', e)
			}
			Vue.delete(state.list, index)
		},
		async empty({ state, dispatch }) {
			const translate = (key, fallback) => {
				try {
					const app = typeof getApp === 'function' ? getApp() : null
					const vm = app && app.$vm
					if (vm && typeof vm.$t === 'function') {
						const v = vm.$t(key)
						if (v && v !== key) return v
					}
				} catch (_) {}
				return fallback
			}
			uni.showModal({
				content: translate('chat.markAllReadConfirm', 'Mark all as read?'),
				success: async res => {
					if (!res.confirm) return
					state.list.forEach(item => { item.count = 0 })
					dispatch('storage', { type: 'empty' })
					try {
						await readAllChat()
						uni.showToast({
							title: translate('chat.markAllReadSuccess', 'Done'),
							icon: 'none'
						})
					} catch (e) {
						console.error('[chat] read failed:', e)
					}
				}
			})
		},
		async update({ state, dispatch }, { type, data, id, shop }) {
			if (type == 'del') {
				let counts = 0
				state.list.some(chat => {
					if (chat.user_id == id) {
						counts = chat.count
						chat.count = 0
						return true
					}
				})
				dispatch('storage', { type: 'del', number: counts })
				try {
					await clearChatUnread({ id })
				} catch (e) {
					console.error('[chat] update clear failed:', e)
				}
			} else if (type == 'chat' || type == 'send') {
				let content = ''
				const createtime = data.createtime
				let chat_id = 0
				if (data.message.type == 'text') {
					content = data.message.content.text
				} else if (data.message.type == 'img') {
					content = '[Image Message]'
				} else if (data.message.type == 'voice') {
					content = '[Voice Message]'
				} else if (data.message.type == 'goods') {
					content = '[Goods Message]'
				} else {
					content = '[Unknown Type Message]'
				}
				if (type == 'chat') {
					chat_id = data.form.id
					dispatch('storage', { type: 'chat' })
				} else if (type == 'send') {
					chat_id = data.to_id
				}
				const result = state.list.some(chat => {
					if (chat.user_id == chat_id) {
						if (type == 'chat') {
							chat.count += 1
						}
						chat.createtime = createtime
						chat.content = content
						return true
					}
				})
				if (!result && shop) {
					state.list.unshift({
						id: shop.id,
						user_id: shop.user_id,
						name: shop.name,
						avatar: shop.avatar,
						content: content,
						count: type == 'chat' ? 1 : 0,
						createtime: createtime
					})
				}
			}
		},
		async storage({ rootState }, { type, number }) {
			if (type == 'statis') {
				rootState.statistics.notice.chat = number
			} else if (type == 'order') {
				rootState.statistics.notice.order += 1
			} else if (type == 'notice') {
				rootState.statistics.notice.notice += 1
			} else if (type == 'chat') {
				rootState.statistics.notice.chat += 1
			} else if (type == 'del') {
				rootState.statistics.notice.chat -= number
			} else if (type == 'empty') {
				rootState.statistics.notice.chat = 0
				rootState.statistics.notice.order = 0
				rootState.statistics.notice.notice = 0
			}
			uni.setStorageSync(STORAGE.stats, rootState.statistics)
		}
	}
}
