/*
 * @Author: micky
 * @Date: 2024-08-10 15:24:06
 * @LastEditors: micky
 * @LastEditTime: 2024-09-03 22:08:32
 * @FilePath: \chargingpile-uniapp\src\hooks\useLockFn.ts
 */
import { computed, nextTick, onMounted, ref, unref } from 'vue'
import { apiCategoryList } from '@/api/user'
import { getRect, toast } from '@/utils/util'
import { smsSend } from '@/api/app'
import { SMSEnum } from '@/enums/appEnums'
import { onLoad } from '@dcloudio/uni-app'
import { useDictData } from './useDictOptions'

export function useLockFn(fn: (...args: any[]) => Promise<any>) {
    const isLock = ref(false)
    const lockFn = async (...args: any[]) => {
        if (isLock.value) return
        isLock.value = true
        try {
            const res = await fn(...args)
            isLock.value = false
            return res
        } catch (e) {
            isLock.value = false
            throw e
        }
    }
    return {
        isLock,
        lockFn
    }
}
export function useToggle() {
    const show = ref(false)
    const handleToggle = (visible = false) => {
        show.value = !visible
    }
    return {
        show,
        handleToggle
    }
}

/**短信验证码 */
export function useSMS(profileForm: any) {
    const seconds = ref(60)
    const uCodeRef = ref()
    const tips = ref('')

    /**短信验证 */
    const handleSendSMS = async () => {
        if (!profileForm.mobile) return
        if (unref(uCodeRef).canGetCode) {
            uni.showLoading({
                title: '正在获取验证码'
            })
            try {
                await smsSend({
                    scene: SMSEnum.SMS_CODE,
                    mobile: profileForm.mobile
                })
                uni.hideLoading()
                toast('验证码已发送')
                uCodeRef.value.start()
            } catch (error) { }
        } else {
            toast('倒计时结束后再发送')
        }
    }
    /**显示验证码文本 */
    const handleCodeText = (text: string) => {
        tips.value = text
    }

    return {
        tips,
        seconds,
        uCodeRef,
        handleSendSMS,
        handleCodeText
    }
}

export function useExpanded(defaultHeight = 200) {
    const expanded = ref(false)

    const parseText = computed(() => (expanded.value ? '收起' : '展开'))
    const parseIcon = computed(() => (expanded.value ? 'icon-up' : 'icon-down'))
    const wrapperStyle = computed(() => ({
        height: expanded.value ? 'auto' : defaultHeight * 2 + 'rpx',
        overflow: expanded.value ? 'auto' : 'hidden'
    }))

    return {
        expanded,
        parseText,
        parseIcon,
        wrapperStyle
    }
}

export function useModulePower() {
    const { dictData }: { dictData: any } = useDictData(['modulePower'])
    const parseModulePower = computed(
        () => (val: number) => dictData.modulePower.find((item) => item.value == val)?.name ?? '--'
    )
    return {
        parseModulePower
    }
}
