import type { ref,type ComponentInternalInstance, Ref } from 'vue'
import { verifyApi, getShortKeyApi, articleCaptchaApi } from '@/api/public'
import message from '@/utils/message'
import type { Res } from '@/utils/typeHelper'

const disabled : Ref<boolean> = ref(false)
const text : Ref<string> = ref('鑾峰彇楠岃瘉鐮�')

//鍙戦€侀獙璇佺爜
const sendCode = () => {
	if (disabled.value) return
	disabled.value = true
	let n = 60
	text.value = '鍓╀綑 ' + n + 's';

	const run = setInterval(() => {
		n = n - 1
		if (n < 0) {
			clearInterval(run)
		}
		text.value = '鍓╀綑 ' + n + 's'
		if (text.value < '鍓╀綑 ' + 0 + 's') {
			disabled.value = false
			text.value = '閲嶆柊鑾峰彇'
		}
	}, 1000)
}
// 鍙戦€侀獙璇佺爜閫昏緫
export function useSendCode() {
	return { text, disabled, sendCode }
}

// 鑾峰彇鐭俊楠岃瘉鐮佷笌key
export function useCmsKeyVerify() {
	//鎺ュ彈鎵嬫満鍙风爜
	const getKeyVerify = (phone : string, flag : number = 0) => {
		getShortKeyApi().then(async (res : Res) => {
			const cmsKey = res.data.key
			const data = {
				phone: phone,
				key: cmsKey,
				types: 0,
				from: 1
			}
			if (flag === 1) {
				// 鐭ヨ瘑绀惧尯楠岃瘉鐮�
				await articleCaptchaApi(phone)
					.then((res : Res) => {
						sendCode()
						message.success(res.message, 'none')
					})
					.catch((error : Res) => {
						message.error(error.message)
					})

			} else {
				await verifyApi(data)
					.then((res : Res) => {
						sendCode()
						message.success(res.message, 'none')
					})
					.catch((error : Res) => {
						message.error(error.message)
					})
			}
		})
	}

	return { getKeyVerify }
}

/**
 * 鑾峰彇鍏冪礌淇℃伅
 */
export function useBarHeight() {
	const height = ref(0)
	const getBarHeight = (ele : string, instance : ComponentInternalInstance, type = true) => {
		let query = uni.createSelectorQuery().in(instance);
		query.select(ele).fields({ size: true, rect: true }, () => { })
		query.exec((data) => {
			height.value = type ? data[0].height + 'px' : data[0].height
		})
	}
	return { height, getBarHeight }
}