<template>
    <div v-if="showDraw">
        <div class="header">
            <div class="top-warp">
                <div class="name">
                    {{name}}
                </div>
                <a href="javascript:;" @click.prevent="handlePrevPageClick">关闭</a>
            </div>
            <section class="swatch-warp">
                <a href="" @click.prevent="canvasUndo($event)" class="swatch-item">
                    <span class="iconfont"> &#xe990;</span>
                    撤销
                </a>
                <a href="" @click.prevent="canvasRotate($event)" class="swatch-item">
                    <span class="iconfont">&#xe12d;</span>
                    旋转
                </a>
                <div class="swatch-item doodlesMore" :class=" way == 'doodles' && doodleNot ? 'isDoodles' : '' ">
                    <label for="doodles" class="way-lable" :class=" way == 'doodles' ? '': 'way-isNot' ">
                        <span class="iconfont">&#xe12f;</span>
                        涂鸦
                    </label>
                    <input type="radio" id="doodles" name="way" value="doodles" v-model="way" class="way-radio">
                    <div class="doodlesShow">
                        <ul class="doodleSlider">
                            <li v-for="(item,index) in strokes"
                                :key="index"
                                :class="lineWidth == item ? 'activeLine': '' ">
                                <label :for="'strokes'+index" class="stroke-l" >
                                    <div class="strokes" :style="{width:item + 2 +'px' , height:item + 2 +'px'}"></div>
                                </label>
                                <input type="radio" :id="'strokes'+index" name="strokes" :value="item" v-model="lineWidth" class="way-radio" @change="way ='doodles'">
                            </li>
                        </ul>
                        <ul class="colorSlider">
                            <li v-for="(item,index) in strokesColor"
                                :key="index"
                                :class="color == item ? 'activeLine': '' ">
                                <input type="radio" name="color" :id="'col'+ index" v-model="color" :value="item" class="way-radio col-r" @change="way ='doodles'">
                                <label :for="'col'+ index" class="col-l" :style="{backgroundColor: item}">&nbsp;</label>
                            </li>
                        </ul>
                    </div>
                </div>
                <div class="swatch-item">
                    <label for="clear" class="way-lable" :class=" way == 'clear' ? '': 'way-isNot' ">
                        <span class="iconfont">&#xe12e;</span>
                        橡皮擦
                    </label>
                    <input type="radio" id="clear" name="way" value="clear" v-model="way" class="way-radio">
                </div>
                <div class="swatch-item">
                    <label for="move" class="way-lable" :class=" way == 'move' ? '': 'way-isNot' ">
                        <span class="iconfont">&#xe12c;</span>
                        移动
                    </label>
                    <input type="radio" id="move" name="way" value="move" v-model="way" class="way-radio">
                </div>
            </section>
        </div>
        <div class="canvas-box">
            <section class="canvas-warp" ref="canvasWarp" :style="{ width : width , height : height }">
                <canvas
                    class="ground"
                    ref="ground">
                </canvas>
                <canvas
                    id="canvas"
                    class="canvas"
                    ref="canvas"
                    @touchstart="canvasDown($event)"
                    @touchmove="canvasMove($event)"
                    @touchend="canvasUp($event)"
                    @touchcancel="canvasUp($event)">
                    请用Chrome浏览器打开当前页面
                </canvas>
            </section>
        </div>
        <div class="foot-warp">
            <a href="#" class="imgUlr-prev imgUlr-btn iconfont" title="展示上一张" @click.prevent="imgUlrPrev()">&#xe111;</a>
            <span class="imgUlr-btn imgUlr-show"> {{ isthumbnailNow + 1 }} / {{ imgUlr.length }} </span>
            <a href="#" class="imgUlr-next imgUlr-btn iconfont" title="展示下一张" @click.prevent="imgUlrNext()">&#xe112;</a>
             <a href="#" class="imgUlr-btn imgUlr-re" @click.prevent="reDraw">重置全部</a>
            <a href="#" class="imgUlr-btn imgUlr-save" @click.prevent="downImg()">保存全部</a>
        </div>
        <!-- @on-click-menu="click" -->
        <actionsheet v-model="showMenusRotate" :menus="menusRotate" @on-click-menu-delete="showMenusRotateIsY()" show-cancel></actionsheet>
        <toast v-model="showPositionValue" type="text" :time="800" is-show-mask text="不能再继续撤销" position="top">不能再继续撤销了</toast>
    </div>
</template>

<script>
import {base64ToFile} from '@/assets/utils/formatFile'
import ossTool from '@/assets/utils/ossTool.js'
import ossConfig from '@/assets/ossConfig.js'
import ossPaths from '@/assets/ossPaths.js'
import { Actionsheet, TransferDom, Toast } from 'vux'
export default {
    name: 'Draw',
    components: {
        Actionsheet,
        Toast
    },
    directives: {
        TransferDom
    },
    props: {
        name: {
            type: String
        },
        width: {
            type: String,
            default: ''
        },
        height: {
            type: String,
            default: '600px'
        },
        imgUlr: {
            type: Array,
            default: () => []
        },
        showDraw: {
            type: Boolean,
            default: false
        }
    },
    watch: {
        imgUlr: {
            immediate: true,
            handler (newVal, oldVal) {
                console.log(newVal)
                this.imgList = JSON.parse(JSON.stringify(newVal))
                this.convertRotateImg(this.putThumbImg(this.isthumbnailNow).showImg, this.lastStatus.rotate)
            }
        },
        count (newVal) {
            console.log(newVal)
            if (newVal === 0) {
                let arr = this.imgList.map(item => {
                    return item.src.split('.com/')[1]
                })
                this.$emit('imgSave', arr)
            }
        }
    },
    data () {
        return {
            strokes: [1, 3, 5],
            strokesColor: ['#ff0000', '#0f0f0f', '#0d5ee4'],
            start: {
                x: 0,
                y: 0
            },
            end: {
                x: 0,
                y: 0
            },
            color: '#ff0000',
            lineWidth: 1,
            way: 'doodles',
            mouseDown: false,
            canvasHistory: [],
            step: -1,
            isthumbnailNow: 0, // 第一图片
            isthumbnailOld: '',
            saveCanvasImg: [],
            isDoodle: false,
            doodleNot: true,
            config: {
                maxScale: 4.0, // 可修改最大放大倍数
                minScale: 0.1, // 仅申明最小缩小倍数
                scale: 1.0 // 原始默认倍数（目前仅用于画笔比例）
            },
            lastStatus: {
                width: 0,
                height: 0,
                translateX: 0,
                translateY: 0,
                rotate: 0,
                scale: 1.0
            },
            touchStart: [],
            touchNow: [],
            distance: {},
            origin: '',
            scaleArr: [],
            theScale: 0,
            theWay: 0,
            clearlineWidth: 10, // 格外添加大小
            showMenusRotate: false,
            showPositionValue: false,
            menusRotate: {
                'title.noop': '此操作将删除全部标记?<br/><span style="color:#666;font-size:12px;">删除后就无法撤消了哦</span>',
                delete: '<span style="color:red">删除标记并旋转</span>'
            },
            ossConfig: ossConfig.bussinessFileBucket, // oss 文件上传配置
            ossPath: ossPaths.classHomeWork.img, // oss 文件存储路径
            ossParams: {
                accessKeyId: '',
                accessKeySecret: '',
                stsToken: '',
                endpoint: ossConfig.bussinessFileBucket.domain,
                bucket: ossConfig.bussinessFileBucket.bucket,
                region: ossConfig.bussinessFileBucket.region,
                cname: true
            },
            fileDomain: ossConfig.bussinessFileBucket.domain, // 图片域名
            imgList: [],
            deleteImgs: [], // 需要从oss删除的图片
            count: 0
        }
    },
    computed: {
        ground () {
            return this.$refs.ground
        },
        canvas () {
            return this.$refs.canvas
        },
        canvasW () {
            return this.$refs.canvas.width
        },
        canvasH () {
            return this.$refs.canvas.height
        },
        canvasWarp () {
            return this.$refs.canvasWarp
        },
        canvasWarpW () {
            return this.$refs.canvasWarp.clientWidth
        },
        canvasWarpH () {
            return this.$refs.canvasWarp.clientHeight
        }

    },
    methods: {
        initCanvas () {
            let $this = this
            $this.convertRotateImg($this.putThumbImg($this.isthumbnailNow).showImg, $this.lastStatus.rotate)
        },
        drawBoxByStatus (x, y) {
            let $this = this
            let imgX = x
            let imgY = y
            let lastStatus = $this.lastStatus

            $this.lastStatus.width = lastStatus.canvasW * lastStatus.scale
            $this.lastStatus.height = lastStatus.canvasH * lastStatus.scale

            console.log('----drawBoxByStatus S----')
            console.log('X', x)
            console.log('Y', y)

            // 最大移动边界值
            if (lastStatus.scale <= $this.config.minScale) {
                imgX = Math.max(Math.min(x, $this.canvasWarpW - lastStatus.width), 0)
                imgY = Math.max(Math.min(y, $this.canvasWarpH - lastStatus.height), 0)
            } else if (lastStatus.scale <= $this.config.oScale) {
                if (lastStatus.width > $this.canvasWarpW) {
                    imgX = Math.min(Math.max(x, $this.canvasWarpW - lastStatus.width), 0)
                    imgY = Math.max(Math.min(y, $this.canvasWarpH - lastStatus.height), 0)
                } else {
                    imgX = Math.max(Math.min(x, $this.canvasWarpW - lastStatus.width), 0)
                    imgY = Math.min(Math.max(y, $this.canvasWarpH - lastStatus.height), 0)
                }
            } else {
                imgX = Math.min(Math.max(x, $this.canvasWarpW - lastStatus.width), 0)
                imgY = Math.min(Math.max(y, $this.canvasWarpH - lastStatus.height), 0)
            }

            // 设置画板距离
            $this.canvas.style.transform = $this.ground.style.transform = 'matrix(' + lastStatus.scale + ', 0, 0, ' + lastStatus.scale + ', ' + imgX + ', ' + imgY + ')'

            $this.canvas.style.transformOrigin = $this.ground.style.transformOrigin = `left top`

            $this.lastStatus.translateX = imgX || lastStatus.translateX // 当触摸的地方离开画板就没焦点
            $this.lastStatus.translateY = imgY || lastStatus.translateY
        },

        getDistance (start, stop) {
            return Math.sqrt(Math.pow((stop.x - start.x), 2) + Math.pow((stop.y - start.y), 2))
        },
        // 取多指中间值
        getCenter (pointers) {
            let pointersLength = pointers.length

            if (pointersLength === 1) {
                return {
                    x: Math.round(pointers[0].clientX),
                    y: Math.round(pointers[0].clientY)
                }
            }

            let x = 0
            let y = 0
            let i = 0
            while (i < pointersLength) {
                x += pointers[i].clientX
                y += pointers[i].clientY
                i++
            }

            return {
                x: Math.round(x / pointersLength),
                y: Math.round(y / pointersLength)
            }
        },
        // 画板点击
        canvasDown (event) {
            event.preventDefault()
            let $this = this
            let canvas = $this.canvas
            let ctx = canvas.getContext('2d')

            $this.mouseDown = true

            $this.start = $this.end = $this.canvasMousePos(canvas, event)

            let touches = event.touches
            let tlength = touches.length

            $this.theScale = $this.lastStatus.scale
            $this.theWay = $this.way

            if (tlength >= 2) {
                $this.distance.start = $this.distance.stop = $this.getDistance({
                    x: event.touches[0].screenX,
                    y: event.touches[0].screenY
                }, {
                    x: event.touches[1].screenX,
                    y: event.touches[1].screenY
                })
            } else if (tlength === 1 && $this.way === 'doodles') {
                ctx.strokeStyle = $this.color
                ctx.lineWidth = $this.lineWidth

                $this.start = $this.canvasMousePosScale($this.start)
                // 绘画
                ctx.save()
                ctx.beginPath()
                ctx.moveTo($this.start.x, $this.start.y)
            } else if (tlength === 1 && $this.way === 'clear') {
                $this.start = $this.canvasMousePosScale($this.start)

                ctx.clearRect($this.start.x, $this.start.y, $this.lineWidth + $this.clearlineWidth, $this.lineWidth + $this.clearlineWidth)
            }
        },
        // 画板移动
        canvasMove (event) {
            event.preventDefault()
            let $this = this
            let canvas = this.canvas
            let ctx = canvas.getContext('2d')
            let mouseDown = $this.mouseDown

            let touches = event.touches
            let tlength = touches.length
            let lastStatus = $this.lastStatus

            $this.end = $this.canvasMousePos(canvas, event)

            if (tlength >= 2) {
                let end = $this.end
                let start = $this.start

                $this.distance.stop = $this.getDistance({
                    x: event.touches[0].screenX,
                    y: event.touches[0].screenY
                }, {
                    x: event.touches[1].screenX,
                    y: event.touches[1].screenY
                })
                //  两指的缩放比例
                let scale = $this.distance.stop / $this.distance.start
                let s1 = scale.toFixed(6)

                $this.lastStatus.scale = Math.max($this.config.minScale, Math.min($this.config.maxScale, ($this.theScale * s1)))

                // 额外备注：目前还不能跟着双指中心放大缩小后再绘画在画板相对应的位置
                // let gc =  $this.getCenter(event.touches)

                // let imgX = $this.getCenter.x + (-$this.getCenter.x) * scale// 缩放中心偏移量
                // let imgY = $this.getCenter.y + (-$this.getCenter.y) * scale

                // 切换移动模式
                $this.way = 'move'

                let diffX = end.x - start.x + lastStatus.translateX
                let diffY = end.y - start.y + lastStatus.translateY

                $this.drawBoxByStatus(diffX, diffY)
            } else if (mouseDown & $this.way === 'doodles' & tlength === 1) {
                $this.doodleNot = false
                $this.end = $this.canvasMousePosScale($this.end)
                ctx.lineTo($this.end.x, $this.end.y)
                ctx.stroke()
            } else if (mouseDown & $this.way === 'clear' & tlength === 1) {
                $this.end = $this.canvasMousePosScale($this.end)
                ctx.clearRect($this.end.x, $this.end.y, $this.lineWidth + $this.clearlineWidth, $this.lineWidth + $this.clearlineWidth)
            } else if (mouseDown & $this.way === 'move' & tlength === 1) {
                let diffX = $this.end.x - $this.start.x + lastStatus.translateX
                let diffY = $this.end.y - $this.start.y + lastStatus.translateY

                $this.drawBoxByStatus(diffX, diffY)
            }
        },
        // 画板抬起
        canvasUp (event) {
            event.preventDefault()
            let $this = this

            if ($this.mouseDown) {
                $this.mouseDown = false

                let diffX = Math.abs(this.end.x - this.start.x)
                let diffY = Math.abs(this.end.y - this.start.y)
                let len = Math.sqrt(diffX * diffX + diffY * diffY)

                if ($this.way === 'doodles') {
                    let canvas = $this.canvas
                    let ctx = canvas.getContext('2d')

                    ctx.closePath()
                    ctx.restore()

                    if (len > 0) {
                        $this.addHistory()
                        $this.isDoodle = true
                    }
                } else if ($this.way === 'clear') {
                    if (len > 0) {
                        $this.addHistory()
                    }
                }

                $this.start = {
                    x: 0,
                    y: 0
                }
                $this.end = {
                    x: 0,
                    y: 0
                }
                $this.way = $this.theWay || $this.way
                $this.doodleNot = true
            }
        },
        // 读取画板与鼠标的偏移量
        canvasMousePos (canvas, event) {
            let $this = this
            // let doc = document
            // let x = (doc.documentElement.scrollLeft || doc.body.scrollLeft) + (event.offsetX || event.clientX)
            // let y = (event.clientY || event.pageY) + this.getScrollTop();
            // 这种方法居然不跳??
            // let x = (event.clientX || event.pageX) + this.getScrollLeft()
            // let y = (event.clientY || event.pageY) + this.getScrollTop()

            let x = (event.targetTouches[0].pageX - canvas.offsetLeft) || (event.offsetX || event.layerX - canvas.offsetLeft)
            let y = (event.targetTouches[0].pageY - canvas.offsetTop) || (event.offsetY || event.layerY - canvas.offsetTop)

            let box = $this.canvasWarp.getBoundingClientRect()
            let boxTop = parseInt(box.top)
            let boxLeft = parseInt(box.left)

            return {
                x: x - $this.lastStatus.translateX - boxLeft,
                y: y - $this.lastStatus.translateY - boxTop
            }
        },
        // 放大缩小后的画布偏移
        canvasMousePosScale (end) {
            let $this = this
            return {
                x: end.x / ($this.lastStatus.scale / $this.config.scale),
                y: end.y / ($this.lastStatus.scale / $this.config.scale)
            }
        },
        // 拖动
        dragOver (event) {
            event.preventDefault()
        },
        // 旋转
        canvasRotate (event) {
            event.preventDefault()

            let $this = this

            let isDoodle = $this.isDoodle

            if (!isDoodle) {
                $this.getCanvasRotate()
                $this.convertRotateImg($this.putThumbImg($this.isthumbnailNow).showImg, $this.lastStatus.rotate)
            } else {
                this.$vux.confirm.show({
                    title: '提示',
                    content: '此操作将删除全部标记, 是否继续?',
                    onCancel () {
                        this.$vux.toast.show({
                            type: 'cancel',
                            text: '已取消'
                        })
                    },
                    onConfirm () {
                        $this.getCanvasRotate()
                        $this.convertRotateImg($this.putThumbImg($this.isthumbnailNow), $this.lastStatus.rotate)
                        $this.isDoodle = false
                    }
                })
            }
        },
        showMenusRotateIsY () {
            let $this = this
            $this.getCanvasRotate()
            $this.convertRotateImg($this.putThumbImg($this.isthumbnailNow).showImg, $this.lastStatus.rotate)
            $this.isDoodle = false
            //   $this.showMenusRotate = false
        },
        // 每次旋转角度
        getCanvasRotate () {
            let $this = this
            $this.lastStatus.rotate = parseInt($this.lastStatus.rotate / 90) * 90 + 90
        },
        // 添加历史
        addHistory () {
            let $this = this
            let canvas = $this.canvas

            $this.step++
            if ($this.step < $this.canvasHistory.length) {
                $this.canvasHistory.length = $this.step
            }
            $this.canvasHistory.push(canvas.toDataURL())
        },
        // 撤销
        canvasUndo (event) {
            event.preventDefault()
            let $this = this
            if ($this.step >= 0) {
                let canvas = $this.canvas
                let ctx = canvas.getContext('2d')

                $this.step--
                ctx.clearRect(0, 0, $this.canvasW, $this.canvasH)

                let canvasPic = new Image()
                canvasPic.src = $this.canvasHistory[$this.step]

                canvasPic.addEventListener('load', () => {
                    ctx.drawImage(canvasPic, 0, 0)
                })
            } else {
                this.$vux.toast.show({text: '不能再继续撤销了', type: 'cancel'})
            }

            if ($this.step === -1) {
                $this.isDoodle = false
            }
        },
        // 两个画板合成数据流
        saveImg () {
            let $this = this
            let ground = $this.ground
            let canvas = $this.canvas

            ground.getContext('2d').drawImage(canvas, 0, 0)

            return ground.toDataURL()
        },
        // 网上拷贝的，小修改了下。理论上是支持单画板涂鸦后再转的。只是现在没时间继续调试了。
        convertRotateImg (src, orientation) {
            return new Promise((resolve, reject) => {
                this.fetchImage(src)
                    .then((img) => {
                        const { width, height } = img
                        let $this = this
                        const ground = $this.ground
                        const canvas = $this.canvas
                        const ctx = ground.getContext('2d')
                        const direction = parseInt(orientation / 90) % 4
                        switch (direction) {
                        case 1: {
                            $this.reCanvasSize(height, width)
                            // canvas.width = height
                            // canvas.height = width
                            ctx.rotate(90 * Math.PI / 180)
                            ctx.drawImage(img, 0, -height)
                            break
                        }
                        case 2: {
                            $this.reCanvasSize(width, height)
                            // canvas.width = width
                            // canvas.height = height
                            ctx.rotate(180 * Math.PI / 180)
                            ctx.drawImage(img, -width, -height)
                            break
                        }
                        case 3: {
                            $this.reCanvasSize(height, width)
                            // canvas.width = height
                            // canvas.height = width
                            ctx.rotate(270 * Math.PI / 180)
                            ctx.drawImage(img, -width, 0)
                            break
                        }
                        default: {
                            $this.reCanvasSize(width, height)
                            // canvas.width = width
                            // canvas.height = height
                            ctx.rotate(0)
                            ctx.drawImage(img, 0, 0)
                            break
                        }
                        }
                        this.toObjectUrl(canvas).then(resolve, reject)
                    }, reject)
            })
        },
        createCORSRequest (method, url) {
            let xhr = new XMLHttpRequest()
            if ('withCredentials' in xhr) {
                // XHR for Chrome/Firefox/Opera/Safari.
                xhr.open(method, url, true)
            } else if (typeof XDomainRequest !== 'undefined') {
                // XDomainRequest for IE.
                xhr = new XDomainRequest()
                xhr.open(method, url)
            } else {
                // CORS not supported.
                xhr = null
            }
            return xhr
        },
        createXHR () {
            if (typeof XMLHttpRequest !== 'undefined') {
                return new XMLHttpRequest()
            } else {
                throw new Error('No XHR object available.')
            }
        },
        fetchImage (url) {
            return new Promise((resolve, reject) => {
                if (RegExp(location.host + '|base64,').test(url)) {
                    const im = new window.Image()
                    console.log(im)
                    im.onload = () => {
                        resolve(im)
                    }
                    im.onerror = (err) => {
                        console.log(err)
                        // reject(new Error('errorMsg'))
                    }
                    im.src = url
                } else {
                    /* const xhr = this.createXHR()
          console.log(url)
          xhr.open('GET', url, true)
          xhr.responseType = 'blob' */
                    let req = this.createCORSRequest('GET', url)
                    req.setRequestHeader('Cache-Control', 'no-cache')
                    req.responseType = 'blob'
                    req.onload = () => {
                        const im = new window.Image()

                        im.onload = () => {
                            resolve(im)
                        }

                        im.onerror = (err) => {
                            console.log(err)
                            //   reject(new Error('errorMsg'))
                        }
                        im.src = window.URL.createObjectURL(req.response)
                    }

                    req.onerror = (err) => {
                        console.log(err)
                        reject(err)
                    }

                    req.send()
                }
            })
        },
        toObjectUrl (canvas) {
            const promise = new Promise((resolve, reject) => {
                if (!canvas) {
                    // eslint-disable-next-line prefer-promise-reject-errors
                    reject()
                } else {
                    // chrome
                    if (canvas.toBlob) {
                        canvas.toBlob((blob) => {
                            resolve(URL.createObjectURL(blob))
                        }, 'image/png', 1)
                    } else if (canvas.msToBlob) {
                        // IE.
                        const blob = canvas.msToBlob()
                        resolve(URL.createObjectURL(blob))
                    } else {
                        const data = canvas.toDataURL('image/png', 1)
                        resolve(data)
                    }
                }
            })
            return promise
        },

        // 同步两个画板的大小
        reCanvasSize (width, height) {
            let $this = this
            $this.ground.width = $this.canvas.width = $this.lastStatus.canvasW = width
            $this.ground.height = $this.canvas.height = $this.lastStatus.canvasH = height

            $this.reCanvasSizeStyle(width, height)
        },
        // 设置画板宽度
        reCanvasSizeStyle (width, height) {
            let $this = this
            let lastStatus = $this.lastStatus
            let canvasWarpH = $this.canvasWarpH
            let canvasWarpW = $this.canvasWarpW

            $this.config.minScale = lastStatus.scale = Math.min(canvasWarpW / width, canvasWarpH / height)
            $this.config.oScale = Math.max(canvasWarpW / width, canvasWarpH / height)

            lastStatus.translateX = canvasWarpW / 2 - (width * lastStatus.scale / 2)
            lastStatus.translateY = canvasWarpH / 2 - (height * lastStatus.scale / 2)

            this.drawBoxByStatus(lastStatus.translateX, lastStatus.translateY)
        },
        // 展示画板图片
        reThumbs (index) {
            let $this = this

            // 重置
            $this.lastStatus = {
                width: 0,
                height: 0,
                translateX: 0,
                translateY: 0,
                rotate: 0,
                scale: 1.0
            }
            $this.canvasHistory = []
            $this.step = -1
            $this.isDoodle = false

            let oldIndex = $this.isthumbnailOld || $this.isthumbnailNow

            $this.isthumbnailNow = index

            if (oldIndex !== index) {
                $this.convertRotateImg($this.putThumbImg($this.isthumbnailNow).showImg, $this.lastStatus.rotate)
                $this.seveThumbsCanvas(oldIndex)
                $this.isthumbnailOld = $this.isthumbnailNow
            }
        },
        // 更新画板图片
        seveThumbsCanvas (index) {
            let $this = this
            let history = {data: $this.saveImg()}
            $this.saveCanvasImg.splice(index, index + 1, history)
        },
        imgUlrPrev () {
            let $this = this
            let imgNum = $this.isthumbnailNow
            if (imgNum > 0) {
                $this.reThumbs(imgNum - 1)
            } else {
                this.$vux.toast.show({text: '已是最前一张了', type: 'cancel'})
            }
        },
        imgUlrNext () {
            let $this = this
            let imgNum = $this.isthumbnailNow
            if (imgNum < $this.imgUlr.length - 1) {
                $this.reThumbs(imgNum + 1)
            } else {
                this.$vux.toast.show({text: '已是最后一张了', type: 'cancel'})
            }
        },
        // 读取图片
        putThumbImg (index) {
            let $this = this
            let showImg = ''
            let saveCanvasImg = $this.saveCanvasImg
            let isUpdate = false
            let originObjectKey = ''
            if (this.imgUlr && this.imgUlr.length > 0) {
                let spliceImg = JSON.parse(JSON.stringify(this.imgUlr[index]))
                let spliceArr = spliceImg.src
                let spliceFinal = spliceArr.split('.com/')
                originObjectKey = spliceFinal.length ? spliceFinal[1] : ''
                if (saveCanvasImg[index]) {
                    showImg = saveCanvasImg[index].data // 转成base64的图片
                    isUpdate = true
                } else {
                    showImg = $this.imgUlr[index].src
                    isUpdate = false
                }
            }
            // originObjectKey
            return {showImg, isUpdate, originObjectKey}
        },
        // 上传到oss
        uploadOss (imgs, index) {
            ossTool.uploadFile(this.ossConfig, this.ossPath, imgs, res => {
                this.count--
                this.imgList[index].src = this.fileDomain + '/' + res.objectKey
            })
        },
        // 测试全部保存用
        downImg () {
            let $this = this
            $this.seveThumbsCanvas($this.isthumbnailNow)
            let arr = []
            for (let j = 0, len = $this.imgUlr.length; j < len; j++) {
                if ($this.putThumbImg(j).isUpdate) { // 已经涂鸦的照片
                    this.count++
                    let deleteKey = $this.imgList[j].src.split('.com/')[1] // 获取需要删除照片的objectKey
                    // ossTool.deleteFile(this.ossConfig, this.ossPath, deleteKey, () => { // 从oss删除旧的
                    arr.push(deleteKey)
                    this.uploadOss(base64ToFile($this.putThumbImg(j).showImg), j) // 转base64为File类型 上传新的涂鸦照片到oss
                    // })
                }
            }
            this.$emit('getDeleteKey', arr)
        },
        reDraw () {
            let $this = this
            $this.lastStatus = {
                width: 0,
                height: 0,
                translateX: 0,
                translateY: 0,
                rotate: 0,
                scale: 1.0
            }
            $this.canvasHistory = []
            $this.saveCanvasImg = []
            $this.step = -1
            $this.isDoodle = false
            $this.isthumbnailNow = 0
            $this.initCanvas()
        },
        handlePrevPageClick () {
            //   this.$router.go(-1)
            this.$emit('closeDraw')
        }
    },
    created () {

    },
    mounted () {
        document.addEventListener('touchmove', function (ev) {
            ev.preventDefault()
        }, {passive: false})

        this.initCanvas()
    }
}
</script>

<style lang="less" scoped>
    *{
        user-select:none;
    }
    .canvas-box{
        background: #000;
    }
    .canvas-warp{
        overflow: hidden;
        position: relative;
    }
    .canvasD{
        display: none;
    }
    .ground{

    }
    .canvas{
        -ms-touch-action: none;
        position: absolute;
        top:0;
        left:0;
    }

    @headerH: 32px;

    .header{
        width: 100%;
        color: #fff;
        background-color: #000;
    }

    .top-warp{
        height: @headerH;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 5px;

        a{
            color:#fff;
        }
    }

    .name{

    }

    .swatch-warp{
        line-height: @headerH;
        position: relative;
    }

    .iconfont{
        font-size: inherit;
    }

    .swatch-item{
        color:#fff;
        display: inline-block;
        vertical-align: top;
        padding: 0 5px;
    }

    .way-lable{
        cursor: default;
    }

    .way-lable.way-isNot{
        opacity: .75;
        cursor: pointer;
    }

    .way-radio{
        display: none;
    }

    .none{
        display: none;
    }

    .doodlesShow{
        position: absolute;
        top:@headerH;
        left: 0;
        z-index: 999;
        padding:5px 0;
        clear: left;
        // display: none;
    }

    .doodleSlider{
        float: left;
        li{
            line-height: 30px;
            width: 32px;
            text-align: center;
            margin: 0 5px 0 0;
            border: 1px transparent solid;
            display: inline-block;
            vertical-align: top;
        }

        li.activeLine .strokes{
            border-color: #FF0000;
        }

    }

    // .doodlesShow:hover .doodlesMore{
    //     display: block;
    // }

    .doodlesMore .doodlesShow{
        display: none;
    }

    .doodlesMore.isDoodles .doodlesShow{
        display: block;
    }

    .strokes{
        background-color: #fefefe;
        width: 3px;
        height: 3px;
        display: inline-block;
        border-radius: 100%;
        box-sizing: content-box;
        border: 5px transparent solid;
    }

    .swatch-color{
        width: 40px;
        padding: 0;
        text-align: center;
    }

    .colorSlider{
        float: left;
        border-left: 1px #ddd solid;
        li{
            line-height: 30px;
            width: 32px;
            text-align: center;
            margin: 0 5px 0 0;
            border: 1px #E8E8E8 solid;
            position: relative;
            display: inline-block;
            vertical-align: top;
        }

        li.activeLine::before{
            content: ' ';
            position: absolute;
            top:6px;
            left:6px;
            width: 18px;
            height: 18px;
            background-color: #fff;
        }

        // li:nth-child(2).activeLine .col-l{
        //     background-color: #E0E0E0!important;
        // }
    }

    .col-l,.stroke-l{
        display: block;
    }

    .thumb-warp{
        text-align: center;
        padding: 10px;
    }

    .thumb-list{

    }

    .foot-warp{
        padding:8px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-size: 14px;
    }

    .imgUlr-btn{
        display: inline-block;
        vertical-align: top;
        line-height: 18px;
        padding: 5px;
        border: 1px #333 solid;
        color: #333
    }
    .imgUlr-btn.imgUlr-prev{
    }

    .imgUlr-btn.imgUlr-next{

    }

    .imgUlr-btn.imgUlr-save{
        border: 1px #333 solid;
        padding: 5px 16px;
    }

    .imgUlr-btn.imgUlr-show{
        padding: 5px 10px;
        border-color: transparent;
    }

    .imgUlr-btn.imgUlr-re{

    }
</style>
