import UAParser from 'ua-parser-js'
import Toast from '@/components/Toast'

import { ItaskDetail } from '@/pages/api/base/type'
import { RACR_AGENT } from './constans'
import { PREVIEW_WEBP } from './constans/international'

export const handleDownloadClick = async (
    imageUrl: string,
    fileName: string,
    tFun: any,
): Promise<boolean> => {
    return new Promise<HTMLImageElement>((resolve, reject) => {
        const image = new Image()
        image.onload = () => resolve(image)
        image.onerror = () => reject(new Error('Failed to load image'))
        image.setAttribute('crossOrigin', 'Anonymous')
        image.src = imageUrl
    })
        .then((img) => {
            const canvas = document.createElement('canvas')
            canvas.width = img.width
            canvas.height = img.height
            const ctx = canvas.getContext('2d')
            // 将img中的内容画到画布上
            ctx?.drawImage(img, 0, 0, canvas.width, canvas.height)
            // 将画布内容转换为Blob
            canvas.toBlob((blob) => {
                if (!blob) return
                // blob转为同源url
                const blobUrl = window.URL.createObjectURL(blob)
                // 创建a链接
                const a = document.createElement('a')
                a.href = blobUrl
                a.download = fileName
                // 触发a链接点击事件，浏览器开始下载文件
                a.click()

                window.URL.revokeObjectURL(blobUrl)
                a.remove()
            })
            return true
        })
        .catch((e) => {
            console.error('Failed to download file', e)
            Toast({ message: tFun('toast.imageDownloadFail') })
            return false
        })
}

export function scrollToTop() {
    const c = document.documentElement.scrollTop || document.body.scrollTop
    if (c > 0) {
        window.requestAnimationFrame(scrollToTop)
        window.scrollTo(0, c - c / 8)
    }
}
export async function compositeImage(
    list: string[],
    width: number,
    height: number,
    counterSelect?: boolean,
) {
    if (list?.length === 1 && !counterSelect) return list[0]
    const canvas = document.createElement('canvas')
    canvas.width = width
    canvas.height = height

    let dataUrl = ''

    const images = list.map((item) => {
        if (item) {
            const img = new Image()
            img.src = item
            return img
        }
    })

    try {
        await Promise.all(images.map((img_1) => img_1?.decode()))
        const ctx = canvas.getContext('2d')
        if (ctx) {
            ctx.fillStyle = 'rgba(0, 0, 0, 0)'
        }
        images.forEach((item_1) => {
            if (item_1) ctx?.drawImage(item_1, 0, 0)
        })

        if (counterSelect) {
            if (ctx) {
                const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height)
                const data = imageData.data

                for (let i = 0; i < data.length; i += 4) {
                    const r = data[i]
                    const g = data[i + 1]
                    const b = data[i + 2]
                    const a = data[i + 3]

                    if (r !== 0 || g !== 0 || b !== 0 || a !== 0) {
                        data[i + 3] = 0 // Set alpha value to 0 (fully transparent)
                    } else {
                        data[i] = 117 // Set red channel to 117
                        data[i + 1] = 48 // Set green channel to 48
                        data[i + 2] = 254 // Set blue channel to 254
                        data[i + 3] = 128 // Set alpha value to 128 (semi-transparent)
                    }
                }

                ctx.putImageData(imageData, 0, 0)
            }
        }
        dataUrl = canvas.toDataURL('image/png')
        return dataUrl
    } catch (error) {
        console.log(error)
        return ''
    }
}

// 生成模型输入校验
export const verfiyInfer = (params: ItaskDetail, tFun: any) => {
    if (!params.image && params.agentName !== 'text2image') {
        Toast({ message: tFun('toast.handle.picFirst') })
        return
    }

    if (!params.mask && params.agentName !== 'text2image' && params.agentName !== 'image2image') {
        Toast({ message: tFun('toast.handle.picKeep') })
        const element = document.getElementById('myEdit')
        if (element) element.scrollTop = 0
        return
    }

    if (params.paramType === 'template') {
        if (!params.agentName) return
        if (!params?.fashionModelId && RACR_AGENT.includes(params.agentName)) {
            Toast({ message: tFun('toast.handle.maskFirst') })
            return
        }

        if (!params.locationId && params.agentName !== 'accessory') {
            Toast({ message: tFun('toast.handle.locationFirst') })
            return
        }
    }

    if (params.paramType === 'prompt' && !params.posPrompt) {
        Toast({ message: tFun('toast.handle.positive') })
        return
    }

    return true
}

export function emptyLoader(item: { src: string; width: number }) {
    return `${item.src}?w=${item.width || 276}`
}

export function previewLoader(item: { src: string }) {
    return PREVIEW_WEBP ? `${item.src}_preview.webp` : item.src
}

export function smallLoader(item: { src: string }) {
    return `${item.src}_256x256.jpeg`
}

// 手机号校验
export function validatePhoneNumber(phoneNumber: string) {
    const regEx = /^(13[0-9]|14[5-9]|15[0-3,5-9]|16[6]|17[0-8]|18[0-9]|19[1,8,9])\d{8}$/
    return regEx.test(phoneNumber)
}

export const loadImage = async (url: string) => {
    try {
        return new Promise((resolve) => {
            const img = new Image()
            img.src = url
            img.onload = () => {
                img.width = img.naturalWidth
                img.height = img.naturalHeight
                resolve({
                    width: img.width,
                    height: img.height,
                })
            }
            img.onerror = () => {
                console.log('Failed to load image:', url)
                resolve({})
            }
        })
    } catch (error) {
        console.error(error)
        return {}
    }
}

export const loginUrl = () => {
    location.href = '/login?from=' + encodeURIComponent(window.location.href)
    return
}

export const browserCheck = () => {
    const parser = new UAParser()
    const result = parser.getResult()
    console.log(`Browser: ${result.browser.name}`)
    console.log(`Version: ${result.browser.version} / ${result?.browser?.major}`)

    if (result?.browser?.name === 'Chrome' && parseInt(<string>result?.browser?.major) < 32) {
        return true
    } else if (result?.browser?.name === 'Edge' && parseInt(<string>result?.browser?.major) < 18) {
        return true
    } else if (
        result?.browser?.name === 'Safari' &&
        parseInt(<string>result?.browser?.major) < 16
    ) {
        return true
    } else if (
        result?.browser?.name === 'Firefox' &&
        parseInt(<string>result?.browser?.major) < 65
    ) {
        return true
    } else if (result?.browser?.name === 'Opera' && parseInt(<string>result?.browser?.major) < 19) {
        return true
    } else if (result?.browser?.name === 'IE') {
        return true
    }
    return false
}

export const getNewUIDGenerator = (): (() => number) => {
    let lastID = -1
    return () => {
        lastID += 1
        return lastID
    }
}

export const commonCopyText = (value: string, data: any, message: string) => {
    const logParam = window?.logger.getParams(
        window?.logger.EID.COMMON_CLICK,
        window?.logger.EVENT_TYPE.CLICK,
        {
            type: 'copy',
            ...data,
        },
    )
    window?.logger.log([logParam])

    Toast({
        message: message,
        duration: 3000,
        type: 'success',
    })
    // 创建一个临时textarea元素
    const textarea = document.createElement('textarea')
    // 设置textarea的值为要复制的文本
    textarea.value = value
    // 将textarea添加到DOM中
    document.body.appendChild(textarea)
    // 选择textarea中的文本
    textarea.select()
    // 执行复制操作
    document.execCommand('copy')
    // 移除临时textarea元素
    document.body.removeChild(textarea)
    // navigator.clipboard?.writeText(value)
}
