import { debounce } from 'lodash-es'
import { Storage } from '@/utils/storage'

export interface Permissions {
    listen: () => void
    stop: () => void
    gotoAppPermissionSetting: () => void
}

export interface RequestPermissionListener {
    onRequest: (e: any) => void
    onConfirm: (e: any) => void
    onComplete: (e: any) => void
    stop: () => void
}

/**
 * 权限申请说明（注：仅适用于 Android）
 * @link https://uniapp.dcloud.net.cn/tutorial/app-nativeresource-android.html#permissions
 */
export function getRequestPermissionTipMessage(id: string) {
    switch (id) {
        case 'android.permission.INTERNET':
            return { name: '网络权限', message: '允许访问网络，便于使用应用相关功能。' }
        case 'android.permission.CAMERA':
            return {
                name: '相机权限',
                message:
                    '允许访问摄像头，便于拍照上传照片/图片用于意见反馈、保存相册、缓存数据提升访问速度等场景中拍摄照片。',
            }
        case 'android.permission.READ_MEDIA_IMAGES':
        case 'android.permission.READ_EXTERNAL_STORAGE':
        case 'android.permission.WRITE_EXTERNAL_STORAGE':
            return {
                name: '存储权限',
                message:
                    '允许访问存储，便于上传照片/图片用于意见反馈、保存相册、缓存数据提升访问速度等场景中读取和写入相册和文件内容。',
            }
        case 'android.permission.READ_PHONE_STATE':
        case 'android.permission.ACCESS_NETWORK_STATE':
        case 'android.permission.ACCESS_WIFI_STATE':
            return {
                name: '设备状态权限',
                message: '允许访问设备状态，便于收集应用异常信息。',
            }
        case 'android.permission.ACCESS_COARSE_LOCATION':
        case 'android.permission.ACCESS_FINE_LOCATION':
        case 'android.permission.ACCESS_LOCATION_EXTRA_COMMANDS':
        case 'android.permission.ACCESS_MOCK_LOCATION':
            return {
                name: '位置权限',
                message: '允许访问位置信息，便于确认上传随手拍问题时的所在位置。',
            }
        case 'android.permission.INSTALL_PACKAGES':
        case 'android.permission.REQUEST_INSTALL_PACKAGES':
            return {
                name: '安装应用权限',
                message: '允许访问安装应用，便于应用更新包的安装。',
            }
    }
}

export function usePermissions(): Permissions {
    const system = uni.getSystemInfoSync()
    const listener = ref<RequestPermissionListener>()

    const requestPermissionId = ref<string>()
    const show = ref(false)
    const debounceShow = debounce((value) => {
        show.value = value
    }, 200)

    watch(
        () => show.value,
        (value) => {
            const id = requestPermissionId.value

            if (value) {
                const statusBarHeight = system.statusBarHeight
                const navigationBarHeight = system.platform === 'android' ? 48 : 44
                const totalHeight = statusBarHeight + navigationBarHeight
                let view = new plus.nativeObj.View(id, {
                    top: '0px',
                    left: '0px',
                    width: '100%',
                    backgroundColor: 'rgba(0,0,0,0.3)',
                })
                view.drawRect(
                    {
                        color: '#fff',
                        radius: '5px',
                    },
                    {
                        top: `${totalHeight}px`,
                        left: '5%',
                        width: '90%',
                        height: '100px',
                    },
                )
                view.drawText(
                    '权限使用说明',
                    {
                        top: `${totalHeight + 5}px`,
                        left: '8%',
                        height: '30px',
                    },
                    {
                        align: 'left',
                        color: '#000',
                        size: '20px',
                    },
                )
                view.drawText(
                    getRequestPermissionTipMessage(id)?.message,
                    {
                        top: `${totalHeight + 35}px`,
                        height: '60px',
                        left: '8%',
                        width: '84%',
                    },
                    {
                        whiteSpace: 'normal',
                        size: '14px',
                        align: 'left',
                        color: '#656563',
                    },
                )
                view.show()
                view = null
            } else {
                // @ts-expect-error
                let view = plus.nativeObj.View.getViewById(id)
                view && view.close()
                view = null
                requestPermissionId.value = null
            }
        },
    )

    function listen() {
        // #ifdef APP-PLUS
        // FIXED: 由于 iOS 下无问题，此处仅处理安卓平台的权限申请问题
        if (system.platform === 'android') {
            // @ts-expect-error
            listener.value = uni.createRequestPermissionListener()
            listener.value.onConfirm((e: string[]) => {
                console.log('onConfirm', e)

                // 创建弹窗视图
                requestPermissionId.value = e[0]
                debounceShow(true)
            })
            listener.value.onComplete((e: string[]) => {
                console.log('onComplete', e)

                // 关闭弹窗视图
                const id = e[0]
                // 判断是否触发了对应的权限显示
                if (requestPermissionId.value !== id && Storage.get(id) !== 'granted') {
                    if (Storage.get(id) === 'denied') {
                        handlerPermissionModal(id)
                    } else {
                        plus.android.requestPermissions(e, (v) => {
                            console.log('requestPermissions', e, v)

                            if (v.granted.includes(id)) {
                                Storage.set(id, 'granted')
                            }
                            if (v.deniedAlways.includes(id)) {
                                Storage.set(id, 'denied')
                                handlerPermissionModal(id)
                            }
                        })
                    }
                } else {
                    requestPermissionId.value = id
                    debounceShow(false)
                }
            })
            console.log('[usePermissions] start listen...')
        }
        // #endif
    }

    function stop() {
        // #ifdef APP-PLUS
        listener.value?.stop()
        // 清除权限标记，防止用户主动设置了权限允许重新打开仍然无法使用的问题
        Storage.keys().forEach((key) => {
            if (key.startsWith('android.permission.')) {
                Storage.remove(key)
            }
        })
        console.log('[usePermissions] stop listen')
        // #endif
    }

    // 权限设置弹窗
    const settingConfirmVisible = ref(false)
    function handlerPermissionModal(id: string) {
        if (settingConfirmVisible.value) {
            return
        }

        settingConfirmVisible.value = true
        Message.confirm(`缺少${getRequestPermissionTipMessage(id).name}，立即去设置开启？`, '温馨提示', '去设置').then(
            (confirm) => {
                settingConfirmVisible.value = false
                if (confirm) {
                    try {
                        Storage.remove(id)
                        gotoAppPermissionSetting()
                    } catch (e) {
                        console.error('[Permissions] gotoAppPermissionSetting fail!', e)
                    }
                }
            },
        )
    }

    // 跳转到 APP 权限设置
    function gotoAppPermissionSetting() {
        // #ifdef APP-PLUS
        if (system.platform === 'ios') {
            const UIApplication = plus.ios.importClass('UIApplication')
            const application = UIApplication.sharedApplication()
            const NSURL = plus.ios.importClass('NSURL')
            const setting = NSURL.URLWithString('app-settings:')
            application.openURL(setting)

            plus.ios.deleteObject(setting)
            plus.ios.deleteObject(NSURL)
            plus.ios.deleteObject(application)
        } else {
            // console.log(plus.device.vendor);
            const Intent = plus.android.importClass('android.content.Intent')
            const Settings = plus.android.importClass('android.provider.Settings')
            const Uri = plus.android.importClass('android.net.Uri')
            const mainActivity = plus.android.runtimeMainActivity()
            // @ts-expect-error
            const intent = new Intent()
            // @ts-expect-error
            intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
            // @ts-expect-error
            const uri = Uri.fromParts('package', mainActivity.getPackageName(), null)
            intent.setData(uri)
            // @ts-expect-error
            mainActivity.startActivity(intent)
        }
        // #endif
    }

    return {
        listen,
        stop,
        gotoAppPermissionSetting,
    }
}
