import { ref } from 'vue'
import { onLoad, onReady } from '@dcloudio/uni-app'

export const useDrawSignature = (canvasId, config = {}) => {
    let ctx = null
    let isButtonDown = false
    let points = []
    let isSigned = ref(false)

    onLoad(() => {
        ctx = uni.createCanvasContext(canvasId)
        // 设置画笔样式
        ctx.lineWidth = 4
        ctx.lineCap = 'round'
        ctx.lineJoin = 'round'
    })

    onReady(() => {
        if (config.path) {
            const query = uni.createSelectorQuery()
            query
                .select('#' + canvasId)
                .fields({ size: true }, (data) => {
                    if (data) {
                        uni.getImageInfo({
                            src: config.path,
                            success: (res) => {
                                const { width, height } = res
                                // 计算缩放比例
                                const scale = Math.min(data.width / width, data.height / height)
                                // 计算绘制的宽高
                                const drawWidth = width * scale
                                const drawHeight = height * scale
                                // 绘制图片
                                ctx.drawImage(res.path, 0, 0, drawWidth, drawHeight)
                                ctx.draw(true)
                                isSigned.value = true
                            },
                            fail: (err) => {
                                console.log(err)
                            }
                        })
                    }
                })
                .exec()
        }
    })

    // 触摸开始，获取到起点
    const touchStart = (e) => {
        let startPoint = { X: e.changedTouches[0].x, Y: e.changedTouches[0].y }
        points.push(startPoint) // 把起点存起来
        ctx.beginPath() // 每次触摸开始，开启新的路径
        isButtonDown = true
    }

    // 触摸移动，获取到路径点
    const touchMove = (e) => {
        if (isButtonDown) {
            let movePoint = { X: e.changedTouches[0].x, Y: e.changedTouches[0].y }
            points.push(movePoint) // 存点
            let len = points.length
            if (len >= 2) {
                draw() // 绘制路径
            }
        }
    }

    // 触摸结束，将未绘制的点清空防止对后续路径产生干扰
    const touchEnd = () => {
        points = []
        isButtonDown = false
    }

    // 绘画
    const draw = () => {
        let point1 = points[0]
        let point2 = points[1]
        points.shift()
        ctx.moveTo(point1.X, point1.Y)
        ctx.lineTo(point2.X, point2.Y)
        ctx.stroke()
        ctx.draw(true)
        isSigned.value = true
    }

    const clear = () => {
        ctx.clearRect(0, 0, 1000, 1000)
        ctx.draw(true)
        isSigned.value = false
    }

    const getPath = (canvasId) => {
        uni.showLoading({
            title: '保存中...',
            mask: true
        })
        return new Promise((resolve, reject) => {
            uni.canvasToTempFilePath({
                canvasId,
                success(data) {
                    resolve(data.tempFilePath)
                },
                fail(err) {
                    reject(err)
                },
                complete() {
                    uni.hideLoading()
                }
            })
        })
    }
    return {
        isSigned,
        touchStart,
        touchMove,
        touchEnd,
        clear,
        getPath
    }
}
