let scene, camera, renderer, controls;
let stats = initStats();
let key = 'points', id = 'id';
let verticalLineAry = [];
let geoKeys = ['3d_point1', '3d_point2'];
// n_panorama_line_3d = rx1

/* 初始加载 */
(function () {
    console.log("three start...");
    init();
    animate();
    console.log("three end...");
})();

/**
 * 初始化函数
 */
function init() {
    initRenderer();
    initScene();
    initCamera();
    initLight();
    initControls();
    drawGeometry(rx1);
    findIntersectLine();
}

// function drawGeometry() {
//     findIntersectLine();
//     if (!panorama_line_3d) {
//         let geometry = new THREE.geometry
//         console.log('panorama_line_3d未定义, 请检查');
//         return;
//     }

//     let material = new THREE.LineBasicMaterial({
//         color: 'red'
//     })
//     let geometry = new THREE.Geometry();

//     // 第一层的面循环
//     for (let i = 0; i < panorama_line_3d.length; i++) {
//         let face = panorama_line_3d[i]['faceLine'];
//         let index = panorama_line_3d[i]['index'];
//         let curVerticalLine = []
//         // if (face.length < 4) {
//         //     console.log('构成面的线段数小于4, 请检查');
//         //     return;
//         // }
//         let sta = false;   // 用于控制寻找相同点还是不同点
//         // 第二层面中的线循环
//         for (let j = 0; j < face.length; j++) {
//             if (!face[j][key] || face[j][key].length < 2) {
//                 console.log('线段' + face[j][id] + '的点数据有误, 请检查');
//                 return;
//             }
//             // 绘制第一条线段
//             if (j === 0) {
//                 // 第一条线段, 先寻找不同点
//                 let firstPoint = findPoint(face[j][key], face[j + 1][key], false);
//                 findverticalLine(firstPoint).forEach((item) => {
//                     index.indexOf(item) < 0 && curVerticalLine.indexOf(item) < 0 && curVerticalLine.push(item);
//                 })
//                 firstPoint && geometry.vertices.push(new THREE.Vector3(firstPoint[0], firstPoint[1], firstPoint[2]));
//                 // 再寻找相同点
//                 let secondPoint = findPoint(face[j][key], face[j + 1][key], true);
//                 findverticalLine(secondPoint).forEach((item) => {
//                     index.indexOf(item) < 0 && curVerticalLine.indexOf(item) < 0 && curVerticalLine.push(item);
//                 })
//                 secondPoint && geometry.vertices.push(new THREE.Vector3(secondPoint[0], secondPoint[1], secondPoint[2]));
//             } else if (j === face.length - 1) {  // 最后一条线段, 寻找与第一条线段相交的点
//                 let lastPoint = findPoint(face[j][key], face[0][key], true);
//                 findverticalLine(lastPoint).forEach((item) => {
//                     index.indexOf(item) < 0 && curVerticalLine.indexOf(item) < 0 && curVerticalLine.push(item);
//                 })
//                 lastPoint && geometry.vertices.push(new THREE.Vector3(lastPoint[0], lastPoint[1], lastPoint[2]));
//             } else {  // 寻找与上一条线段相交的点
//                 let point = findPoint(face[j][key], face[j + 1][key], true);
//                 findverticalLine(point).forEach((item) => {
//                     index.indexOf(item) < 0 && curVerticalLine.indexOf(item) < 0 && curVerticalLine.push(item);
//                 })
//                 point && geometry.vertices.push(new THREE.Vector3(point[0], point[1], point[2]));
//             }
//         }
//         panorama_line_3d[i].verticalLine.push(curVerticalLine);
//     }
//     let line = new THREE.Line(geometry, material);
//     scene.add(line);

// }

function drawGeometry(n_panorama_line_3d) {
    
    // if (!panorama_line_3d) {
    //     console.log('panorama_line_3d未定义, 请检查');
    //     return;
    // }
    if (scene.getObjectByName("3d_line")) {
        scene.remove(scene.getObjectByName("3d_line"));
        }

    let material = new THREE.LineBasicMaterial({
        color: 'red'
    })


    let line_model = new THREE.Object3D();
    // 第一层的面循环
    for (let i = 0; i < n_panorama_line_3d.length; i++) {
        let threeDLine = n_panorama_line_3d[i];
        let geometry = new THREE.Geometry();
        for (let j = 0; j < geoKeys.length; j++) {
            geometry.vertices.push(new THREE.Vector3(threeDLine[geoKeys[j]][0], threeDLine[geoKeys[j]][1], threeDLine[geoKeys[j]][2]))
        }
        let line = new THREE.Line(geometry, material);
        line_model.add(line);
    }
    line_model.name = '3d_line';
    scene.add(line_model);

}

/**
 * 
 * @param {*} point 
 */
function findverticalLine(point) {
    let lineAry = [];
    for (let i = 0; i < panorama_line_3d.length; i++) {
        for (let j = 0; j < panorama_line_3d[i].length; j++) {
            for (let k = 0; k < panorama_line_3d[i][j]['points'].length; k++) {
                let o_point = panorama_line_3d[i][j]['points'][k];
                if (arrayEquals(o_point, point)) {
                    lineAry.push(panorama_line_3d[i][j]['id']);
                }
            }
        }
    }
    // console.log(lineAry);
    return lineAry;
}



/**
 * 初始化渲染器
 */
function initRenderer() {
    renderer = new THREE.WebGLRenderer({
        antialias: true
    });
    renderer.setSize(window.innerWidth / 2, window.innerHeight);
    renderer.setClearColor("#ccc");
    renderer.shadowMap.enabled = true;
    let rightCav = document.getElementById('geo-cav');
    rightCav.appendChild(renderer.domElement);
    // canvas = renderer.domElement;
}

/**
 * 初始化场景
 */
function initScene() {
    scene = new THREE.Scene();
    // initContents();
}

/**
 * 初始化相机
 */
function initCamera() {
    camera = new THREE.PerspectiveCamera(
        45,
        0.5 * window.innerWidth / window.innerHeight,
        1,
        100
    );
    // camera = new THREE.OrthographicCamera(3 / - 2, 3 / 2, 3 / 2, 3 / - 2, 1, 1000);
    camera.position.set(15, -15, 8);
    camera.up.x = 0;
    camera.up.y = 0;
    camera.up.z = 1;
    camera.lookAt(new THREE.Vector3(0, 0, 0));
}

/**
 * 初始化灯光
 */
function initLight() {
    let ambientLight = new THREE.AmbientLight(0x333333);
    let directionalLight = new THREE.DirectionalLight("#FFFAFA", 1);
    directionalLight.position.set(100, -200, 200);
    directionalLight.castShadow = true;
    scene.add(ambientLight);
    scene.add(directionalLight);
}

/**
 * 初始化控制器
 */
function initControls() {
    // TODO: 3D状态下启动控制器
    controls = new THREE.OrbitControls(camera, renderer.domElement);
}


/**
 * 初始化性能插件
 */
function initStats() {
    let stats = new Stats();
    stats.setMode(0);
    stats.domElement.style.position = "absolute";
    stats.domElement.style.left = "0";
    stats.domElement.style.top = "0";
    document.body.appendChild(stats.domElement);
    return stats;
}

/* 循环调用 */
function animate() {
    requestAnimationFrame(animate);
    renderer.render(scene, camera);
    update();
}

/* 更新数据 */
function update() {
    stats.update();
    controls.update();
}