export type SplitOptionsType = {
    columns: number // 横向分割几块
    rows: number // 纵向分割几块
}

/**
 * @description 切割图片
 * @param {String} path  图片地址
 * @param {SplitOptionsType} options `{ columns: 2, rows: 2 }`
 */
export const useSplit = (path: string, options: SplitOptionsType) => {
    const { columns, rows } = options
    if (!path) {
        throw Error('请传入图片地址')
    }
    if (!columns && !rows) {
        throw Error('请传入columns和rows')
    }

    // 获取图片
    const getImages = () => {
        return new Promise((resolve, reject) => {
            // #ifdef H5
            const image: HTMLImageElement = new Image()
            // 图片加上时间错（防止canvas污染跨域
            image.setAttribute('src', path + '?' + new Date().getTime())
            // 图片设置跨域属性（防止canvas污染跨域
            image.setAttribute('crossOrigin', '')
            image.onload = () => {
                resolve(split(image.width, image.height, image))
            }
            image.onerror = (err) => {
                reject(err)
            }
            // #endif

            // #ifdef MP
            // 获取图片信息
            uni.getImageInfo({
                src: path,
                success: (image: UniApp.GetImageInfoSuccessData) => {
                    resolve(split(image.width, image.height, image))
                },
                fail: (error) => {
                    reject(error)
                }
            })
            // #endif
        })
    }

    // 拆分图片
    const split = async (
        width: number,
        height: number,
        ref: HTMLImageElement | UniApp.GetImageInfoSuccessData
    ) => {
        // #ifdef MP
        // 创建一个离屏的canvas（也就是说不需要在标签页上使用
        const canvas: UniApp.OffscreenCanvas = uni.createOffscreenCanvas({
            type: '2d',
            width: width,
            height: height
        })
        const context: CanvasRenderingContext2D = canvas.getContext('2d')
        const image: ImageData = canvas.createImage()
        // 等待图片加载
        await new Promise(resolve => {
            image.src = path
            image.onload = resolve
        })
        context.clearRect(0, 0, width, height)
        context.drawImage(image, 0, 0, width, height)
        return getList(context)
        // #endif
        // #ifdef H5
        const canvas: HTMLCanvasElement = document.createElement('canvas')
        canvas.width = width
        canvas.height = height
        const ctx: CanvasRenderingContext2D = canvas.getContext('2d')
        // @ts-ignore
        ctx.drawImage(ref, 0, 0, width, height)
        return getList(ctx)
        // #endif
    }

    // 得到切割后的图片列表
    const getList = (ctx: CanvasRenderingContext2D) => {
        const width: number = ctx.canvas.width / columns
        const height: number = ctx.canvas.height / rows
        const list: any[] = []
        for (let i = 0; i < rows; i++) {
            const listFirst = []
            for (let k = 0; k < columns; k++) {
                const path = getPart(
                    ctx,
                    k * width,
                    i * height,
                    width,
                    height
                )
                listFirst.push(path)
            }
            list.push(...listFirst)
        }
        return list
    }

    // 得到canvas的指定部分
    const getPart = (
        ctx: CanvasRenderingContext2D,
        x: number,
        y: number,
        w: number,
        h: number
    ) => {
        // #ifdef MP
        const canvas: UniApp.OffscreenCanvas = uni.createOffscreenCanvas({
            type: '2d',
            width: w,
            height: h
        })
        const context: CanvasRenderingContext2D = canvas.getContext('2d')
        const data: ImageData = ctx.getImageData(x, y, w, h)
        context.putImageData(data, 0, 0)
        return canvas.toDataURL('image/png', 1)
        // #endif
        // #ifdef H5
        const canvas: HTMLCanvasElement = document.createElement('canvas')
        canvas.width = w
        canvas.height = h
        const data: ImageData = ctx.getImageData(x, y, w, h)
        const context: CanvasRenderingContext2D = canvas.getContext('2d')
        context.putImageData(data, 0, 0)
        return canvas.toDataURL('image/png', 1)
        // #endif
    }

    return {
        getImages
    }
}
