//查找属性
function o(w, v, i) {
    return w.getAttribute(v) || i
}
//查找对应的标签
function j(i) {
    return document.getElementsByTagName(i)
}

function jId(i) {
    return document.getElementById(i)
}

export function Lines(elementId) {
    //获取宽高
    function k() {
        if (elementId) {
            r = u.width = jId(elementId).clientWidth; //获取元素的宽度
            n = u.height = jId(elementId).clientHeight; //获取元素的高度
        } else {
            r = u.width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; //获取窗口的宽度
            n = u.height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight //获取窗口的高度
        }
    }
    //行内样式设定
    function l() {
        var i = j("script"),
            w = i.length,
            v = i[w - 1];
        return {
            l: w,
            z: o(v, "zIndex", 1), //线条显示层级
            o: o(v, "opacity", 0.8), //线条透明度
            c: o(v, "color", "255,255,255"), //线条颜色
            n: o(v, "count", 50) //线条数量
        }
    }
    //canvas实现
    function b() {
        e.clearRect(0, 0, r, n);
        var w = [f].concat(t);
        var x, v, A, B, z, y;
        t.forEach(function(i) {
            i.x += i.xa;
            i.y += i.ya;
            i.xa *= i.x > r || i.x < 0 ? -1 : 1;
            i.ya *= i.y > n || i.y < 0 ? -1 : 1;
            e.fillRect(i.x - 0.5, i.y - 0.5, 1, 1);
            for (v = 0; v < w.length; v++) {
                x = w[v];
                if (i !== x && null !== x.x && null !== x.y) {
                    B = i.x - x.x;
                    z = i.y - x.y;
                    y = B * B + z * z;
                    y < x.max && (
                        x === f && y >= x.max / 2 && (i.x -= 0.03 * B, i.y -= 0.03 * z),
                        A = (x.max - y) / x.max,
                        e.beginPath(),
                        e.lineWidth = A / 1, //线条粗细
                        e.strokeStyle = "rgba(" + s.c + "," + (A + 0.2) + ")", //线条颜色
                        e.moveTo(i.x, i.y), //起点
                        e.lineTo(x.x, x.y), //终点
                        e.stroke()
                    )
                }
            }
            w.splice(w.indexOf(i), 1)
        })
        m(b)
    }

    var u = document.createElement("canvas"), //创建canvas画布
        s = l(),
        e = u.getContext("2d"),
        r, n, m = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(i) {
            window.setTimeout(i, 1000 / 60)
        }, // 帧动画
        a = Math.random, // 随机值
        f = {
            x: null,
            y: null,
            max: 10 //鼠标影响的范围
        };
    u.id = "c_n" + s.l; // 设置画布id
    u.style.cssText = "position:absolute;top:0;left:0;bottom:0;right:0;z-index:" + s.z + ";opacity:" + s.o; // 设置画布样式
    if (elementId) {
        jId(elementId).appendChild(u); //将canvas加到对应元素中
    } else {
        j("body")[0].appendChild(u); //将canvas加到body中
    }
    k();
    //窗口大小变化
    window.onresize = function() {
        k()
    }

    //鼠标移动事件
    window.onmousemove = function(i) {
            i = i || window.event;
            f.x = i.clientX, f.y = i.clientY;
        }
        //鼠标移出事件
    window.onmouseout = function() {
        f.x = null, f.y = null;
    }
    for (var t = [], p = 0; s.n > p; p++) {
        var h = a() * r,
            g = a() * n,
            q = 2 * a() - 1,
            d = 2 * a() - 1;
        t.push({
            x: h,
            y: g,
            xa: q,
            ya: d,
            max: 10 //线条最大长度
        })
    }

    //延时调用
    setTimeout(() => {
        k();
        b();
    }, 1000)
}



export function Stars(elementId) {
    //获取宽高
    function k() {
        if (elementId) {
            width = u.width = jId(elementId).clientWidth; //获取元素的宽度
            height = u.height = jId(elementId).clientHeight; //获取元素的高度
        } else {
            width = u.width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; //获取窗口的宽度
            height = u.height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight //获取窗口的高度
        }
    }

    // 运动角度
    function lineToAngle(x1, y1, length, radians) {
        var x2 = x1 + length * Math.cos(radians),
            y2 = y1 + length * Math.sin(radians);
        return {
            x: x2,
            y: y2
        };
    }
    // 随机数
    function randomRange(min, max) {
        return min + Math.random() * (max - min);
    }
    // 角度转弧度
    function degreesToRads(degrees) {
        return degrees / 180 * Math.PI;
    }
    // 星星基本属性配置
    var particle = {
        x: 0,
        y: 0,
        vx: 0,
        vy: 0,
        radius: 0,
        // 创建对象
        create: function(x, y, speed, direction) {
            var obj = Object.create(this);
            obj.x = x;
            obj.y = y;
            obj.vx = Math.cos(direction) * speed;
            obj.vy = Math.sin(direction) * speed;
            return obj;
        },
        // 获取速度
        getSpeed: function() {
            return Math.sqrt(this.vx * this.vx + this.vy * this.vy);
        },
        // 设置速度
        setSpeed: function(speed) {
            var heading = this.getHeading();
            this.vx = Math.cos(heading) * speed;
            this.vy = Math.sin(heading) * speed;
        },
        // 获取头部值
        getHeading: function() {
            return Math.atan2(this.vy, this.vx);
        },
        // 设置头部值
        setHeading: function(heading) {
            var speed = this.getSpeed();
            this.vx = Math.cos(heading) * speed;
            this.vy = Math.sin(heading) * speed;
        },
        // 更新位置
        update: function() {
            this.x += this.vx;
            this.y += this.vy;
        }
    };

    var u = document.createElement("canvas"), //创建canvas画布
        context = u.getContext("2d"),
        width, height, Animation = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(i) {
            window.setTimeout(i, 1000 / 60)
        }; // 帧动画
    if (elementId) {
        jId(elementId).appendChild(u); //将canvas加到对应元素中
    } else {
        j("body")[0].appendChild(u); //将canvas加到body中
    }

    // 星星参数配置
    var stars = [], // 星星
        shootingStars = [], // 流星
        layers = [{ //星星属性
                speed: 0.02, // 运动速度
                scale: 0.1, // 缩放
                count: 300 // 数量
            }, {
                speed: 0.04,
                scale: 0.25,
                count: 150
            },
            {
                speed: 0.06,
                scale: 0.5,
                count: 50
            }, {
                speed: 0.08,
                scale: 0.75,
                count: 20
            },
            {
                speed: 0.1,
                scale: 0.9,
                count: 5
            }
        ], // 参数数组
        times,
        starsAngle = 135, //运动角度
        shootingStarSpeed = { //速度范围
            min: 15,
            max: 20
        },
        shootingStarOpacityDelta = 0.02, // 流星不透明度
        trailLengthDelta = 0.01, // 轨迹长度增量
        shootingStarEmittingInterval = 4000, //流星出现时间间隔
        shootingStarLifeTime = 500, //流星寿命
        maxTrailLength = 200, // 最大轨迹长度
        starBaseRadius = 2, //星基半径
        shootingStarRadius = 3, // 流星半径
        paused = false; //是否暂停

    // 生成星空
    function creatSky() {
        for (var j = 0; j < layers.length; j += 1) {
            var layer = layers[j];
            for (var i = 0; i < layer.count; i += 1) {
                var star = particle.create(randomRange(0, width), randomRange(0, height), 0, 0);
                star.radius = starBaseRadius * layer.scale;
                star.setSpeed(layer.speed);
                star.setHeading(degreesToRads(starsAngle));
                stars.push(star);
            }
        }
    }

    // 创建流星
    function createShootingStar() {
        var shootingStar = particle.create(randomRange(width / 4, width), randomRange(0, height / 2), 0, 0);
        shootingStar.setSpeed(randomRange(shootingStarSpeed.min, shootingStarSpeed.max));
        shootingStar.setHeading(degreesToRads(starsAngle));
        shootingStar.radius = shootingStarRadius;
        shootingStar.opacity = 0;
        shootingStar.trailLengthDelta = 0;
        shootingStar.isSpawning = true;
        shootingStar.isDying = false;
        shootingStars.push(shootingStar);
    }
    // 销毁流星
    function killShootingStar(shootingStar) {
        setTimeout(function() {
            shootingStar.isDying = true;
        }, shootingStarLifeTime);
    }
    // 更新画布
    function update() {
        // if (!paused) {
        context.clearRect(0, 0, width, height);
        context.fillStyle = "rgb(40, 42, 58,0.2)"; //星空颜色#282a3a
        context.fillRect(0, 0, width, height);
        context.fill();
        for (var i = 0; i < stars.length; i += 1) {
            var star = stars[i];
            star.update();
            drawStar(star);
            if (star.x > width) {
                star.x = 0;
            }
            if (star.x < 0) {
                star.x = width;
            }
            if (star.y > height) {
                star.y = 0;
            }
            if (star.y < 0) {
                star.y = height;
            }
        }

        for (i = 0; i < shootingStars.length; i += 1) {
            var shootingStar = shootingStars[i];
            if (shootingStar.isSpawning) {
                shootingStar.opacity += shootingStarOpacityDelta;
                if (shootingStar.opacity >= 1.0) {
                    shootingStar.isSpawning = false;
                    killShootingStar(shootingStar);
                }
            }
            if (shootingStar.isDying) {
                shootingStar.opacity -= shootingStarOpacityDelta;
                if (shootingStar.opacity <= 0.0) {
                    shootingStar.isDying = false;
                    shootingStar.isDead = true;
                }
            }
            shootingStar.trailLengthDelta += trailLengthDelta;

            shootingStar.update();
            if (shootingStar.opacity > 0.0) {
                drawShootingStar(shootingStar);
            }
        }

        for (i = shootingStars.length - 1; i >= 0; i--) {
            if (shootingStars[i].isDead) {
                shootingStars.splice(i, 1);
            }
        }
        // }

        Animation(update);
    }

    //绘制星星
    function drawStar(star) {
        context.fillStyle = "rgb(255, 221, 157)"; //星星颜色
        context.beginPath();
        context.arc(star.x, star.y, star.radius, 0, Math.PI * 2, false);
        context.fill();
    }

    //绘制流星
    function drawShootingStar(p) {
        var x = p.x,
            y = p.y,
            currentTrailLength = (maxTrailLength * p.trailLengthDelta),
            pos = lineToAngle(x, y, -currentTrailLength, p.getHeading());

        context.fillStyle = "rgba(255, 255, 255, " + p.opacity + ")";
        // context.beginPath();
        // context.arc(x, y, p.radius, 0, Math.PI * 2, false);
        // context.fill();
        var starLength = 2;
        context.beginPath();
        context.moveTo(x - 1, y + 1);

        context.lineTo(x, y + starLength);
        context.lineTo(x + 1, y + 1);

        context.lineTo(x + starLength, y);
        context.lineTo(x + 1, y - 1);

        context.lineTo(x, y + 1);
        context.lineTo(x, y - starLength);

        context.lineTo(x - 1, y - 1);
        context.lineTo(x - starLength, y);

        context.lineTo(x - 1, y + 1);
        context.lineTo(x - starLength, y);

        context.closePath();
        context.fill();

        context.fillStyle = "rgba(255, 221, 157, " + p.opacity + ")";
        context.beginPath();
        context.moveTo(x - 1, y - 1);
        context.lineTo(pos.x, pos.y);
        context.lineTo(x + 1, y + 1);
        context.closePath();
        context.fill();
    }

    function creatShooting() {
        times = setInterval(function() {
            if (paused) return;
            createShootingStar();
        }, shootingStarEmittingInterval);
    }

    //窗口大小变化
    window.onresize = function() {
        clearInterval(times)
        stars = []
        shootingStars = []
        k();
        creatSky();
        creatShooting();
    }
    window.onfocus = function() {
        paused = false;
    }

    window.onblur = function() {
        paused = true;
    }

    //延时调用
    setTimeout(() => {
        k();
        creatSky();
        creatShooting();
        update();
    }, 1000)
}