export function formatSignTime(value) {
	if (!value) return ''
	const date = new Date(value)
	if (Number.isNaN(date.getTime())) return String(value)

	const pad = num => String(num).padStart(2, '0')
	return [
		date.getFullYear(),
		pad(date.getMonth() + 1),
		pad(date.getDate()),
	].join('.') + ` ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
}

export function getFileType(fileUrl = '') {
	const path = String(fileUrl).split('?')[0].toLowerCase()
	if (/\.(png|jpe?g|gif|webp|bmp|svg)$/.test(path)) return 'image'
	if (/\.pdf$/.test(path)) return 'pdf'
	return 'unknown'
}

export function normalizeContractRecords(payload) {
	if (!payload || !Array.isArray(payload.file)) return []

	const signTime = formatSignTime(payload.signTime)
	return payload.file.map(file => ({
		id: file.id,
		contractName: file.contractName || '合同文件',
		signTime,
		signerName: payload.signerName || '',
		merchantId: payload.merchantId,
		fileUrl: file.fileUrl || '',
		fileType: getFileType(file.fileUrl),
	}))
}

export function resolveContractFileUrl(fileUrl = '', baseUrl = '') {
	if (!fileUrl) return ''
	if (/^https?:\/\//i.test(fileUrl)) return fileUrl
	if (!fileUrl.startsWith('/')) return fileUrl

	try {
		const { origin } = new URL(baseUrl)
		return `${origin}${fileUrl}`
	} catch (e) {
		return fileUrl
	}
}

export function getUserIdFromSessionStorage(storage) {
	if (!storage || typeof storage.getItem !== 'function') return ''

	const directUserId = storage.getItem('userId')
	if (directUserId) return directUserId

	const keys = ['userInfo', 'user', 'merchantInfo', 'technicianInfo']
	for (const key of keys) {
		const userId = getUserIdFromStorageValue(storage.getItem(key))
		if (userId) return userId
	}

	if (typeof storage.key === 'function') {
		for (let index = 0; index < storage.length; index += 1) {
			const key = storage.key(index)
			if (keys.includes(key) || key === 'userId') continue

			const userId = getUserIdFromStorageValue(storage.getItem(key))
			if (userId) return userId
		}
	}

	return ''
}

function getUserIdFromStorageValue(raw) {
	if (!raw) return ''
	try {
		return findUserId(JSON.parse(raw), 0, 'userInfo')
	} catch (e) {
		return ''
	}
}

function findUserId(value, depth = 0, parentKey = '') {
	if (!value || typeof value !== 'object' || depth > 5) return ''

	const directUserId = value.userId || value.merchantId
	if (directUserId) return directUserId

	if (value.id && (isKnownUserKey(parentKey) || isLikelyUserObject(value))) return value.id

	const preferredKeys = ['merchant', 'technician', 'user', 'userInfo', 'data', 'result']
	for (const key of preferredKeys) {
		const userId = findUserId(value[key], depth + 1, key)
		if (userId) return userId
	}

	for (const key of Object.keys(value)) {
		if (preferredKeys.includes(key)) continue
		const userId = findUserId(value[key], depth + 1, key)
		if (userId) return userId
	}

	return ''
}

function isKnownUserKey(key) {
	return ['merchant', 'technician', 'user', 'userInfo', 'merchantInfo', 'technicianInfo'].includes(key)
}

function isLikelyUserObject(value) {
	return Boolean(
		value.userId ||
		value.merchantId ||
		value.auditStatus !== undefined ||
		value.serviceTag !== undefined ||
		value.cOpenid ||
		value.copenid ||
		value.cPhone ||
		value.cphone ||
		value.token
	)
}
