<template>
    <div class="paint" v-show="showPaint && role == 'leader'">
        <div class="toolbar">
            <ul>
                <li v-show="show == false" @click="start">
                    <i class="iconfont iconkd_tagging"></i>
                    <div>标记</div>
                </li>
                <li v-if="show" @click="end">
                    <i class="iconfont iconclose"></i>
                    <div>关闭</div>
                </li>
            </ul>
        </div>
    </div>
</template>
<script>
import { app } from "@/core"
import { objects } from "@/core/base"
import config from "@/config"
import { getRole, sendToH5,sendToApp } from "../../../socket"
import settings from "@/core/settings"
import math from "@/core/util/math"
import convertTool from "@/core/util/convertTool"
import texture from "@/core/util/texture.js"
import lerp from "@/core/util/lerp"
import transitions from "@/core/util/transitions"
import easing from "@/core/util/easing"

let meshGroup = null //new THREE.Object3D()
let circles = []
const map = texture.load(config.getStaticResource("img/scene_tabele.png?v=1"), null, null, {
    antialias: false,
})

export default {
    props: {
        showPaint: Boolean,
    },
    data() {
        return {
            role: getRole(),
            show: false,
            flags: [],
            canUndo: false,
            colorA: "#02c8ae",
            colorB: "#2e98fe",
        }
    },
    created() {
        const self = this

        if (meshGroup == null) {
            meshGroup = new THREE.Object3D()
            meshGroup.name = "shop-circles"
            if (app.ready) {
                app.model.add(meshGroup)
            } else {
                this.$bus.on("ready", function() {
                    app.model.add(meshGroup)
                })
            }
        }

        function remove() {
            setTimeout(() => {
                self.flags.shift()
                if (self.flags.length) {
                    remove()
                }
                self.updateCirclesDrawing(self.flags)
            }, 1000)
        }

        function syncAction(data) {
            if (data.type == "flags") {
                self.flags.push(data.data)
                self.updateCirclesDrawing(self.flags)
                remove()
            }
        }

        this.$bus.on("shop/sync/action", syncAction)
        this.$once("hook:beforeDestroy", () => {
            this.$bus.off("shop/sync/action", syncAction)
            this.show = false
            this.flags = []
            this.updateCirclesDrawing(this.flags)
        })
    },
    watch: {
        show() {
            sendToApp('cart',!this.show)
            this.$bus.emit("shop/header/disable", this.show)
            setTimeout(() => {
                app.play.control.noFly = this.show
            }, 300);
        },
    },
    mounted() {
        var self = this
        function draw(e) {
            if (!self.show) {
                return
            }
            const x = (e.touches[0] || e).clientX
            const y = (e.touches[0] || e).clientY
            const f = {
                sid: Date.now(),
                pos: self.transformTo3d({ x, y }),
                color: self.colorA,
            }
            self.flags.push(f)
            self.updateCirclesDrawing(self.flags)

             setTimeout(() => {
                self.flags.shift()
                self.updateCirclesDrawing(self.flags)
            }, 1000)

            sendToH5({ type: "flags", data: f })
           
        }
        const $player = document.getElementById("player")
        $player.addEventListener("mousedown", draw)
        $player.addEventListener("touchstart", draw)
        this.role = getRole()
    },
    methods: {
        start() {
            this.show = true
        },
        undo() {
            this.flags.pop()
            this.updateCirclesDrawing(this.flags)
        },
        end() {
            this.show = false
            this.flags = []
            this.updateCirclesDrawing(this.flags)
        },
        updateCirclesDrawing(flags) {
            //呈现一系列circles  其中包含已经绘制好的

            var dels = []
            circles.forEach(circle => {
                //检查是否有要删除的
                var find = flags.find(info => circle.sid == info.sid)
                if (!find) {
                    dels.push(circle)
                }
            })
            dels.forEach(circle => this.fadeCircle(circle))

            flags.forEach(info => {
                //再添加新的
                var circle = meshGroup.children.find(circle => circle.sid == info.sid)
                if (circle) {
                    //如果要修改什么属性在这修改
                } else {
                    this.createCircle(info.sid, info.pos, info.color)
                }
            })
        },

        transformTo3d(pos2d) {
            //获取三维坐标
            const data = new THREE.Vector3()
            const mouse = new THREE.Vector2()

            math.convertScreenPositionToNDC(pos2d.x, pos2d.y, mouse)

            var intersect = convertTool.getMouseIntersect(
                objects.player.camera,
                [objects.model.skybox],
                mouse
            )

            if (!intersect) {
                console.error("no intersect ??")
            } else {
                data.copy(intersect.point)
                var dir = data
                    .clone()
                    .sub(objects.player.position)
                    .normalize()
                data.copy(objects.player.position.clone().add(dir))
            }

            return data
        },
        createCircle(sid, pos, color) {
            //绘制新的圈

            var circle = new THREE.Sprite(this.getMat(color))
            circle.sid = sid
            circle.position.copy(pos)
            circle.quaternion.copy(objects.player.camera.quaternion)
            circle.scale.set(0.05, 0.05, 0.05)
            meshGroup.add(circle)
            circles.push(circle)
            /*var scale = math.getScaleForConstantSize({
                width2d:100,
                camera:objects.player.camera,
                position: pos
            })
            bubble.scale.copy(scale)*/
        },

        fadeCircle(circle) {
            //开始消失
            //console.log("fadeCircle"+circle.sid)
            var _duration = 800
            transitions.start(
                lerp.property(circle.material, "opacity", 0),
                _duration,
                () => {
                    this.removeCircle(circle)
                },
                0,
                easing[settings.transition.blendEasing],
                "shop-circles-fade",
                settings.freeze.shopCircle
            )

            //从列表中删除
            var index = circles.indexOf(circle)
            circles.splice(index, 1)
        },

        removeCircle(circle) {
            //移除某个圈 <!-- sid -->
            //var circle = meshGroup.children.find(circle=>circle.sid == sid);
            //console.log("removeC " + circle.sid)
            circle.material.dispose()
            circle.parent.remove(circle)
        },

        getMat(color) {
            /*var mat = this.materials[color]
            if (mat) return mat
            else {
                mat = new THREE.SpriteMaterial({
                    transparent: true,
                    depthTest: false,
                    map: map,
                    side: THREE.DoubleSide,
                    color: color,
                })
                this.materials[color] = mat
                return mat
            }*/
            return new THREE.SpriteMaterial({
                transparent: true,
                depthTest: false,
                map: map,
                side: THREE.DoubleSide,
                color: color,
            })
        },
    },
}
</script>
<style lang="scss" scoped>
.paint {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    z-index: 99;
    pointer-events: none !important;
    .toolbar {
        pointer-events: auto;
        position: absolute;
        right: 0.35rem;
        bottom: 4.5rem;
        padding: 0.4rem 0.2rem;
        border-radius: 30px;
        z-index: 100;
        background-color: rgba(0, 0, 0, 0.3);
        ul,
        li {
            margin: 0;
            padding: 0;
            list-style: none;
        }
        li {
            padding: 0.3px;
            text-align: center;
            font-size: 14px;
            margin-bottom: 0.5rem;
            &:last-child {
                margin-bottom: 0;
            }
            i {
                font-size: 20px;
                &.icon_cancel {
                    font-size: 22px;
                }
                // &.iconclose {
                //     font-size: 14px;
                // }
            }
        }
    }
}
</style>
