/**
 * 专注于提醒的js
 * 依赖 util.js;eventBus.js
 * 青格勒 2021年6月10日
 *
 *
 * 静默模式下只提示错误和需要确认的操作，其他提醒不提示
 */

function GetyteLength(str) {
	var length = 0
	Array.from(str).map(function (char) {
		if (char.charCodeAt(0) > 255) {
			//字符编码大于255，说明是双字节字符
			length += 2
		} else {
			length++
		}
	})

	return length
}

/**
 *
 * @param {String} message required
 * @param {Enum} type  success|warning|error
 * @param {Number} duration default 3 单位秒
 */
function ShowMessage(
	message = '',
	type = 'default',
	duration = 3,
	lock = false
) {
	if (!message) return
	if (IsSilentMode() && ['default', 'success'].includes(type)) return
	let width = Math.max(120, GetyteLength(message) * 7 + 32)
	if (type !== 'default') width += 32
	//同步调用会堵塞，造成wps崩溃
	setTimeout(() => {
		wps.ShowDialog(
			GetResourcePath() +
				`share/ui/message.html?message=${
					message && encodeURIComponent(message)
				}&type=${type}&duration=${duration}`,
			'message',
			width * window.devicePixelRatio,
			42 * window.devicePixelRatio,
			lock,
			false
		)
		//TODO UOS 试下改成1e2q
	}, 1e2)
}

/**
 *
 * @param {String} message required
 * @param {Enum} type  success|warning|error
 * @param {Number} duration default 3 单位秒
 */
function ShowLoading(
	message = '',
	instid = '',
	lock = true,
	forceTop = false,
	autoclose = 0
) {
	if (IsSilentMode && IsSilentMode()) return
	var url =
		GetResourcePath() +
		`share/ui/loading.html?message=${
			message && encodeURIComponent(message)
		}&instid=${instid}`
	if (autoclose > 0) url += '&autoclose=' + autoclose
	// setTimeout(() => {
	wps.ShowDialog(
		url,
		'loading',
		160 * window.devicePixelRatio,
		160 * window.devicePixelRatio,
		lock,
		forceTop //强制置顶需要显示Caption才能实现
	)
	// }, 100)
}

function ShowConfirm(message, type, opts = {}) {
	if (!message) return
	var instid = uuid(8)
	var url =
		GetResourcePath() +
		`share/ui/confirm.html?message=${
			message && encodeURIComponent(message)
		}&instid=${instid}`
	if (!!type) url += '&type=' + type
	if (opts.title) url += '&title=' + opts.title
	if (!opts.btns) {
		opts.btns = [{ close: true, key: 'default', text: '确定' }]
	}
	var btns = []
	opts.btns.forEach((item) => {
		var obj = Object.assign({}, item)
		if (obj.close === undefined) obj.close = true
		delete obj.callback
		btns.push(obj)
		if (item.callback)
			EventBus.Subscribe(`confirm$${instid}$${item.key}`, item.callback)
	})
	url += '&btns=' + encodeURIComponent(JSON.stringify(btns))

	setTimeout(() => {
		wps.ShowDialog(
			url,
			'loading',
			460 * window.devicePixelRatio,
			220 * window.devicePixelRatio,
			true,
			false
		)
	}, 1e2)
}
/**
 * 关闭loading提醒
 */
function CloseLoading(instid = '') {
	EventBus.Publish(`closeLoading$${instid}`, null)
}
