import appSettings from '@/core/config/app-settings'
import { staticAssetPath } from './cdn-assets'

const RESIZE_MODES = ['m_lfit', 'm_mfit', 'm_fill', 'm_fixed']

export function buildOssUrl(
	url,
	width = 120,
	height = 120,
	modeIndex = 2,
	kind = '',
	format = 'jpg',
	resizeTag = 'resize',
	scale = 3
) {
	const pipeline = [
		'?x-oss-process=image',
		'auto-orient,1',
		'interlace,1',
		'format,jpg',
		'quality,q_90',
		'sharpen,50',
		'resize,m_fixed,w_120,h_120'
	]
	if (format === 'png') pipeline[3] = 'format,png'
	const mode = RESIZE_MODES[modeIndex] || RESIZE_MODES[2]
	const w = width * scale
	const h = height * scale
	if (width === 0) {
		pipeline[6] = `${resizeTag},${mode},h_${h}`
	} else if (height === 0) {
		pipeline[6] = `${resizeTag},${mode},w_${w}`
	} else {
		pipeline[6] = `${resizeTag},${mode},w_${w},h_${h}`
	}

	if (!url) {
		if (kind === 'transparent') return ''
		if (kind === 'avatar') return staticAssetPath('/common/mine_def_touxiang_3x.png')
		return staticAssetPath('/common/img_default3x.png')
	}
	if (/^data:image\//.test(url)) return url
	if (/^https?:\/\//.test(url)) {
		pipeline.pop()
		return kind === 'video' ? url : url + pipeline.join('/')
	}
	const suffix = pipeline.join('/')
	const absolute = appSettings.cdnurl + url
	return kind === 'video' ? absolute : absolute + suffix
}
