<template src="./webgl_rxdz_test.html"></template>
<script>
	import * as THREE from 'three';
	import Stats from 'three/addons/libs/stats.module.js';
	import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
	import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
	import spaceTypes from '@/static/spaceTypesIE.js';
    import TWEEN from 'three/addons/libs/tween.module.js';
	import router from "@/router";
	import {
		setStorage,
		getStorage,
	} from '@/utils/localStorage';
	var requestId = "";
	const util = require('@/utils/util.js').default;
	// const config = require('@/services/urlConfig.js');
	import wallType from '@/static/wallData.js';
	// import modelData from '@/webgl/static/layoutModelData.js';
	// import requestConfig from '@/services/requestConfig.js';
	// import viewShell from'@/webgl/components/newQCCom/viewShell/viewShell.vue';
	// import * as BufferGeometryUtils from '@/webgl/jsm/utils/BufferGeometryUtils.js';
	import screenshot from '@/mixins/screenshot.js';
	import floorMethod from '@/mixins/floorMethod.js';
	import wallMethod from '@/mixins/wallMethod.js';
	import loadModel from '@/mixins/loadModel.js';
	import commonPageMethod from '@/mixins/commonPageMethod.js';
	import viewShell from'@/components/newQCCom/viewShell/viewShell.vue';
	// import contrastImg from'@/components/contrastImg/contrastImg.vue';
	export default {
		name:"webgl_rxdz",
		components:{viewShell},
		mixins:[screenshot,floorMethod,wallMethod,loadModel,commonPageMethod],
		/**
		 * 页面的初始数据
		 */
		data() {
			return {
				pvCurPageName: "home_show",
				locusBehaviorName: "主界面",
				pvCurPageParams: null,
				houseId: "",
				pvId: 'p_2cmina_23080401',
				canvas:null,
				navbar: {
					showCapsule: 0,
					title: '空间定制',
					titleColor: '#000',
					navPadding: 0,
					navPaddingBg:'transparent',
					navBarColor: 'transparent',
					navBackColor: 'transparent',
					haveCallback: false,
					fromShare: false,
					fromProject: 0,
					shareToken: "",
					pageName: this.pvCurPageName,
				},
				id:'232',// 户型编号
				spaceList:[], // 空间列表
				spaceListBackup:[], // 空间列表原始尺寸备份，用于墙体比例计算
				gltfSpaces:[], // 场景中地板模型数组
				gltfSpaceRoofs:[], // 屋顶模型数组
				curSpaceObj:null, // 当前选中的空间
				// curSpaceIndex:-1, // 当前选中的空间索引
				curWallDirection:"", // 当前选中的墙面
				curWallValue:0, // 当前墙面的滑动值
				curWallMaxValue:300,
				curWallHidden:false, // 当前墙面的状态
				wallIds:[], // 空间墙体id
				wallList:[], // 墙体数据
				gltfWalls:[], // 场景中墙体模型数组
				gltfAutoWalls:[],// 空间自动补墙模型数组
				// lastWallPosition:0, // 当面墙中墙体模型的开始位置
				tempSpaceList:[],// 全部空间临时数组,寻找关联空间，递归使用
				leftSpaces:[], // 移动空间左边数组
				rightSpaces:[],// 移动空间右边数组
				changeSpaces:[],// 尺寸变化涉及到的全部空间
				loader:null,
				scene:null,
				sky:null,
				camera:null,
				houseList:[],	//当前户型所有的户型详情，可以切换
				curHouseType: null,	//当前选中的户型类型
				curHouseName:'',//当前选中的户型类型名称
				curHouseFloor: null,	//当前选中的户型楼层
				curHouseObj: null,
				controlStarPosition : { x:0, y:0, z:0},	//控制器初始位置
				cameraStarPosition : { x:0, y:30, z:0}	,//摄像头初始位置
                allSpaceCenter:null,//所有空间的中心点-水平面
				// cameraLastPosition: null,		//摄像头上一次移动到的位置
				// controlLastPosition: null,		//观察点上一次移动到的位置
				canvasHeight:200,	//canvas视图的高度-计算得出
				chooseMesh:null,//标记鼠标拾取到的mesh
				// chooseMeshColor:'',	//拾取到的mesh的原始颜色；
				chooseWallMeshColor:'', // 拾取墙体原始颜色
				curWallArr:[], // 当前空间选中墙面的墙体模型
				isManyou: false,	//当前是否处在漫游状态
				pageShowIndex: 2, // 默认户型列表页面
				aleadyLoaderModel:[],	//已经加载的墙体元数据模型列表
				// fontLabelGroup: [],
				shottingImg: [],
				progress:1,	//进度条
				myLoadingStatus:false,
				// textGeoList:[],
				repeatFlag:false,	//重复点击
				skyPlan: null, // 天空盒子
				instancedMeshList: [],
				lableItem:[],
				showLables:false,
				loadOver:false,
				voiceMaskShow:false,	//录音时的蒙层是否显示

				minspace1: null,
				minspace2: null,
				minspace3: null,
				minspace4 : null,

				spaces1 : [],
				spaces2 : [],
				spaces3 : [],
				spaces4 : [],
				
				layoutIds:[], // 空间墙体id
				layoutLists:[], // 墙体数据
				gltfLayouts:[], // 场景中墙体模型数组
				screenshotResolve:null,
				curLayoutStruct:null,//当前户型大类下所有楼层数据-用于提交
				overChange:false,	//是否形变中
				isIOS:false,	//是否ios手机。默认不是
				currentChangeSpaceId:null,	//当前变化的空间id
				styleType:2,
				sumArea:0,	//总面积
				changeArea:0,	//当次变化的面积
				fixedArea:0,	//初始面积值
				layoutArea:0,	//总面积
				selectSpace:null,//
				changeStatus:false,
                floorList:[],
                // selectIndex:'',
			}
		},
		beforeDestroy() {
			cancelAnimationFrame(requestId, this.canvas)
			this.worker && this.worker.terminate()
			if (this.renderer instanceof THREE.WebGLRenderer) {
				// 遍历场景中的所有子对象，找到类型为Mesh的对象并移除
				let deleList = this.scene.children.filter(object=>{
					if (object instanceof THREE.Mesh) {
						return object
					}
				})
				if(deleList && deleList.length>0){
					this.scene.remove(...deleList);
				}
				this.scene.traverse(function(object) {
					if (object instanceof THREE.Mesh) {
						if(object.geometry && typeof(object.geometry.dispose)=='function'){
							object.geometry.dispose();
						}
						if(object.material && typeof(object.material.dispose)=='function'){
							object.material.dispose();
						}
						if(object.texture && typeof(object.texture.dispose)=='function'){
							object.texture.dispose();
						}
					}
				});
				this.renderer.clear();
				this.renderer.dispose();
				this.renderer.forceContextLoss();
				this.renderer.context = null;
				this.renderer.domElement = null;
				this.renderer = null;;
				this.clearEvent()
			}
			this.gltfWalls = [];
			this.gltfSpaces = [];
			this.gltfSpaceRoofs = [];
			this.gltfLayouts = [];
			this.instancedMeshList = [];
			this.instancedSpaceMeshList = [];
			this.lableItem = [];
			this.instancedFurList = [];
			this.wallList = [];
			TWEEN && TWEEN.removeAll();//清除所有的tween;
			console.warn("***beforeDestroy-webgl_rxdz***");
		},
        mounted() {
			console.log("***onLoad-webgl_rxdz_test***", this.$route.query,this.$store.state.houseId,this.customizedRecordId);
			let isIOS = !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
			this.isIOS = isIOS;
			var that = this;
			this.houseId = this.$store.state.houseId || '';
			// this.selectIndex = this.$route.query.selectIndex || 0;
            if(this.customizedRecordId){
                this.curHouseObj = null;
            }else{
                if(getStorage('curHouseObj')){
                	this.curHouseObj = JSON.parse(getStorage('curHouseObj'));
                }
                else if(this.$store.state.curHouseObj){
                	this.curHouseObj = JSON.parse(JSON.stringify(this.$store.state.curHouseObj));
                }
            }
			console.warn("***this.curHouseObj***",this.curHouseObj)
			let screenWidth = window.screen.width;
			let screenHeight = window.screen.height;
			if(window.innerWidth && window.screen.width){
				screenWidth = Math.min(window.innerWidth,window.screen.width)
			}
			if(window.innerHeight && window.screen.height){
				screenHeight = Math.min(window.innerHeight,window.screen.height)
			}
			let unit = screenWidth / 750;//单位rpm 对应 px 的值
			that.canvasHeight = screenHeight - (600 * unit) + (20 * unit);
			const container = this.$refs.webgl;
            const canvas3d = this.canvas = this.$refs.glcanvas;
			
			let camera = null, renderer = null, controls=null;
			// let trackballControls = null;
			console.warn("***loader0***",this.loader)
			let loader = null;
			loader = this.loader = new GLTFLoader();
			// this.getInitData();//请求获取页面模型数据等
            let scene = this.scene = new THREE.Scene();
            let chooseMesh = this.chooseMesh;//标记鼠标拾取到的mesh
			let isUserContorl = false;
			let tweenCameraAnma = false;	//表示当前是否处在动画过程中
			let needRender = false;	//是否需要渲染 false表示不需要渲染；true 表示需要渲染
			let frustumSize = 30;//正交相机的视窗宽度距离
			let stats;
			init();
			// render();
			// this.$refs.myLoading.showLoading("加载中..." + this.progress+"%")
			// this.myLoadingStatus = true;
			this.progress = 1;
			this.clearEvent = clearEvent;
			this.attendEvent = attendEvent;
			this.updateLables = updateLables;
			this.enableRenderHandle = enableRender;
			this.tweenCameraAnmaChange = tweenCameraAnmaChange;
			this.gradientResize = gradientResize;
			this.moveMeshCenterHandle = moveMeshCenterHandle;
            this.movePositionHandle = movePositionHandle;
			this.starRender = starRender;//对外暴露启动渲染的方法
			this.stopRender = stopRender;//对外暴露停止渲染的方法
			this.cameraInit = cameraInit;
			this.resetControl = resetControl;
            this.setControlTarget = setControlTarget;
			if(this.curHouseObj){
				this.houseInit()
			}else{
                this.findHouseTypeSpaceListByIds();
            }
			function init() {

                scene.background = new THREE.Color("#FFFFFF");
                // scene.environment = new THREE.Color("#F2F2F2");

				// 创建相机位置-投影相机
				camera = new THREE.PerspectiveCamera( 80, screenWidth / that.canvasHeight, 0.1, 10000 );
				// let aspect = screenWidth /  that.canvasHeight;
				// camera = new THREE.OrthographicCamera( frustumSize * aspect / - 2, frustumSize * aspect / 2, frustumSize / 2, frustumSize / - 2, 0.1,1000);
				camera.up.set(0, 1, 0);//俯视状态，将相机的up向量设置为z轴负方向
				scene.add(camera);
                that.camera = camera;
				// 辅助方格
				// const axesHelper = new THREE.AxesHelper( 50 );
				// scene.add( axesHelper );
				// const gridHelper = new THREE.GridHelper(50, 10, 0xcccccc, 0xcccccc);
				// gridHelper.position.y = 0;
				// gridHelper.position.x = 0;
				// scene.add(gridHelper);

                // 环境光会均匀的照亮场景中的所有物体
                const ambientLight = new THREE.AmbientLight(0xFFEFE0, 3);
                scene.add(ambientLight);
                //平行光
                const light = new THREE.DirectionalLight(0xFFF8E5, 3);
                light.position.set(-3, 9, 3); //default; light shining from top
				light.castShadow = true; // default false
				// 默认情况下光投影相机区域是一个长宽高为10x10x500的长方体区域，光源投射方向为通过坐标原点
				light.shadow.camera.left = -100; // default
				light.shadow.camera.right  = 100; // default
				light.shadow.camera.top  = 100; // default
				light.shadow.camera.bottom  = -100; // default
				
				light.shadow.mapSize.width = 8192; // default
				light.shadow.mapSize.height = 8192; // default
				// light.shadow.camera.near = 0.1; // default
				// light.shadow.camera.far = 500; // default
				
				// light.shadow.bias = -0.01;
				// light.shadow.radius = 1;
				// light.shadow.darkness = 1; // 设置阴影强度为0.5
                scene.add(light);
				
				// const helper = new THREE.CameraHelper( light.shadow.camera );
				// scene.add(helper);
                // 从一个点向各个方向发射的光源。一个常见的例子是模拟一个灯泡发出的光。
                // const pointLight = new THREE.PointLight( 0xffffff, 0.3 );
                // camera.add( pointLight );

				
				//antialias 这个值得设置为false，不然IOS上截图会失效
                renderer = that.renderer = new THREE.WebGLRenderer({ 
					canvas:canvas3d, 
					alpha: true, 
					antialias:false,
					// 如果想保存three.js canvas画布上的信息，注意设置preserveDrawingBuffer
					preserveDrawingBuffer: true,
				});
				renderer.shadowMap.enabled = true;//产生阴影
				renderer.shadowMap.type = THREE.PCFSoftShadowMap; // 阴影属性
				renderer.outputEncoding = THREE.sRGBEncoding;
				renderer.outputColorSpace = THREE.SRGBColorSpace;
				// renderer.toneMappingExposure = 0.1;//色调映射的曝光级别。默认是1
				renderer.toneMapping = THREE.NoToneMapping;//色调映射
				renderer.physicallyCorrectLights = true;//关键参数，模拟物理光照影响，必须设置为true
				
                renderer.setPixelRatio( window.devicePixelRatio );
                renderer.setSize( screenWidth,  that.canvasHeight );
                container.appendChild( renderer.domElement );
				
				controls = new OrbitControls(camera, renderer.domElement);
				controls.screenSpacePanning = false;//平移时确保不超过PolarAngle限制
				controls.enableDamping = true;
				controls.minDistance = 1;
				controls.maxDistance = 400;
				controls.minPolarAngle = Math.PI / 8;// 默认0
				controls.maxPolarAngle = Math.PI / 2; // 默认Math.PI，即可以向下旋转到的视角。
				controls.target.set(that.controlStarPosition.x, that.controlStarPosition.y, that.controlStarPosition.z);
				controls.enableZoom = true;//启用摄像机的缩放
				controls.enablePan  = false;//启用或禁用摄像机平移，默认为true
				
				// 监听相机移动事件-限制只能在当前空间范围内移动
				// controls.addEventListener('change', () => {
				// 	// 检查相机位置是否超出边界框
				// 	if (camera.position.y < 0) {
				// 		camera.position.y = 0;
				// 	}
				// });
				// stats = new Stats();
				// container.appendChild(stats.dom);
				// stats.domElement.style.top = '100px';
				attendEvent();	//注册监听事件
				starRender();	//启动渲染
				cameraInit();	//初始化摄像头
            	controls.saveState();//保存当前控制器的状态
            }
            //初始化相机位置
            function cameraInit(){
            	camera.position.set(that.cameraStarPosition.x, that.cameraStarPosition.y, that.cameraStarPosition.z);
            	camera.lookAt(that.controlStarPosition.x,that.controlStarPosition.y,that.controlStarPosition.z);
            }
            //初始状态
            function resetControl(){
            	controls.reset();
            }
            //设置控制器的焦点
            function setControlTarget(target){
                if(target.isVector3){
                    controls.target = target;
                }
            }
			function onWindowResize() {
			    camera.aspect = screenWidth / that.canvasHeight;
			    camera.updateProjectionMatrix();
			    renderer.setSize( screenWidth, that.canvasHeight );
				console.warn("****onWindowResize**")
			}
			function attendEvent () {
				window.addEventListener('resize', onWindowResize);
				// renderer.domElement.addEventListener('touchstart', onPointerStart, false);
				// renderer.domElement.addEventListener('touchmove', onPointerMove, false);
				// renderer.domElement.addEventListener('touchend', onPointerUp, false);
			}
			function tweenCameraAnmaChange (value) {
				tweenCameraAnma = value
			}
			//开启渲染-帧率优化，不触发时停止渲染
			function enableRender() {
			}
			//取消事件监听-避免二次进入时触发多次事件
			function clearEvent(){
				console.warn("**clearEvent****")
				// renderer && renderer.domElement && renderer.domElement.removeEventListener('touchstart', onPointerStart);
				// renderer && renderer.domElement && renderer.domElement.removeEventListener('touchmove', onPointerMove );
				// renderer && renderer.domElement && renderer.domElement.removeEventListener('touchend', onPointerUp );
			}
			// 手指移动开始
			function onPointerStart(event){
				console.log('开始触摸事件：',that.overChange)
				if(that.overChange){//形变中，不能相应用户操作
					return false;
				}
			}
			//持续触摸中
			function onPointerMove( event ) {
				if(that.overChange){//形变中，不能相应用户操作
					return false;
				}
				// that.showLables = false;
			}
			//触摸结束
			function onPointerUp(event) {
				if(that.overChange){//形变中，不能相应用户操作
					return false;
				}
				// enableRender();
				if(event.touches.length==0){
					// that.showLables = true;
					// updateLables();
				}
			}
			//把摄像机移动的选中模型的正上方，观察点也变更为模型中心点，同时选中模型
			function moveMeshCenterHandle(mesh = null,noChangeColor = true){
				if(mesh){//如果传入了模型，则取模型
					let spaceId = mesh.spaceId;//空间id
					if(chooseMesh && spaceId == chooseMesh.spaceId){
						console.warn("**moveMeshCenterHandle-重复选中了***")
						return false;
					}
					chooseMesh = mesh;
				}
				if(!chooseMesh){
					console.warn("**moveMeshCenterHandle-没有数据***")
					return false;
				}
				that.showLables = false;//隐藏
				// controls.enable = false;//控制器不响应用户的操作
				let spaceObj = chooseMesh;//获取空间模型的相关数据
				// controls.panTo(spaceObj.centerX/100, camera.position.y, -spaceObj.centerY/100);
				let cameraNewPosition ={};
				let targetNewPosition ={};
				let oldUp = {};
				let newUp = {};
				if (isUserContorl === false) { // 非漫游状态
					let _juli = camera.position.y * Math.tan(Math.PI / 8);
					cameraNewPosition = {
						x:spaceObj.centerX/100,
						y:camera.position.y, 
						z:-spaceObj.centerY/100 + _juli,//增加偏差，防止极点翻转问题？不知道为啥会有用
					}
					//新的观察点的位置-取模型的中心点坐标，加上高度，由于模型都是贴地的，所以高度设置为0
					targetNewPosition = {
						x:spaceObj.centerX/100,
						y:0, 
						z:-spaceObj.centerY/100,
					}
					oldUp = camera.up;//俯视状态
					newUp = camera.up;
					// newUp = new THREE.Vector3(0,0,-1);
					// that.cameraLastPosition = cameraNewPosition;//记录下上一次摄像头位置
					// that.controlLastPosition = targetNewPosition;//记录下上一次观察点位置
					// if(cameraNewPosition.x<0){
					// 	cameraNewPosition.x = 0;
					// }
				}
				console.warn("**moveMeshCenter***",isUserContorl,spaceObj,JSON.stringify(camera.position),JSON.stringify(controls.target)
				,cameraNewPosition,targetNewPosition,JSON.stringify(camera.up))
				tweenCamera(camera.position,controls.target,cameraNewPosition,targetNewPosition,oldUp,newUp,1000);
				setTimeout(()=>{
					that.showLables = true;
					// camera.up = new THREE.Vector3(0,1,0);
					// updateLables();
				},1001);//动画结束后回复原始状态
			}
			//把摄像机移动到目标点位
			function movePositionHandle(position = null, height=null){
				let cameraNewPosition ={};
				let targetNewPosition ={};
				let oldUp = {};
				let newUp = {};
                let cy = height ? height : camera.position.y;
				let _juli = cy * Math.tan(Math.PI / 8);
				cameraNewPosition = {
					x:position.x,
					y:cy, 
					z:position.z + _juli,//增加偏差，防止极点翻转问题？不知道为啥会有用
				}
				//新的观察点的位置-取模型的中心点坐标，加上高度，由于模型都是贴地的，所以高度设置为0
				targetNewPosition = {
					x:position.x,
					y:position.y, 
					z:position.z
				}
				oldUp = camera.up;//俯视状态
				newUp = camera.up;
				// console.warn("**movePositionHandle***",position,JSON.stringify(camera.position),JSON.stringify(controls.target)
				// ,cameraNewPosition,targetNewPosition,JSON.stringify(camera.up))
				tweenCamera(camera.position,controls.target,cameraNewPosition,targetNewPosition,oldUp,newUp,500);
			}
            // oldP  相机原来的位置
            // oldT  target原来的位置
            // newP  相机新的位置
            // newT  target新的位置
            function tweenCamera(oldP, oldT, newP, newT, oldUp, newUp, time=1000) {
				if(JSON.stringify(oldP) == JSON.stringify(newP) && JSON.stringify(oldT) == JSON.stringify(newT)){
					return false;
				}
				// if (!chooseMesh) {
				// 	return false;
				// }
				tweenCameraAnma = true;
				var tween = new TWEEN.Tween({
					x1: oldP.x, // 相机x
					y1: oldP.y, // 相机y
					z1: oldP.z, // 相机z
					x2: oldT.x, // 控制点的中心点x
					y2: oldT.y, // 控制点的中心点y
					z2: oldT.z,	// 控制点的中心点z
					x3: oldUp.x, // 控制点的中心点x
					y3: oldUp.y, // 控制点的中心点y
					z3: oldUp.z  // 控制点的中心点z
				})
				.to({
			        x1: newP.x,
					y1: newP.y,
					z1: newP.z,
					x2: newT.x,
					y2: newT.y,
					z2: newT.z,
					x3: newUp.x, // up向量
					y3: newUp.y, // 控制点的中心点y
					z3: newUp.z  // 控制点的中心点z
			    }, time)
				.easing(TWEEN.Easing.Quadratic.InOut)
				.onUpdate((object)=> {
					camera.position.x = object.x1;
					camera.position.y = object.y1;
					camera.position.z = object.z1;
					let newTarget = new THREE.Vector3(object.x3,object.y3,object.z3);
					camera.up.copy(newTarget);
					camera.lookAt(object.x2,object.y2,object.z2);
					// controls.target.x = object.x2;
					// controls.target.y = object.y2;
					// controls.target.z = object.z2;
					// controls.update();
					// console.warn("****onUpdate**",object.x1,object.y1,object.z1,object.x2,object.y2,object.z2)
				}).onComplete(()=>{
					controls.target.x = newT.x;
					controls.target.y = newT.y;
					controls.target.z = newT.z;
					//修正最后的视角
					let up = new THREE.Vector3(newUp.x,newUp.y,newUp.z);
					camera.up.copy(up);
					camera.lookAt(controls.target.x,controls.target.y,controls.target.z);
					tweenCameraAnma = false;
				})
				// 开始动画
				tween.start();
			}
			//高度持续变化处理 time 动画持续时间 单位秒
			function gradientResize (time,startHeight,endHeight) {
				// let _timeStep = 20;//单位 毫秒
				// let unit = screenWidth / 750;//单位rpm 对应 px 的值
				// that.canvasHeight = screenHeight - (200 * unit) + (20 * unit);
				return false;//不在执行变化
				let unit = screenWidth / 750;//单位rpx 对应 px 的值
				let _height = startHeight - endHeight;//高度变化-单位rpx
				let _jisua = that.canvasHeight;
				let lastHeight = _jisua + (_height * unit);//动画结束时的高度值； 单位 px
				that.canvasHeight = lastHeight;//触发css动画
				// let step = (_height * unit) / (time*1000 / _timeStep);//真实大小 单位px
				console.warn("***gradientResize***",lastHeight,_jisua,startHeight,endHeight)

				// that.showLables = false;
				// let canvas_webgl = document.getElementById('canvas_webgl');
				console.log("相机变化1:", camera.position.y);
				var tween = new TWEEN.Tween({
				    h1: _jisua,
				})
				.to({
				    h1: lastHeight,
				}, 1000)
				.easing(TWEEN.Easing.Linear.None)
				.onUpdate((object)=> {
					if(camera.isOrthographicCamera){//正交相机
						let aspect = screenWidth / object.h1;
						camera.left = frustumSize * aspect / - 2;
						camera.right  = frustumSize * aspect / 2;
						camera.top  = frustumSize / 2;
						camera.bottom  = frustumSize / -2;
						camera.updateProjectionMatrix();
					}
					else if(camera.isPerspectiveCamera){//透视相机
						camera.aspect = screenWidth / object.h1;
						camera.updateProjectionMatrix();
						renderer.setSize( screenWidth, object.h1 );
						// let step = 0.12;//每次缩放放大的尺度
						// let _juli = step * Math.tan(Math.PI / 8);//由于观测点和相机存在角度，所以要计算每次变化尺度产生的Z轴变化量
						// if(_height>0){
						// 	camera.position.y = camera.position.y + step;
						// 	camera.position.z = camera.position.z + _juli;
						// }else{
						// 	camera.position.y = camera.position.y - step;
						// 	camera.position.z = camera.position.z - _juli;
						// }
						// that.canvasHeight = object.h1;
					}
				}).onComplete(()=>{
					camera.aspect = screenWidth / that.canvasHeight;
					camera.updateProjectionMatrix();
					renderer.setSize(screenWidth, that.canvasHeight );
					tweenCameraAnma = false;
					console.log("相机变化2:", camera.position.y);
					// that.showLables = true;
					// updateLables();//更新lable
				});
				// 开始动画
				tween.start();
				tweenCameraAnma = true;
			}
			//更新lables
			function updateLables(){
				if(!that.showLables){
					return false;
				}
				that.lableItem.forEach(lable =>{
					if(!that.gltfSpaces[lable.cubeIndex] || !that.gltfSpaces[lable.cubeIndex].instancedMeshIndexList){
						return false;
					}
					let item = that.gltfSpaces[lable.cubeIndex].instancedMeshIndexList[0];//获取地板模型的第一个geometry实例
					let _index = item.instancedMeshIndex;//第一个geometry实例 在 全局InstancedMesh实例的位置
					let instancedMesh = that.instancedSpaceMeshList[_index];//获取具体的网格实例
					let stratMatrix = new THREE.Matrix4();//定义一个四维矩阵
					instancedMesh.getMatrixAt(item.instancedAtIndex,stratMatrix);//获取当前几何体的四维矩阵到stratMatrix里面
					let position = new THREE.Vector3();//当前几何体的位置参数
					position.setFromMatrixPosition(stratMatrix);//从四维向量中提取位置信息
					// console.warn("***updateLables***",item.instancedAtIndex,JSON.stringify(position));
					position.project(camera);
					const x = (position.x *  .5 + .5) * screenWidth;
					const y = (position.y * -.5 + .5) * that.canvasHeight;
					lable.transform = `translate(-50%, -50%) translate(${x}px,${y}px)`;
				})
			}
			function stopRender () {
				needRender = false;
			}
			function starRender () {
				if(needRender==true){//如果已经在渲染中了，则不能再次开启，避免渲染过多
					false;
				}
				needRender = true;
				render();//开始渲染
			}
            function render() {
				if(needRender==false){
					return false;
				}
                TWEEN && TWEEN.update();
				// stats.update();
				//不处在动画过程中，则可以处理移动等动作
				if(tweenCameraAnma==false){
					controls.update();
					updateLables();//更新lable
				}
				requestId = requestAnimationFrame(render, canvas3d);
				renderer.render(scene, camera);//单次渲染
				if (that.screenshotResolve) {
					// stopRender();
					// that.screenshotResolve()
					// that.screenshotResolve = null;//释放Promise
                    // 上述代码是全canvas截图，下述代码是canvas部分截图
                    let gl = renderer.getContext();
                    let pix = window.devicePixelRatio;
                    let width = parseInt(screenWidth*pix);
                    let height = parseInt((that.canvasHeight - 40)*pix);//丢弃上面高度为40px 的区域
                    let pixelData = new Uint8Array(width * height * 4);
                    if (gl.checkFramebufferStatus(gl.FRAMEBUFFER) === gl.FRAMEBUFFER_COMPLETE) {
                    	// gl.readPixels(0, 0, frameBuffer.x, frameBuffer.y, gl.RGBA, gl.UNSIGNED_BYTE, pixelData);
                    	gl.readPixels(0, 0, width, height, gl.RGBA, gl.UNSIGNED_BYTE, pixelData);
                    	// 确保有像素，微信小程序安卓在进入子页面返回本页面后，再一次readPixels稳定无像素
                    	if (pixelData.some(i => i !== 0)) {
                    		stopRender();
                    		console.warn("***screenshotResolve-pixelData***");
                    		that.screenshotResolve({pixelData, width, height})
                    		that.screenshotResolve = null;//释放Promise
                    		pixelData = null;//清空内存中的数据
                    	}
                    }
				}
            }
			
		},
		onShow(){
			console.warn("---onShow1---",this.pvId)
			if(this.attendEvent){
				this.attendEvent()
			}
		},
		onHide(){
			this.clearEvent();
		},
		computed: {
			aiData() {
				return this.$store.state.aiData;
			},
			userId() {
				return this.$store.state.userId;
			},
            customizedRecordId() {
            	return this.$store.state.customizedRecordId;
            },
            ueId() {
            	return this.$store.state.ueId;
            },
		},

		methods: {
            async getInitData(){
            	let parmas = {
            		childLayout:this.childLayout || 0,
            		houseId:this.houseId,
            	}
            	const res = await requestConfig('getHouseTypeSpaceDetailsV2', parmas, true);
            	if (res.success && res.list) {
            		let list = res.list || [];
            		list && list.forEach((single,index)=>{
            			single.layoutStruct.forEach((item)=>{
            				if(item.houseJson){
            					let spaceList = JSON.parse(item.houseJson);
            					// 交换centerX， centerY
            					for (let index = 0; index < spaceList.length; index++) {
            					    var element = spaceList[index];
            					    const {centerX, centerY} = element;
            					    element.centerX = centerY;
            					    element.centerY = centerX;
            					}
            					item.houseJson = JSON.stringify(spaceList);
            				}
            			})
            		})
            		console.log("户型详情列表-接口原始数据: ", list);
            		this.curLayoutStruct = list;//数据会同步到组件中-进而反馈更新页面数据
            	}
            },
            // 查询户型列表
            async findHouseTypeSpaceListByIds() {
                // let parmas = {
                // 	childLayout:this.childLayout || 0,
                // 	houseId:this.houseId,
                // }
                // let _url = "getHouseTypeSpaceDetailsV2";
                var parmas = {
                    brandId: $config.brandId,
                    houseId: this.houseId,
                    pageNo: 1,
                    pageSize: 2000,
                };
                
                if(location.href.indexOf("//dm-mng.elab-plus.cn/screen/space-customiz") != -1){//生产环境
                    parmas.ids = this.ueId ? this.ueId.split(',') : [245];
                }else{
                    parmas.ids = this.ueId ? this.ueId.split(',') : [286];
                }
                let res = await requestConfig("findHouseTypeSpaceListByIds", parmas);
                this.floorList = [];
                if (res.success && res.list && res.list.length>0) {
                    let list = res.list || [];
                    list && list.forEach((item, index) => {
                        if (item.houseJson) {
                            let spaceList = JSON.parse(item.houseJson);
                            // 交换centerX， centerY
                            for (let index = 0; index < spaceList.length; index++) {
                                var element = spaceList[index];
                                const {
                                    centerX,
                                    centerY
                                } = element;
                                element.centerX = centerY;
                                element.centerY = centerX;
                                //默认布局和实际默认布局对不上时的处理方案
                                if (element.layouts.length > 1) {
                                    let layout = element.layouts.find(it => it.isDefault == true);
                                    if (layout) {
                                        element.layoutId = layout.layoutId;
                                    }
                                }
                            }
                            item.houseJson = JSON.stringify(spaceList);
                            this.floorList.push({
                                id:item.id,
                                houseFloor:(index+1),
                            })
                            console.log("户型详情列表: ", spaceList);
                        }
                    })
                    this.curLayoutStruct = list;
                    //把楼层的数据存入缓存中,因为这个页面需要使用大量内存,ios很容易导致内存不足自动回收内存，所以不能用全局内存变量去存储这个数据
                    setStorage('curLayoutStruct', this.curLayoutStruct);
                    this.curHouseObj = list[0];
                    setStorage('curHouseObj', this.curHouseObj);
                    this.houseInit();
                }else{
                    console.warn("***没有数据***",res.list)
                }
            },
            //页面返回后同步数据
            backAysncData(){
                console.warn("---backAysncData---",this.pvId)
                let curLayoutStruct = JSON.parse(getStorage('curLayoutStruct')) ;//获取楼层的数据-户型数组
                if(curLayoutStruct && curLayoutStruct.length>0){
                    curLayoutStruct.forEach((layoutStruct,index)=>{
                        let spaceList =  JSON.parse(layoutStruct.houseJson);//houseJson是字符串需要序列号处理
                        spaceList.forEach(obj => delete obj.wallList);//去除墙体数据，减少数据量
                        if(this.curHouseObj && this.curHouseObj.id==layoutStruct.id){
                            this.curHouseObj.houseJson = JSON.stringify(spaceList);
                            console.warn("***backAysncData-curHouseObj***",this.curHouseObj)
                        }
                        if(this.curLayoutStruc && this.curLayoutStruct[index]){
                            this.curLayoutStruct[index].houseJson = JSON.stringify(spaceList);//数据会同步到组件中
                        }
                    })
                }
            },
            //当前户型初始化
            houseInit(item){
            	this.gltfWalls = [];
            	this.gltfSpaces = [];
            	this.gltfSpaceRoofs = [];
            	this.instancedMeshList = [];
            	this.instancedSpaceMeshList = [];
            	this.lableItem = [];
            	this.gltfLayouts = [];
            	this.instancedFurList = [];
            	this.wallList = [];
            	this.changeArea = 0;
            	// this.cameraInit();
            	this.resetControl();
            	setTimeout(()=>{
            		this.loadSpace();
            	}, 100);
            	console.warn("***curHouseObj***",this.curHouseObj,this.aiData)
            	// this.navbar.title = this.curHouseObj.name + "  " + this.curHouseObj.houseArea + "㎡";
            	this.navbar.title = "空间定制";
            	document.title = this.navbar.title;
            	this.sumArea = this.curHouseObj.houseArea;
            	this.fixedArea = this.curHouseObj.houseArea;
            	this.curHouseName = this.curHouseObj.name;
            	if(this.curHouseObj.houseArea<=100){//面积小于100平米，则摄像头靠近一点
            		this.cameraStarPosition.y = 20;
            	}else if(this.curHouseObj.houseArea>100){
            		this.cameraStarPosition.y = 30;
            	}
            	this.cameraInit();
                this.locusValue = this.curHouseObj.name + "-" + this.curHouseObj.houseArea + "㎡";
                let param = {
                	type: 'PV',
                	pvId: this.pvId,
                	locusBehaviorName: this.locusBehaviorName,
                	pvCurPageName: this.pvCurPageName,
                	locusValue: this.locusValue,
                    behaviorName:"空间定制",
                };
                util.trackRequest(param);//发送统一PV埋点
            },
            //户型楼层发生了变更
            curHouseFloorChange(item){
                let that = this;
                if(!item || !item.id){
                    return false;
                }
                let _curHouseObj = this.curLayoutStruct.find(it=>it.id==item.id);
                if(!_curHouseObj){
                    console.warn("***curHouseFloorChange-nodeta***",this.curLayoutStruct,item)
                    return false
                }
            	// 遍历场景中的所有子对象，找到类型为Mesh的对象并移除
            	let deleList = that.scene && that.scene.children.filter(object=>{
            		if(object.userType=="mesh" || object.userType=="layoutMesh"){
            			return object
            		}
            	})
            	// console.warn("***deleList***",deleList)
            	if(deleList && deleList.length>0){
            		that.showLables = false;//隐藏lable
            		that.scene.remove(...deleList);
            	}
            	if(this.selectSpace){
            		this.changeSpaceColor(this.selectSpace.spaceId,2);//取消上一个空间的颜色
            	    this.selectSpace = null;
            	}
                
                this.curHouseObj = _curHouseObj;
                setStorage('curHouseObj', this.curHouseObj);
                this.houseInit();
            	//恢复初始视角
            	// this.cameraInit();
            	// this.resetControl();
            	console.warn("***curHouseFloorChange***",this.curHouseObj,item)
            	// this.navbar.title = this.curHouseObj.name + "  " + this.curHouseObj.houseArea + "㎡";
            	
            },
			voiceMaskChange(voiceMask){
				this.voiceMaskShow = voiceMask;
			},
			// async submitHouse(){
			// 	if(this.overChange){
			// 		this.$message.warning("空间正在调整");
			// 		return false
			// 	}
			// 	let shottingImg = await this.shottingAction() + "?x-oss-process=image/auto-orient,1/quality,Q_46/format,jpg";//开始截图
			// 	console.warn("***shottingImg***",shottingImg);
			// },
			enableRender(){
				this.enableRenderHandle();
			},
			/**
			 * 选中墙体触发
			 */
			selectWall(wallIndex){
			    console.log("index",wallIndex)
			
				if(this.chooseWallMeshColor){
					for (let index = 0; index < this.curWallArr.length; index++) {
						const element = this.curWallArr[index];
						const cube = element.obj;
						this.chooseWallMeshColor.convertSRGBToLinear(); // 将颜色值转换为线性颜色值
						if(cube && cube.children[0].children[0] && cube.children[0].children[0].material){
							cube.children[0].children[0].material.color = this.chooseWallMeshColor;//修改选中模型的颜色-高亮显示 当前选中的模型
						}else{//新版逻辑
							// element.instancedMeshIndexList.forEach(item=>{
							// 	let _index = item.instancedMeshIndex;
							// 	let instancedMesh = this.instancedMeshList[_index];//网格实例
							// 	instancedMesh.instanceColor.needsUpdate = true;//打开颜色修改开关,不开，颜色是不能修改额
							// 	instancedMesh.setColorAt(item.instancedAtIndex, this.chooseWallMeshColor);//修改这个几何体的颜色
							// })
						}
					}
				}
				
				switch (wallIndex) {
			        case 1:
			            this.curWallDirection = "N";
			            break;
			        case 2:
			            this.curWallDirection = "S";
			            break;
			        case 3:
			            this.curWallDirection = "W";
			            break;
			        case 4:
			            this.curWallDirection = "E";
			            break;
			    }
			    this.selectedWall(this.curWallDirection)
			
				this.curWallArr = [];
			    if(wallIndex!=0){
			        const wallMoveValues = this.curSpaceObj.wallMoveValue;
					console.log
			        const values = JSON.parse(wallMoveValues);
					if(this.curWallValue == 150){
						this.curWallValue = values[wallIndex-1]
					}else{
						let wallIndex = 0
						switch (this.curWallDirection) {
							case "N":
								wallIndex = 0;
								values[wallIndex] = this.curWallValue;
								values[1] = this.curWallValue;
								break;
							case "S":
								wallIndex = 1;
								values[wallIndex] = this.curWallValue;
								values[0] = this.curWallValue;
								break;
							case "W":
								wallIndex = 2;
								values[wallIndex] = this.curWallValue;
								values[3] = this.curWallValue;
								break;
							case "E":
								wallIndex = 3;
								values[wallIndex] = this.curWallValue;
								values[2] = this.curWallValue;
								break;
						}
					}
					this.curSpaceObj.wallMoveValue = JSON.stringify(values)
					console.log("墙体可移动数据：", this.curSpaceObj.wallMoveValue, this.spaceList);
			
					const wallStatus = this.curSpaceObj.wallStatus || "[false,false,false,false]"
					const status = JSON.parse(wallStatus);
			        this.curWallHidden = status[wallIndex-1]
			        console.log("当前墙面数据：", wallStatus , status, wallIndex);
			
					const curSpaceGltfWall = this.gltfWalls.filter((item)=>{
						return this.curSpaceObj.spaceId == item.spaceId && item.wallDirection == this.curWallDirection
					})
					if(curSpaceGltfWall.length != 0){
						this.curWallArr.push(...curSpaceGltfWall);
					}else{
						let rightWallD = "";
						switch (wallIndex-1) {
							case 0:
								rightWallD= "S";
								break;
							case 1:
								rightWallD= "N";
								break;
							case 2:
								rightWallD= "E";
								break;
							case 3:
								rightWallD= "W";
								break;
						}
						for (let index = 0; index < this.leftSpaces.length; index++) {
							const element = this.leftSpaces[index];
							const gltfWall = this.gltfWalls.filter((item)=>{
								return element.spaceId == item.spaceId && item.wallDirection == this.curWallDirection
							})
							if(gltfWall){
								this.curWallArr.push(...gltfWall);
							}
						}
			
						for (let index = 0; index < this.rightSpaces.length; index++) {
							const element = this.rightSpaces[index];
							const gltfWall = this.gltfWalls.filter((item)=>{
								return element.spaceId == item.spaceId && item.wallDirection == rightWallD;
							})
							if(gltfWall){
								this.curWallArr.push(...gltfWall);
							}
						}
					}
					for (let index = 0; index < this.curWallArr.length; index++) {
						const element = this.curWallArr[index];
						const cube = element.obj;
						if(cube && cube.children[0].children[0] && cube.children[0].children[0].material){
							this.chooseWallMeshColor = cube.children[0].children[0].material.color.clone();
							let color = new THREE.Color(0xff0000); // 使用sRGB颜色值
							color.convertSRGBToLinear(); // 将颜色值转换为线性颜色值
							cube.children[0].children[0].material.color = color;//修改选中模型的颜色-高亮显示 当前选中的模型
						}else{//新版逻辑
							// element.instancedMeshIndexList.forEach(item=>{
							// 	let _index = item.instancedMeshIndex;
							// 	let instancedMesh = this.instancedMeshList[_index];//网格实例
								
							// 	this.chooseWallMeshColor = instancedMesh.material.color.clone();;
							// 	let color = new THREE.Color(0xff0000); // 使用sRGB颜色值
							// 	color.convertSRGBToLinear(); // 将颜色值转换为线性颜色值
							// 	instancedMesh.instanceColor.needsUpdate = true;//打开颜色修改开关,不开，颜色是不能修改额
							// 	instancedMesh.setColorAt(item.instancedAtIndex, color);//修改这个几何体的颜色
							// })
							
						}
					
					}
			
			    }
			},
			curSpaceSelect(data){
				console.warn("***curSpaceSelect***",data);
				if(this.selectSpace){
					this.changeSpaceColor(this.selectSpace.spaceId,2);//取消上一个空间的颜色
				}
				let spaceId = data.spaceId;
				let space = this.spaceList.find(it=>it.spaceId==spaceId);
				this.selectSpace = space;
				this.currentChangeSpaceId = spaceId;
				this.$store.state.curSpaceId = data.spaceId;
				
				this.changeSpaceColor(data.spaceId,1);//设置选中空间的颜色
				this.moveMeshCenter(space);
                // setTimeout(()=>{
                //     this.setControlTarget(this.allSpaceCenter)
                // },1100)
			},
			//具体空间面积变化-拖动产生的
			//data = {
			//		spaceId:245,
			//		area:12, //正负值 单位平方米
			//	}
			curSpaceChange(data){
				console.warn("***空间面积变化***",this.overChange,data);
				// let changArea = data.isZoomIn ? parseFloat(data.area.toFixed(2)) : -parseFloat(data.area.toFixed(2));
				// this.changeArea = changArea;//当次变化的面积，有正负值
				// this.sumArea = parseFloat((this.sumArea + changArea).toFixed(2));
				this.overChange = true;//变形开始 防止在形变结束前，再次形变
				this.currentChangeSpaceId = data.spaceId;
				this.$store.state.curSpaceId = data.spaceId;
				this.changCurSpaceArea(data);
				let space = this.spaceList.find(it=>it.spaceId==this.currentChangeSpaceId);
				this.moveMeshCenter(space);
			},
			
			// 空间移动，
			changCurSpaceArea(data){
				console.log("当前户型的核心点", this.curHouseObj.houseCore, this.overChange);
				const houseCore = this.curHouseObj.houseCore.split(',');
				const coreX = houseCore[0] | 0
				const coreY = houseCore[1] | 0
				// 根据核心点计算空间所在象限
				this.spaces1 = [];
				this.spaces2 = [];
				this.spaces3 = [];
				this.spaces4 = [];
				let curSpace = null;
				for (let index = 0; index < this.spaceList.length; index++) {
					const element = this.spaceList[index];
					if(element.centerX > coreX){ // 2 3象限
						if(element.centerY > coreY){ // 2象限
							console.log(`象限2 ${element}`);
							element.quadrant = 2;
							this.spaces2.push(element)
						}else{// 3象限
							console.log(`象限3 ${element}`);
							element.quadrant = 3;
							this.spaces3.push(element)
						}
					}else{// 1 4象限
						if(element.centerY > coreY){ // 1象限
							console.log(`象限1 ${element}`);
							element.quadrant = 1;
							this.spaces1.push(element)
						}else{ // 4象限
							console.log(`象限4 ${element}`);
							element.quadrant = 4;
							this.spaces4.push(element)
						}
					}
					if(element.spaceId == data.spaceId){
						curSpace = element;
					}
				}
			
				console.log("当前space所在象限",data.spaceId, curSpace.spaceId , curSpace.quadrant);
				console.log("象限", this.spaces1, this.spaces2, this.spaces3, this.spaces4);
			
			
				this.calculateSpaceData(curSpace, data)
			},
			calculateSpaceData(curSpace, data){
				let that = this;
				this.curSpaceObj = curSpace;
				this.changeStatus = true;
				// 计算宽高移动数值 
				const changeArea = data.area;
				const isZoomIn = data.isZoomIn;
				const oldArea = (curSpace.spaceWidth / 100) * (curSpace.spaceHeight / 100);
				const newArea = oldArea + changeArea * (data.isZoomIn ? 1 : -1);
				const sizeScale = Math.sqrt(newArea/oldArea) ;
			
				// 新的宽度
				let newWidth = curSpace.spaceWidth * sizeScale;

				if(newWidth < curSpace.spaceWidthMin){
					newWidth = curSpace.spaceWidthMin
				}
				if(newWidth > curSpace.spaceWidthMax){
					newWidth = curSpace.spaceWidthMax
				}
				// 新的高度
				let newHeight = newArea * 10000 / newWidth;

				if(newHeight < curSpace.spaceHeightMin){
					newHeight = curSpace.spaceHeightMin
				}
				if(newHeight > curSpace.spaceHeightMax){
					newHeight = curSpace.spaceHeightMax
				}

				newWidth = newArea * 10000 / newHeight;

				
				let changeWidth = Math.abs(newWidth - curSpace.spaceWidth)
				let changeHeight = Math.abs(newHeight - curSpace.spaceHeight)

				console.log("变化的尺寸", changeWidth, changeHeight, newWidth, newHeight, curSpace.spaceWidth, curSpace.spaceHeight);
			
				if(curSpace.quadrant == 1){
					// 默认往南 往西移动
					this.moveSpace(curSpace, 1, 3, isZoomIn, newArea, newWidth, newHeight, changeWidth, changeHeight)
				}
				if(curSpace.quadrant == 2){
					// 默认往南 往西移动
					this.moveSpace(curSpace, 1, 4, isZoomIn, newArea, newWidth, newHeight, changeWidth, changeHeight)
				}
				if(curSpace.quadrant == 3){
					// this.selectWall(4);
					// 		// // 移动墙面
					// this.moveSpaceWall(this.curWallDirection, isZoomIn, changeWidth);
					// 默认往南 往东移动
					this.moveSpace(curSpace, 2, 4, isZoomIn, newArea, newWidth, newHeight, changeWidth, changeHeight)
				}
				if(curSpace.quadrant == 4){ 
					// 默认往南 往西移动
					this.moveSpace(curSpace, 2, 3, isZoomIn, newArea, newWidth, newHeight, changeWidth, changeHeight)
				}
				setTimeout(() => {
					// that.updataPageData();
					that.overChange = false;
					that.callBackFun && that.callBackFun(true);
					// that.calculateLayoutModelSize(); //重新计算家具位置
					if(that.changeStatus){//空间有变化才触发替换等动作
						that.updateWallModels(); // 替换墙体模型
						that.changeLayoutModel(); // 改变空间模型
					}
					// that.changeLayoutModelState(true); // 显示家具模型
				}, 4200);
			}, 
			moveSpace(curSpace, directionIndex, directionIndex01, isZoomIn, newArea, newWidth, newHeight, changeWidth, changeHeight){
				let that = this;
				const wallLock =  this.currWallLock(directionIndex, curSpace); //南边
				const wallLock01 =  this.currWallLock(directionIndex01, curSpace); //东边
				console.log("移动空间", wallLock, wallLock01)
				if(wallLock ==-1 && wallLock01 == -1){
					this.changeStatus = false;//表示无变化
					return this.$message.warning("空间尺寸已锁定");
				}
				let changeValue = changeHeight;
				if(wallLock == -1){
					if(wallLock01 == 0){
						directionIndex01 = directionIndex01 == 4 ? 3 : 4; // 往西移动
					}
					// 南北锁死，重新计算移动的方向
					newWidth =  newArea / (curSpace.spaceHeight / 100) * 100
					changeWidth = newWidth / 100 - curSpace.spaceWidth / 100;
					changeWidth = Math.abs(changeWidth * 100);
					directionIndex = directionIndex01; // 往东移动
					changeValue = changeWidth;
					console.log("高度锁死不能拉伸, 宽度变化1",newWidth, directionIndex,curSpace.spaceWidth, curSpace.spaceHeight, changeValue);
					that.selectWall(directionIndex);
					let checkResult = this.checkRightSpace(!isZoomIn, changeWidth, false, curSpace)
					if(!checkResult.result){
						changeWidth = checkResult.newValue
					}
					console.log("宽度达到极限值结果++++++++++++++", checkResult, changeWidth)
					that.moveSpaceWall(that.curWallDirection, isZoomIn, changeWidth);
					if(changeWidth==0){
						this.changeStatus = false;//表示无变化
					}
					// that.autoCreateWall(directionIndex, curSpace)
					return;
				}else{
					if(wallLock == 0){
						directionIndex = directionIndex == 2 ? 1 : 2; // 往北边移动
					}
					if(wallLock01 == -1){
						// 东西锁死，重新计算移动方向
						newHeight =  newArea / (curSpace.spaceWidth / 100) * 100
						changeHeight = newHeight / 100 - curSpace.spaceHeight / 100;
						changeHeight = Math.abs(changeHeight * 100);
						changeValue = changeHeight;
			
						that.selectWall(directionIndex);

						let checkResult = this.checkRightSpace(!isZoomIn, changeHeight, true, curSpace)
						console.log("高度达到极限值结果++++++++++++++", checkResult, changeHeight)
						if(!checkResult.result){
							changeHeight = checkResult.newValue
						}
						that.moveSpaceWall(that.curWallDirection, isZoomIn, changeHeight);
						if(changeHeight==0){
							this.changeStatus = false;//表示无变化
						}
						// 自动补墙逻辑
						// that.autoCreateWall(directionIndex, curSpace);
						return
					}
			
					if(wallLock01 == 0){
						directionIndex01 = directionIndex01 == 4 ? 3 : 4; // 往西移动
					}
			
					console.warn(curSpace.spaceId, "要变化的宽度：", newWidth, "要变化的高度：",newHeight)
					// 目标宽度
					if(newHeight > curSpace.spaceHeightMax){
						newHeight = curSpace.spaceHeightMax; 
						changeHeight = Math.abs(newHeight - curSpace.spaceHeight)
						// 重新计算宽度值
						newWidth = (newArea / (newHeight / 100)) * 100
						changeWidth = (newWidth / 100 - curSpace.spaceWidth / 100) * 100;
						console.log("高度达到最大值，重新计算宽度",newWidth, newHeight, changeWidth, changeHeight)
					}
			
					if(newHeight < curSpace.spaceHeightMin){
						newHeight = curSpace.spaceHeightMin; 
						changeHeight = Math.abs(newHeight - curSpace.spaceHeight)
						// 重新计算宽度值
						newWidth = (newArea / (newHeight / 100)) * 100
						changeWidth = Math.abs((newWidth / 100 - curSpace.spaceWidth / 100) * 100);
						console.log("高度达到最小值，重新计算宽度",newWidth, newHeight, changeWidth, changeHeight)
					}
			
					if(newWidth > curSpace.spaceWidthMax){
						newWidth = curSpace.spaceWidthMax; 
						changeWidth = Math.abs(newWidth - curSpace.spaceWidth)
						// 重新计算宽度值
						newHeight = (newArea / (newWidth / 100)) * 100
						changeHeight = (newHeight / 100 - curSpace.spaceHeight / 100) * 100;
						console.log("宽度达到最大值，重新计算高度",newWidth, newHeight, changeWidth, changeHeight)
					}
			
					if(newWidth < curSpace.spaceWidthMin){
						newWidth = curSpace.spaceWidthMin; 
						changeWidth = Math.abs(newWidth - curSpace.spaceWidth)
						// 重新计算宽度值
						newHeight = (newArea / (newWidth / 100)) * 100
						changeHeight = Math.abs((newHeight / 100 - curSpace.spaceHeight / 100) * 100);
						console.log("宽度达到最小值，重新计算高度",newWidth, newHeight, changeWidth, changeHeight)
					}
					// if(!checkWidth || !checkHeight){
					// 	return
					// }
					if(changeHeight > 0){
						that.changeSpaces = [];
						that.selectWall(directionIndex);
						let checkResult = this.checkRightSpace(!isZoomIn, changeHeight, true, curSpace)
						console.log("高度达到极限值结果++++++++++++++", checkResult, changeHeight)
						if(!checkResult.result){
							changeHeight = checkResult.newValue
						}
						that.moveSpaceWall(that.curWallDirection, isZoomIn, changeHeight);
						// 自动补墙逻辑
						// that.autoCreateWall(directionIndex, curSpace)
					}
					let timeout = 0
					if(changeWidth > 0 && changeHeight > 0 ){
						timeout = 2100
					}
					console.log("改变尺寸",changeWidth, changeHeight,newWidth, newHeight,  timeout, directionIndex, directionIndex01, wallLock, wallLock01)
					if(changeWidth > 0){
						setTimeout(() => {
							that.changeSpaces = [];
							// // 选中墙面
							that.selectWall(directionIndex01);
							// 计算
							let checkResult = this.checkRightSpace(!isZoomIn, changeWidth, false, curSpace)
							if(!checkResult.result){
								changeWidth = checkResult.newValue
							}
							console.log("宽度达到极限值结果++++++++++++++", checkResult, changeWidth)
							// 移动墙面
							that.moveSpaceWall(that.curWallDirection, isZoomIn, changeWidth);
							// 自动补墙逻辑
							// that.autoCreateWall(directionIndex01, curSpace)
						}, timeout);
					}
				}
			},
			currWallLock(direction, curSpace){
			
				let curDirection = ""
				let faceDirection = ""
				switch (direction) {
			        case 1:
						curDirection = "N";
						faceDirection = "S";
			            break;
			        case 2:
						curDirection = "S";
						faceDirection = "N";
			            break;
			        case 3:
						curDirection = "W";
						faceDirection = "E";
			            break;
			        case 4:
						curDirection = "E";
						faceDirection = "W";
			            break;
			    }
				const wallInfo = this.wallList.find((item)=>{
					let element = JSON.parse(item.wallJson);
					return element.spaceId == curSpace.spaceId;
				})
				let walls = JSON.parse(wallInfo.wallJson).wallData;
			
				const wall = walls.find((item)=>{ // 当前墙面锁定
					return item.wallDirection==curDirection && item.isLocked=="true"
				})
				const faceWall = walls.find((item)=>{ // 对面墙面锁定
					return item.wallDirection==faceDirection && item.isLocked=="true"
				})
				
				if(wall){
					if(faceWall){
						return -1 // 当前对面同时锁定
					}
					return 0 // 当前锁定
				}else{
					return 1 // 不锁定，可以移动
				}
				
			},
			// 排查关联空间是否达到极限值
			checkRightSpace(isZoomIn, changeValue, isNS, curSpace){
				if(changeValue == 0){
					return;
				}
				let n = isZoomIn?1:-1;
				let l = isZoomIn?-1:1;
				let result = true;
				let space = null;
				let newValue = changeValue;
			
				console.log("排查空间",isZoomIn, changeValue,isNS, this.leftSpaces, this.rightSpaces);
				for (let index = 0; index < this.leftSpaces.length; index++) {
					const element = this.leftSpaces[index];
					// 过滤掉花园判断
					if(element.spaceType == 14 || element.spaceId == curSpace.spaceId){
						continue;
					}
					let newWidth = element.spaceWidth + l * changeValue;
					let newHeight = element.spaceHeight + l * changeValue;
					if(isNS){
						if( newHeight > element.spaceHeightMax || newHeight < element.spaceHeightMin){
							result = false;
							space = element;
							break;
						}
					}else{
						if(newWidth > element.spaceWidthMax || newWidth < element.spaceWidthMin){
							result = false;
							space = element;
							break;
						}
					}
				}
			
				for (let index = 0; index < this.rightSpaces.length; index++) {
					const element = this.rightSpaces[index];
					// 过滤掉花园判断
					if(element.spaceType == 14){
						console.log("空间排查跳出")
						continue;
					}
					let newWidth = element.spaceWidth + n * changeValue;
					let newHeight = element.spaceHeight + n * changeValue;
					
					if(isNS){
						if( newHeight > element.spaceHeightMax || newHeight < element.spaceHeightMin){
							result = false;
							space = element;
							const newHeightValue = newHeight > element.spaceHeightMax ? element.spaceHeightMax : element.spaceHeightMin;
							newHeight = newHeightValue - newHeight;
							const newChangeValue = changeValue - newHeight;
							if(newValue > newChangeValue){
								newValue = newChangeValue;
							}
							break;
						}
					}else{
						console.log("排查右边空间",newWidth, element.spaceWidthMax,newWidth, element.spaceWidthMin);
						if(newWidth > element.spaceWidthMax || newWidth < element.spaceWidthMin){
							result = false;
							space = element;
							let newWidthValue = newWidth > element.spaceWidthMax ? element.spaceWidthMax : element.spaceWidthMin
							if(isZoomIn){ // 放大
								if(newWidth>element.spaceWidthMax){ // 关联空间放大时已经是最大，则变化值为0
									newValue = 0
									break;
								}
							}else{
								newWidthValue = newWidth < element.spaceWidthMin ? element.spaceWidthMin : newWidth;
								console.log("排查右边空间2",newWidth, element.spaceWidthMax, element.spaceWidthMin);
							}
							newWidth = newWidthValue - newWidth;
							const newChangeValue = changeValue - newWidth;
							if(newValue > newChangeValue){
								newValue = newChangeValue;
							}
							break;
						}
					}
				}
				
				if(!result){
					this.$message.warning(`关联空间[${ space && space.spaceName || ''}]达到极限值`);
				}
				return {"result":result,"newValue":newValue}
			},
			checkSpaceSize(isZoomIn, changeWidth, changeHeight){
				console.log("检查尺寸", isZoomIn, changeWidth, changeHeight, this.leftSpaces, this.rightSpaces)
			
				for (let index = 0; index < this.leftSpaces.length; index++) {
					const element = this.leftSpaces[index];
					if(isZoomIn){
						if(element.spaceWidth + changeWidth > element.spaceWidthMax || element.spaceHeight + changeHeight > element.spaceHeightMax){
							console.log("++++++++++移动空间达到极大值1", element.spaceId, element.spaceWidth + changeWidth > element.spaceWidthMax, element.spaceHeight + changeHeight > element.spaceHeightMax)
							console.log("++++++++++移动空间达到极大值宽", element.spaceWidth, changeWidth, element.spaceWidthMax)
							console.log("++++++++++移动空间达到极大值高", element.spaceHeight, changeHeight, element.spaceHeightMax)
							return false;
						}
					}else{
						if(element.spaceWidth - changeWidth < element.spaceWidthMin || element.spaceHeight - changeHeight < element.spaceHeightMin){
							console.log("++++++++++移动空间达到极小值2", element.spaceId)
							console.log("++++++++++移动空间达到极大值宽", element.spaceWidth, changeWidth, element.spaceWidthMin)
							console.log("++++++++++移动空间达到极大值高", element.spaceHeight, changeHeight, element.spaceHeightMin)
							return false;
						}
					}
				}
				for (let index = 0; index < this.rightSpaces.length; index++) {
					const element = this.rightSpaces[index];
					if(!isZoomIn){
						if(element.spaceWidth - changeWidth < element.spaceWidthMin || element.spaceHeight - changeHeight < element.spaceHeightMin){
							console.log("++++++++++其他空间达到极小值4", element.spaceId)
							console.log("++++++++++移动空间达到极大值宽", element.spaceWidth, changeWidth, element.spaceWidthMin)
							console.log("++++++++++移动空间达到极大值高", element.spaceHeight, changeHeight, element.spaceHeightMin)
							return false;
						}
					}else{
						if(element.spaceWidth + changeWidth > element.spaceWidthMax || element.spaceHeight + changeHeight > element.spaceHeightMax){
							console.log("++++++++++其他空间达到极大值3", element.spaceId)
							console.log("++++++++++移动空间达到极大值宽", element.spaceWidth, changeWidth, element.spaceWidthMax)
							console.log("++++++++++移动空间达到极大值高", element.spaceHeight, changeHeight, element.spaceHeightMax)
							return false;
						}
					}
				}
			
				return true
			},
			// 新版本空间移动计算
			changeCurSpaceSize(curSpace, changeArea, isZoomIn){
				
				// 计算当前空间的变化
				// 1.原先面积
				const oldArea = (curSpace.spaceWidth / 100) * (curSpace.spaceHeight / 100);
				const newArea = oldArea + changeArea * isZoomIn;
			
				const sizeScale = Math.sqrt(newArea/oldArea) ;
			
				console.log(`新面积:${newArea} 老面积:${oldArea}缩放比例:${sizeScale} 改变的面积:${changeArea} 是否放大:${isZoomIn} 中心点:${curSpace.centerX} ${curSpace.centerX}`);
				console.log(`改变前：尺寸：${curSpace.spaceWidth} ${curSpace.spaceHeight} 中心点:${curSpace.centerX} ${curSpace.centerY}`);
			
				curSpace.toScaleX = curSpace.spaceWidth * sizeScale / 300 ;
				curSpace.toScaleZ = curSpace.spaceHeight * sizeScale / 300 ;
			
			
				if(this.minspace1 && this.minspace1.spaceId == curSpace.spaceId){
					curSpace.toPx = (curSpace.spaceWidth * sizeScale - curSpace.spaceWidth) / 2 / 100 * -1;
					curSpace.toPz = (curSpace.spaceHeight * sizeScale - curSpace.spaceHeight) / 2 / 100 * -1;
					console.log("XXXXXXXX-计算空间变化信息1", curSpace.toScaleX, curSpace.toScaleZ, curSpace.toPx, curSpace.toPz);
				}else if(this.minspace2 && this.minspace2.spaceId == curSpace.spaceId){
					curSpace.toPx = (curSpace.spaceWidth * sizeScale - curSpace.spaceWidth) / 2 / 100;
					curSpace.toPz = (curSpace.spaceHeight * sizeScale - curSpace.spaceHeight) / 2 / 100 * -1;
					console.log("XXXXXXXX-计算空间变化信息2", curSpace.toScaleX, curSpace.toScaleZ, curSpace.toPx, curSpace.toPz);
				}else if(this.minspace3 && this.minspace3.spaceId == curSpace.spaceId){
					curSpace.toPx = (curSpace.spaceWidth * sizeScale - curSpace.spaceWidth) / 2 / 100;
					curSpace.toPz = (curSpace.spaceHeight * sizeScale - curSpace.spaceHeight) / 2 / 100;
					console.log("XXXXXXXX-计算空间变化信息3", curSpace.toScaleX, curSpace.toScaleZ, curSpace.toPx, curSpace.toPz);
				}else if(this.minspace4 && this.minspace4.spaceId == curSpace.spaceId){
					curSpace.toPx = (curSpace.spaceWidth * sizeScale - curSpace.spaceWidth) / 2 / 100 * -1;
					curSpace.toPz = (curSpace.spaceHeight * sizeScale - curSpace.spaceHeight) / 2 / 100;
					console.log("XXXXXXXX-计算空间变化信息4", curSpace.toScaleX, curSpace.toScaleZ, curSpace.toPx, curSpace.toPz);
				}else{
					return
				}
			
			
				// 更新数据：
			
				curSpace.spaceWidth = curSpace.spaceWidth * sizeScale;
				curSpace.spaceHeight = curSpace.spaceHeight * sizeScale;
				curSpace.centerX =  curSpace.centerX + curSpace.toPx * 100
				curSpace.centerY =  curSpace.centerY + curSpace.toPz * 100
				const spaceIndex = this.spaceList.findIndex((item)=>{
			        return item.spaceId == curSpace.spaceId;
			    })
			    if(spaceIndex!=-1){
			        this.spaceList[spaceIndex] = curSpace;
			    }
				console.log(`改变后：尺寸：${curSpace.spaceWidth} ${curSpace.spaceHeight} 中心点:${curSpace.centerX} ${curSpace.centerY} `, curSpace.toPx, curSpace.toPz);
				
			
			},
			
			findxxSpace(manSpace,changeArea, xiangxian, isZoomIn){
				if(xiangxian == 1){
					const spaceE = this.spaces1.find((item)=>{
			        	return item.spaceId == manSpace.eastId;
			    	})
					const spaceS = this.spaces1.find((item)=>{
			        	return item.spaceId == manSpace.southId;
			    	})
			
					const oldArea = (manSpace.spaceWidth / 100) * (manSpace.spaceHeight / 100);
					const newArea = oldArea + changeArea * isZoomIn;
			
					const sizeScale = Math.sqrt(newArea/oldArea) ;
			
					manSpace.toScaleX = manSpace.spaceWidth * sizeScale / 300 ;
					manSpace.toScaleZ = manSpace.spaceHeight * sizeScale / 300 ;
			
					if(spaceE){
						manSpace.toPx = (manSpace.spaceWidth * sizeScale - manSpace.spaceWidth) / 2 / 100  * -1 + spaceE.toPx  * 2;
						console.log("XXXXXXXX东边有空间", manSpace.spaceId, spaceE.toPx)
					}else{
						manSpace.toPx =  (manSpace.spaceWidth * sizeScale - manSpace.spaceWidth) / 2 / 100  * -1;
						console.log("XXXXXXXX东边没空间", manSpace.spaceId)
					}
						
					if(spaceS){
						manSpace.toPz = (manSpace.spaceHeight * sizeScale - manSpace.spaceHeight) / 2 / 100 * -1 + spaceS.toPz * 2;
						console.log("XXXXXXXX南边有空间", manSpace.spaceId, spaceS.toPz)
					}else{
						manSpace.toPz = (manSpace.spaceHeight * sizeScale - manSpace.spaceHeight) / 2 / 100 * -1;
						console.log("XXXXXXXX南边没空间", manSpace.spaceId)
					}
			
					
					console.log("XXXXXXXX-前象限1的其他空间", manSpace.spaceId, manSpace.spaceWidth, manSpace.spaceHeight, manSpace.centerX, manSpace.centerY, manSpace.toPx);
			
					manSpace.spaceWidth = manSpace.spaceWidth * sizeScale;
					manSpace.spaceHeight = manSpace.spaceHeight * sizeScale;
					manSpace.centerX +=  manSpace.toPx * 100
					manSpace.centerY +=  manSpace.toPz * 100
			
					console.log("XXXXXXXX-后象限1的其他空间", manSpace.spaceId, manSpace.spaceWidth, manSpace.spaceHeight, manSpace.centerX, manSpace.centerY);
			
					const spaceIndex = this.spaceList.findIndex((item)=>{
						return item.spaceId == manSpace.spaceId;
					})
					if(spaceIndex!=-1){
						this.spaceList[spaceIndex] = manSpace;
					}
					const spacesIndex = this.spaces1.findIndex((item)=>{
						return item.spaceId == manSpace.spaceId;
					})
					if(spacesIndex!=-1){
						this.spaces1[spacesIndex] = manSpace;
					}
				}
				if(xiangxian == 2){
					const spaceW = this.spaces2.find((item)=>{
			        	return item.spaceId == manSpace.westId;
			    	})
					const spaceS = this.spaces2.find((item)=>{
			        	return item.spaceId == manSpace.southId;
			    	})
			
					const oldArea = (manSpace.spaceWidth / 100) * (manSpace.spaceHeight / 100);
					const newArea = oldArea + changeArea * isZoomIn;
			
					const sizeScale = Math.sqrt(newArea/oldArea) ;
			
					manSpace.toScaleX = manSpace.spaceWidth * sizeScale / 300 ;
					manSpace.toScaleZ = manSpace.spaceHeight * sizeScale / 300 ;
			
					if(spaceW){
						manSpace.toPx = (manSpace.spaceWidth * sizeScale - manSpace.spaceWidth) / 2 / 100 + spaceW.toPx  * 2;
						console.log("XXXXXXXX西边有空间", manSpace.spaceId, spaceW.toPx)
					}else{
						manSpace.toPx =  (manSpace.spaceWidth * sizeScale - manSpace.spaceWidth) / 2 / 100;
						console.log("XXXXXXXX西边没空间", manSpace.spaceId)
					}
						
					if(spaceS){
						manSpace.toPz = (manSpace.spaceHeight * sizeScale - manSpace.spaceHeight) / 2 / 100 * -1 + spaceS.toPz * 2;
						console.log("XXXXXXXX南边有空间", manSpace.spaceId, spaceS.toPz)
					}else{
						manSpace.toPz = (manSpace.spaceHeight * sizeScale - manSpace.spaceHeight) / 2 / 100 * -1;
						console.log("XXXXXXXX南边没空间", manSpace.spaceId)
					}
			
					
					console.log("XXXXXXXX-前象限2的其他空间", manSpace.spaceId, manSpace.spaceWidth, manSpace.spaceHeight, manSpace.centerX, manSpace.centerY, manSpace.toPx);
			
					manSpace.spaceWidth = manSpace.spaceWidth * sizeScale;
					manSpace.spaceHeight = manSpace.spaceHeight * sizeScale;
					manSpace.centerX +=  manSpace.toPx * 100
					manSpace.centerY +=  manSpace.toPz * 100
			
					console.log("XXXXXXXX-后象限2的其他空间", manSpace.spaceId, manSpace.spaceWidth, manSpace.spaceHeight, manSpace.centerX, manSpace.centerY);
			
					const spaceIndex = this.spaceList.findIndex((item)=>{
						return item.spaceId == manSpace.spaceId;
					})
					if(spaceIndex!=-1){
						this.spaceList[spaceIndex] = manSpace;
					}
					const spacesIndex = this.spaces2.findIndex((item)=>{
						return item.spaceId == manSpace.spaceId;
					})
					if(spacesIndex!=-1){
						this.spaces2[spacesIndex] = manSpace;
					}
				}
				if(xiangxian == 3){
					const spaceW = this.spaces3.find((item)=>{
			        	return item.spaceId == manSpace.westId;
			    	})
					const spaceN = this.spaces3.find((item)=>{
			        	return item.spaceId == manSpace.northId;
			    	})
			
					const oldArea = (manSpace.spaceWidth / 100) * (manSpace.spaceHeight / 100);
					const newArea = oldArea + changeArea * isZoomIn;
			
					const sizeScale = Math.sqrt(newArea/oldArea) ;
			
					manSpace.toScaleX = manSpace.spaceWidth * sizeScale / 300 ;
					manSpace.toScaleZ = manSpace.spaceHeight * sizeScale / 300 ;
			
					if(spaceW){
						manSpace.toPx = (manSpace.spaceWidth * sizeScale - manSpace.spaceWidth) / 2 / 100 + spaceW.toPx  * 2;
						console.log("XXXXXXXX西边有空间", manSpace.spaceId, spaceW.toPx)
					}else{
						manSpace.toPx =  (manSpace.spaceWidth * sizeScale - manSpace.spaceWidth) / 2 / 100;
						console.log("XXXXXXXX西边没空间", manSpace.spaceId)
					}
						
					if(spaceN){
						manSpace.toPz = (manSpace.spaceHeight * sizeScale - manSpace.spaceHeight) / 2 / 100 + spaceN.toPz * 2;
						console.log("XXXXXXXX北边有空间", manSpace.spaceId, spaceN.toPz)
					}else{
						manSpace.toPz = (manSpace.spaceHeight * sizeScale - manSpace.spaceHeight) / 2 / 100;
						console.log("XXXXXXXX北边没空间", manSpace.spaceId)
					}
			
					
					console.log("XXXXXXXX-前象限3的其他空间", manSpace.spaceId, manSpace.spaceWidth, manSpace.spaceHeight, manSpace.centerX, manSpace.centerY, manSpace.toPx);
			
					manSpace.spaceWidth = manSpace.spaceWidth * sizeScale;
					manSpace.spaceHeight = manSpace.spaceHeight * sizeScale;
					manSpace.centerX +=  manSpace.toPx * 100
					manSpace.centerY +=  manSpace.toPz * 100
			
					console.log("XXXXXXXX-后象限3的其他空间", manSpace.spaceId, manSpace.spaceWidth, manSpace.spaceHeight, manSpace.centerX, manSpace.centerY);
			
					const spaceIndex = this.spaceList.findIndex((item)=>{
						return item.spaceId == manSpace.spaceId;
					})
					if(spaceIndex!=-1){
						this.spaceList[spaceIndex] = manSpace;
					}
					const spacesIndex = this.spaces3.findIndex((item)=>{
						return item.spaceId == manSpace.spaceId;
					})
					if(spacesIndex!=-1){
						this.spaces3[spacesIndex] = manSpace;
					}
				}
				if(xiangxian == 4){
					const spaceE = this.spaces4.find((item)=>{
			        	return item.spaceId == manSpace.eastId;
			    	})
					const spaceN = this.spaces4.find((item)=>{
			        	return item.spaceId == manSpace.northId;
			    	})
			
					const oldArea = (manSpace.spaceWidth / 100) * (manSpace.spaceHeight / 100);
					const newArea = oldArea + changeArea * isZoomIn;
			
					const sizeScale = Math.sqrt(newArea/oldArea) ;
			
					manSpace.toScaleX = manSpace.spaceWidth * sizeScale / 300 ;
					manSpace.toScaleZ = manSpace.spaceHeight * sizeScale / 300 ;
			
					if(spaceE){
						manSpace.toPx = (manSpace.spaceWidth * sizeScale - manSpace.spaceWidth) / 2 / 100 * -1 + spaceE.toPx  * 2;
						console.log("XXXXXXXX东边有空间", manSpace.spaceId, spaceE.toPx)
					}else{
						manSpace.toPx =  (manSpace.spaceWidth * sizeScale - manSpace.spaceWidth) / 2 / 100 * -1;
						console.log("XXXXXXXX东边没空间", manSpace.spaceId)
					}
						
					if(spaceN){
						manSpace.toPz = (manSpace.spaceHeight * sizeScale - manSpace.spaceHeight) / 2 / 100 + spaceN.toPz * 2;
						console.log("XXXXXXXX北边有空间", manSpace.spaceId, spaceN.toPz)
					}else{
						manSpace.toPz = (manSpace.spaceHeight * sizeScale - manSpace.spaceHeight) / 2 / 100;
						console.log("XXXXXXXX北边没空间", manSpace.spaceId)
					}
			
					
					console.log("XXXXXXXX-前象限4的其他空间", manSpace.spaceId, manSpace.spaceWidth, manSpace.spaceHeight, manSpace.centerX, manSpace.centerY, manSpace.toPx);
			
					manSpace.spaceWidth = manSpace.spaceWidth * sizeScale;
					manSpace.spaceHeight = manSpace.spaceHeight * sizeScale;
					manSpace.centerX +=  manSpace.toPx * 100
					manSpace.centerY +=  manSpace.toPz * 100
			
					console.log("XXXXXXXX-后象限4的其他空间", manSpace.spaceId, manSpace.spaceWidth, manSpace.spaceHeight, manSpace.centerX, manSpace.centerY);
			
					const spaceIndex = this.spaceList.findIndex((item)=>{
						return item.spaceId == manSpace.spaceId;
					})
					if(spaceIndex!=-1){
						this.spaceList[spaceIndex] = manSpace;
					}
					const spacesIndex = this.spaces4.findIndex((item)=>{
						return item.spaceId == manSpace.spaceId;
					})
					if(spacesIndex!=-1){
						this.spaces4[spacesIndex] = manSpace;
					}
				}
			},
			
			//空间面积等变更后-同步更新其他数据对象
			updataPageData(){
				let sumArea = 0;
				this.spaceList.forEach(space=>{
					let curSpaceArea = parseFloat((
						(space.spaceWidth * space.spaceHeight) * space.spaceRatio / 10000
					).toFixed(2));
					sumArea +=curSpaceArea;
				})
				this.changeArea = parseFloat((sumArea - this.fixedArea).toFixed(2));
				this.sumArea = parseFloat(sumArea.toFixed(2));
				let str = JSON.stringify(this.spaceList)
				//更新当前空间对象
				this.curHouseObj.houseJson = str;
				this.curHouseObj.houseArea = this.sumArea;
                if(!this.curLayoutStruct){
                    this.curLayoutStruct = [this.curHouseObj]
                }
				//更新提交的数据
				let layoutStruct = this.curLayoutStruct.find(it=>{
					return it.id == this.curHouseObj.id
				})
				layoutStruct.houseJson = str;
				layoutStruct.houseArea = this.sumArea;
                setStorage('curLayoutStruct', this.curLayoutStruct);//把楼层的数据存入缓存中
				this.currentChangeSpaceId = null;//变化结束后
				console.warn("***curLayoutStruct-updataPageData***",this.changeArea,this.sumArea,this.curHouseFloor,this.curHouseObj)
			},
			
			
			onMouseMove(e){
				return false;
			},
			//进入布局选择模式
			enterPlot(gltf){
				if(gltf.spaceType==13){//楼梯不处理
					return false
				}
				// this.selectSpace = this.spaceList.find(it=>it.spaceId==gltf.spaceId);
				this.$refs.viewShell.changeStyleType(3,this.selectSpace)
			},
			selectSpaceHandle(gltf){
				if(gltf.spaceType==13){//楼梯不处理
					return false
				}
                console.warn("***selectSpaceHandle0***",this.selectSpace)
				if(this.selectSpace){
					this.changeSpaceColor(this.selectSpace.spaceId,2);//取消上一个空间的颜色
				}
				this.selectSpace = this.spaceList.find(it=>it.spaceId==gltf.spaceId);
				this.$store.state.curSpaceId = this.selectSpace.spaceId;
				this.currentChangeSpaceId = this.selectSpace.spaceId;
				// this.moveMeshCenter(this.selectSpace);
				this.changeSpaceColor(this.selectSpace.spaceId,1);//设置选中空间的颜色
				console.warn("***selectSpaceHandle***",this.selectSpace)
			},
			//用户选择的布局id-需要切换到这个布局去
			userSelectPlot(layoutObj,space=null){
				if(!layoutObj){
					console.warn("***userSelectPlot***数据错误")
					return false
				}
				let spaceId = space ? space.spaceId : this.selectSpace.spaceId;
				console.warn("***userSelectPlot***",spaceId,layoutObj)
				this.changeSingleLayout(space,layoutObj);
				this.updataLable(spaceId,layoutObj);
			},
			async goRoam1(spaceId){
				if(this.overChange){
					this.$message.warning("空间正在调整");
					return false
				}
                this.locationHandle();
                setTimeout( async ()=>{
                    let shottingImg = await this.shottingAction() + "?x-oss-process=image/auto-orient,1/quality,Q_46/format,jpg";//开始截图
                    console.warn("***shottingImg***",shottingImg,this.selectSpace,this.curLayoutStruct);
                    setStorage('shottingImg', shottingImg);//把空间选择的数据存入本地缓存里面，方便后续使用
                    if(!this.curLayoutStruct){
                        this.curLayoutStruct = [this.curHouseObj]
                    }
                    let curObj = this.curLayoutStruct.find(it=>it.id==this.curHouseObj.id);
                    if(curObj){
                        curObj.shottingImg = shottingImg;
                        setStorage('curLayoutStruct', this.curLayoutStruct);//把楼层的数据存入缓存中
                    }
                    if(this.selectSpace){
                    	this.changeSpaceColor(this.selectSpace.spaceId,2);//取消上一个空间的颜色
                        this.selectSpace = null;
                    }
                    let gltf = this.lableItem.find(it=>it.spaceId==spaceId);
                    if(gltf){
                        this.goRoam(gltf)
                    }
                },550);
				
			},
			//物体漫游-切换页面的方式进入
			goRoam(gltf){
				console.warn('goRoam',gltf,this.selectSpace);
				if(gltf.spaceType==13){//楼梯不能跳转
					return false
				}
				let spaceId = this.selectSpace ? this.selectSpace.spaceId : gltf.spaceId;//具体的空间Id
				let data = {
					spaceId:spaceId,
					houseId:this.houseId,
                    locusValue:gltf.text || "",
				}
				if(this.repeatFlag){
					return false;
				}
				this.repeatFlag = true;
				router.push({
					name: "webgl_rxdz_test_roam",
					query:data
				});
				if(this.isIOS){
					setStorage('curHouseObj', this.curHouseObj);
					setStorage('wallList', this.wallList);
				}
				this.$store.dispatch('setCurHouseObj', this.curHouseObj);
				this.$store.dispatch('setWallList', this.wallList);
				setTimeout(()=> {
					this.repeatFlag = false;
				}, 1000);
			},
			//obj 物体对象，type 是否改变颜色
			moveMeshCenter(obj,type){
				console.warn("**moveMeshCenter***",obj)
				if(obj && this.gltfSpaces && this.gltfSpaces.length>0){
					this.moveMeshCenterHandle(obj,type);
				}
			},
            locationHandle(){
                this.movePositionHandle(this.allSpaceCenter,this.cameraStarPosition.y);//把摄像机移动到所有模型的中心点（水平面中心）
            },
            // 绘制地板
            async loadSpace(){
				this.spaceList = [];
				this.wallIds = [];
				this.layoutIds = [];
				this.gltfSpaces = [];
				this.curWallArr = [];
				this.progress = 0;
				if(!this.curHouseObj){//减少重复请求
					return false
				}
				let type=[];
                if(this.curHouseObj){
                    const spaceDetail = this.curHouseObj;
                    const spaceList = JSON.parse(spaceDetail.houseJson);
                    // 交换centerX， centerY;上一页面已经处理过了，这里不在需要处理
                    for (let index = 0; index < spaceList.length; index++) {
                        var element = spaceList[index];
                        // const centerX = JSON.parse(JSON.stringify(element.centerX))
                        // element.centerX = element.centerY;
                        // element.centerY = centerX;
						element.wallMoveValue = "[0,0,0,0]"
                        this.spaceList.push(element);
                        this.wallIds.push(element.wallId);
						this.layoutIds.push(element.layoutId);
						type.push(element.spaceType);
                        if(element.isSelected){ // 默认选中空间
                            this.curSpaceObj = element;
                        }
                    }
                    if(!this.curSpaceObj && this.spaceList.length > 0){
                        this.curSpaceObj = this.spaceList[0];
                    }
                }
                this.allSpaceCenter = this.getAllSpaceCenter(this.spaceList);//获取所有空间的中心点
                console.log("该户型空间数据:", this.spaceList,this.spaceList.map(it=>it.spaceId), this.layoutIds,type);
                console.log("当前选中的空间:", this.curSpaceObj,this.curHouseObj);
				this.spaceListBackup = JSON.parse(JSON.stringify(this.spaceList));
				this.$store.state.curSpaceId = this.curSpaceObj.spaceId;
				this.loaderSpaceArr(this.spaceList);
                // 绘制墙体
                this.getHouseTypeSpaceWalls();
            },
			//更改空间显示名称 X空间 类型 根据布局所属类型来显示
			updataLable(spaceId,layoutObj){
				let list = this.arrFrunList;
				let lable = this.lableItem.find(it=>it.spaceId == spaceId);
				let name = spaceTypes[layoutObj.type - 1];
				lable.text = name;
				console.warn("***updataLable***",lable)
				this.$refs.viewShell.$refs.viewCareful.updataData(spaceId,layoutObj);
			},
			// 添加文字标签
			addWordLabel(){
				if(!this.gltfSpaces || this.gltfSpaces.length <= 0){
					return false;
				}
				// 方案二
				this.lableItem = [];
				this.gltfSpaces.forEach((cube,index) =>{
					// 给地板加上空间类型标注, 空间为链接空间的不显示
					if(cube.spaceName && !cube.isSizeLock){
						let spaceIndex = this.spaceList.filter(it=>it.spaceName && !it.isSizeLock).findIndex(item=>item.spaceId==cube.spaceId);
						let name = spaceTypes[cube.spaceType - 1];
						if(cube.spaceType==15){			//更改空间显示名称 X空间 类型 根据布局所属类型来显示
							let layoutId = this.spaceList.find(it => it.spaceId == cube.spaceId).layoutId;
							let layout = this.arrFrunList.find(it=>it.id == layoutId);
							if(layout){
								name = spaceTypes[layout.type - 1];
							}
						}
						this.lableItem.push(
							{
								text:name,
								spaceId:cube.spaceId,
								spaceType:cube.spaceType,
								transform:'',
								spaceIndex:spaceIndex,
								cubeIndex:index,
							}
						)
					}
				})
				this.showLables = true;
				// this.updateLables();//更新lable
			}, 
			// 获取墙体数据
            async getHouseTypeSpaceWalls(){
                let data = {id:this.wallIds}
                // let data = {id:[2385]}
                const res = await requestConfig('getHouseTypeSpaceWalls', data, true);
                console.log("墙体数据:", res.list)
                let wallList = [];
                if(res.success){
                    wallList = this.wallList = res.list;
                }
                let wallArr = []
                for (let index = 0; index < wallList.length; index++) {//每个空间对应一个数据
                    let element = JSON.parse(wallList[index].wallJson);
					let space = this.spaceList.find(space=>space.spaceId==element.spaceId);
					if(!space){//存在映射不上的数据
						console.warn("***computeWallHandleOld-warn***",index,element,this.spaceList)
						continue;
					}
					this.computeWallHandleOld(space,element);//提前计算
                    for (let i = 0; i < element.wallData.length; i ++) {//对应空间里面的4个方向的墙壁数据
                        let wallData = element.wallData[i];
						//对应方向的墙壁的墙体模型数据列表，每一面墙可能有多个模型
                        for (let j = 0; j < wallData.wallModelData.length; j ++) {
                            let wallModelData = wallData.wallModelData[j];
                            wallArr.push({spaceId:element.spaceId, wallModelData:wallModelData, wallDirection:wallData.wallDirection})
                            // console.log("wallModelData", element,wallData.wallDirection, wallModelData.wallType );
                        }
                    }
                }
                this.loadSpaceObjWalls(wallArr, wallList);
				this.getOverallArrangementDetailsList(1);
            },
			// 加载单个空间墙体资源
            async loadSpaceObjWalls(wallArr, wallList){
                // 加载远程墙体模型资源
				let startTime = new Date().getTime();
                // console.log("wallArr:", wallArr)
				let promise_list = [];
				let realWallArr = this.preWallData(wallArr);
				let arrLength = realWallArr.length;
				realWallArr && realWallArr.forEach((item,index) => {
					promise_list.push(
						new Promise((resolve, reject) => {
							this.loadWallModels(item, wallList, arrLength , resolve);
						})
					)
				});
				Promise.all(promise_list).then(()=>{
					let endTime = new Date().getTime();
					console.log("模型全部加载完成，时间：",endTime - startTime,this.allSpaceCenter);
					this.progress = 100;
					// this.$refs.myLoading.showLoading("加载中..." + this.progress + '%')
					// 设置空间数组的墙体信息
					// this.setSpaceListWallInfo();
					this.$nextTick(()=>{
                        this.movePositionHandle(this.allSpaceCenter);//把摄像机移动到所有模型的中心点（水平面中心）
						// this.moveMeshCenter(this.curSpaceObj);
						// this.myLoadingStatus = false;
						// this.$refs.myLoading.hideLoading();
						setTimeout(()=>{
							this.addWordLabel(); // 添加文字标签
						}, 610);
						// 设置空间数组的墙体信息 
					})
				})
            },
			// 选择墙体
			selectedWall(direction){
				if(!direction || direction==""){
					return
				}
			    console.log(`当前空间的id：${this.curSpaceObj.spaceId};墙面方向：${direction};宽度：${this.curSpaceObj.spaceWidth};宽度：${this.curSpaceObj.spaceHeight}`)
			    console.log("当前空间的:", this.curSpaceObj);
			    this.leftSpaces = [];
			    this.rightSpaces = [];
			    this.tempSpaceList = JSON.parse(JSON.stringify(this.spaceList));
			    // 计算关联空间
			    this.findLeftRelateSpace(this.curSpaceObj, direction);
			    console.log("空间数组:", this.leftSpaces, this.rightSpaces);
			
				// 计算墙体的可移动范围
				var min = 0;
				var max = 300;
				// 计算最小值
				for (let index = 0; index < this.leftSpaces.length; index++) {
			        const element = this.leftSpaces[index];
					console.log("左边空间数据:", element);
					var spaceMoveNW = element.spaceWidth;
					var spaceMoveSW = element.spaceWidth;
					var spaceMoveEH = element.spaceHeight;
					var spaceMoveWH = element.spaceHeight;
					var curSpaceWall = [];
					for (let index = 0; index < this.gltfWalls.length; index++) {
						const wall = this.gltfWalls[index];
						if(element.spaceId == wall.spaceId && wall.wallDirection != direction){
							curSpaceWall.push(wall);
							if((direction == "W" || direction == "E") && wall.wallDirection != direction){
								if(wall.wallDirection == "N"){
									spaceMoveNW -= wall.wallModelData.wallWidth;
									console.log("北边墙:", spaceMoveNW, wall.wallModelData.wallWidth, wall.id);
								}
								if(wall.wallDirection == "S"){
									spaceMoveSW -= wall.wallModelData.wallWidth;
									console.log("南边墙:", spaceMoveSW, wall.wallModelData.wallWidth, wall.id);
								}
			
								this.curWallValue = Math.floor(Math.min(Math.min(spaceMoveNW, spaceMoveSW), this.curWallValue));
							}
							if((direction == "N" || direction == "S") && wall.wallDirection != direction){
								if(wall.wallDirection == "E"){
									spaceMoveEH -= wall.wallModelData.wallWidth;
									console.log("东边墙:", spaceMoveNW, wall.wallModelData.wallWidth, wall.id);
								}
								if(wall.wallDirection == "W"){
									spaceMoveWH -= wall.wallModelData.wallWidth;
									console.log("西边墙:", spaceMoveSW, wall.wallModelData.wallWidth, wall.id);
								}
								this.curWallValue = Math.floor(Math.min(Math.min(spaceMoveEH, spaceMoveWH), this.curWallValue));
							}
						}
					}
			
					// 排序墙体数据
					curSpaceWall.sort(function(a,b){return a.wallModelData.id -b.wallModelData.id});
			    	curSpaceWall.sort(function(a,b){return a.wallDirection.localeCompare(b.wallDirection)})
			
					console.log("墙体模型:", curSpaceWall, spaceMoveNW, spaceMoveSW);
					console.log("可缩小的最小值:", Math.floor(Math.min(spaceMoveNW, spaceMoveSW)));
			
					if((direction == "W" || direction == "E") && element.spaceWidth == this.curWallValue){
						this.curWallValue = 149;
					}
					if((direction == "N" || direction == "S") && element.spaceHeight == this.curWallValue){
						this.curWallValue = 149;
					}
					// this.curWallValue = Math.floor(Math.min(spaceMoveNW, spaceMoveSW));
			    }
				
				// 计算最大值
				
				for (let index = 0; index < this.rightSpaces.length; index++) {
			        const element = this.rightSpaces[index];
					console.log("右边空间数据:", element);
					var spaceMoveNW = element.spaceWidth;
					var spaceMoveSW = element.spaceWidth;
					var spaceMoveEH = element.spaceHeight;
					var spaceMoveWH = element.spaceHeight;
					var curSpaceWall = [];
					for (let index = 0; index < this.gltfWalls.length; index++) {
						const wall = this.gltfWalls[index];
						if(element.spaceId == wall.spaceId && wall.wallDirection != direction){
							curSpaceWall.push(wall);
							if((direction == "W" || direction == "E") && wall.wallDirection != direction){
								if(wall.wallDirection == "N"){
									spaceMoveNW -= wall.wallModelData.wallWidth;
									console.log("北边墙:", spaceMoveNW, wall.wallModelData.wallWidth, wall.id);
								}
								if(wall.wallDirection == "S"){
									spaceMoveSW -= wall.wallModelData.wallWidth;
									console.log("南边墙:", spaceMoveSW, wall.wallModelData.wallWidth, wall.id);
								}
			
								this.curWallMaxValue = Math.floor(Math.min(spaceMoveNW, spaceMoveSW)) + this.curWallValue;
							}
							if((direction == "N" || direction == "S") && wall.wallDirection != direction){
								if(wall.wallDirection == "E"){
									spaceMoveEH -= wall.wallModelData.wallWidth;
									console.log("东边墙:", spaceMoveNW, wall.wallModelData.wallWidth, wall.id);
								}
								if(wall.wallDirection == "W"){
									spaceMoveWH -= wall.wallModelData.wallWidth;
									console.log("西边墙:", spaceMoveSW, wall.wallModelData.wallWidth, wall.id);
								}
								this.curWallMaxValue = Math.floor(Math.min(spaceMoveEH, spaceMoveWH)) + this.curWallValue;
							}
						}
					}
			
					// 排序墙体数据
					curSpaceWall.sort(function(a,b){return a.wallModelData.id -b.wallModelData.id});
			    	curSpaceWall.sort(function(a,b){return a.wallDirection.localeCompare(b.wallDirection)})
			
					console.log("墙体模型:", curSpaceWall, spaceMoveNW, spaceMoveSW);
					console.log("可缩小的最小值:", Math.floor(Math.min(spaceMoveNW, spaceMoveSW)));
			    }
			
			
				console.log(`当前墙面的最大值：${this.curWallMaxValue}, 最小值：${this.curWallValue}`)
				// 统计变化的空间
				this.changeSpaces.push(...this.leftSpaces)
				this.changeSpaces.push(...this.rightSpaces)
			},
			// 递归寻找左边->右边关联空间
			findLeftRelateSpace(spaceObj, direction){
			    const {eastId, westId, northId, southId, spaceId} = spaceObj;
			
			    const leftIndex =  this.tempSpaceList.findIndex((item)=>{
			        return item.spaceId == spaceId;
			    })
			    if(leftIndex!=-1){
			        const spaceObj =  this.tempSpaceList[leftIndex];
			        this.leftSpaces.push(spaceObj);
			        this.tempSpaceList.splice(leftIndex,1);
			
			        const leftNextIndex =  this.tempSpaceList.findIndex((item)=>{
			            if(direction == "E"){
			                return item.spaceId == eastId;
			            }else if(direction == "W"){
			                return item.spaceId == westId;
			            }else if(direction == "S"){
			                return item.spaceId == southId;
			            }else if(direction == "N"){
			                return item.spaceId == northId;
			            }
			        })
			        if(leftNextIndex!=-1){
			            const nextSpaceObj =  this.tempSpaceList[leftNextIndex];
			            console.log("递归再一次", nextSpaceObj);
			            this.findRightRelateSpace(nextSpaceObj, direction);
			        }
			
			        const rightArr = this.tempSpaceList.filter((item)=>{
			            if(direction == "E"){
			                return item.westId == spaceId;
			            }else if(direction == "W"){
			                return item.eastId == spaceId;
			            }else if(direction == "S"){
			                return item.northId == spaceId;
			            }else if(direction == "N"){
			                return item.southId == spaceId;
			            }
			        })
			
			        for (let index = 0; index < rightArr.length; index++) {
			            const nextSpaceObj = rightArr[index];
			            // const nextSpaceObj =  this.tempSpaceList[rightNextIndex];
			            console.log("递归再一次", nextSpaceObj);
			            this.findRightRelateSpace(nextSpaceObj, direction);
			        }
			
			    }
			
			},
			// 递归寻找右边->左边关联空间
			findRightRelateSpace(spaceObj, direction){
			    const {eastId, westId, northId, southId, spaceId} = spaceObj;
			
			    const rightIndex =  this.tempSpaceList.findIndex((item)=>{
			        return item.spaceId == spaceId;
			    })
			
			    if(rightIndex!=-1){
			        const spaceObj =  this.tempSpaceList[rightIndex];
			        this.rightSpaces.push(spaceObj);
			        this.tempSpaceList.splice(rightIndex,1);
			        console.log("当前空间数组:", this.tempSpaceList);
			
			        const leftNextIndex =  this.tempSpaceList.findIndex((item)=>{
			            if(direction == "E"){
			                return item.spaceId == westId;
			            }else if(direction == "W"){
			                return item.spaceId == eastId;
			            }else if(direction == "N"){
			                return item.spaceId == southId;
			            }else if(direction == "S"){
			                return item.spaceId == northId;
			            }
			        })
			        if(leftNextIndex!=-1){
			            const nextSpaceObj =  this.tempSpaceList[leftNextIndex];
			            console.log("递归再一次", nextSpaceObj);
			            this.findLeftRelateSpace(nextSpaceObj, direction);
			        }
			
			        const rightArr = this.tempSpaceList.filter((item)=>{
			            if(direction == "E"){
			                return item.eastId == spaceId;
			            }else if(direction == "W"){
			                return item.westId == spaceId;
			            }else if(direction == "N"){
			                return item.northId == spaceId;
			            }else if(direction == "S"){
			                return item.southId == spaceId;
			            }
			        });
			
			        for (let index = 0; index < rightArr.length; index++) {
			            const nextSpaceObj = rightArr[index];
			            console.log("递归再一次", nextSpaceObj);
			            this.findLeftRelateSpace(nextSpaceObj, direction);
			        }
			
			    }
			},
			moveSpaceWall(direction, moveOut, moveValue){
			
				// let isNS = (direction == "N" || direction == "S")
				// if(!this.checkRightSpace(!moveOut, moveValue, isNS)){
				// 	return
				// }
				// 隐藏变化空间的家具模型，空间动画结束后显示
				if(moveValue<= 0){ // 无需变化
					return
				}

				this.changeLayoutModelState();
				console.log("关联空间XXXXX", this.leftSpaces, this.rightSpaces)
			    for (let index = 0; index < this.leftSpaces.length; index++) {
			        const element = this.leftSpaces[index];
					const space = this.spaceList.find((item)=>{
			            return item.spaceId == element.spaceId;
			        })
			        this.moveWall(space, direction, moveOut, moveValue);
					// this.wallTransform(space, direction, moveOut, moveValue);
			    }
			    let otherdirection = "";
			    switch (direction) {
			        case "E":
			            otherdirection = "W"
			            break;
			        case "W":
			            otherdirection = "E"
			            break;
			        case "N":
			            otherdirection = "S"
			            break;
			        case "S":
			            otherdirection = "N"
			            break;
			    }
			    for (let index = 0; index < this.rightSpaces.length; index++) {
			        const element = this.rightSpaces[index];
			        this.moveWall(element, otherdirection, !moveOut, moveValue);
			    }
			    console.log(`当前空间的后id：${this.curSpaceObj.spaceId};墙面方向：${direction};宽度：${this.curSpaceObj.spaceWidth};高度：${this.curSpaceObj.spaceHeight}`)
			},
			// 调整大小
			// direction:方向
			// moveOut:是否外移
			// moveValue: 移动距离
			moveWall(spaceObj, direction, moveOut, moveValue){
			    console.log(`移动的空间的id-------：${spaceObj.spaceId};移动方向：${direction};是否外移：${moveOut};移动距离：${moveValue}`,spaceObj)
				const oldSpaceObj = JSON.parse(JSON.stringify(spaceObj))
				
			    const cube = this.gltfSpaces.find((item)=>{
			        return item.spaceId == spaceObj.spaceId;
			    })
			
			    if(!cube){
                    console.warn("不存在 cube",this.gltfSpaces)
			        return
			    }
			
			    if(!moveOut){
			        moveValue = moveValue * -1;
			    }
			    const {position,scale} = cube;
			    // 重新计算缩放 和 位置
			    let toScaleX = scale.x;
			    let toScaleZ = scale.z;
			    let toPx = position.x;
			    let toPz = position.z;
			    if(direction == 'E' || direction == 'W'){
			        let spaceWidth = scale.x * 300; 
			        toScaleX = (spaceWidth + moveValue) / 300;
			        if(direction == 'W'){
			            toPx = position.x - moveValue / 2 / 100;
			        }else{
			            toPx = position.x + moveValue / 2 / 100;
			        }
			        spaceObj.spaceWidth +=  moveValue;
			        spaceObj.centerX = toPx * 100;
			    }
			    
			    if(direction == 'N' || direction == 'S'){
			        let spaceHeight = scale.z * 300;  
			        toScaleZ = (spaceHeight + moveValue) / 300;
			        if(direction == 'N'){
			            toPz = position.z - moveValue / 2 / 100;
			        }else{
			            toPz = position.z + moveValue / 2 / 100;
			        }
			        spaceObj.spaceHeight += moveValue;
			        spaceObj.centerY = toPz * 100 * -1;
			    }
			    console.log("curSpaceObj",this.curSpaceObj.spaceId, spaceObj.spaceId, spaceObj.centerX, spaceObj.centerY, toScaleX,toScaleZ,toPx,toPz)    
			    console.log("当前空间变化后的尺寸",spaceObj.spaceWidth, spaceObj.spaceHeight, spaceObj.spaceId)          
			
			    // 更新数据
			    const spaceIndex = this.spaceList.findIndex((item)=>{
			        return item.spaceId == spaceObj.spaceId;
			    })
			    if(spaceIndex!=-1){
			        this.spaceList[spaceIndex] = spaceObj;
			        if(this.curSpaceObj.spaceId == spaceObj.spaceId){
			            this.curSpaceObj = spaceObj;
			        }
			    }
				this.curHouseObj.houseJson = JSON.stringify(this.spaceList);
			    //空间动画处理-提取到floorMethod.js中
				this.changeSpacesAnim({spaceId:spaceObj.spaceId,toScaleX,toScaleZ,toPx,toPz,spaceObj})
				// 墙体动画处理
				//// 根据空间尺寸，更新前提数据
				const wallObj = this.wallList.find((item)=>{
					return item.id == spaceObj.wallId;
				})
			
				const initSpaceObj = this.spaceListBackup.find((item)=>{
					return item.spaceId == spaceObj.spaceId;
				})
			
				if(wallObj){
					let element = JSON.parse(wallObj.wallJson);
					console.warn("****wallObj**",element)
					this.computeWallHandle(initSpaceObj, spaceObj, element, moveOut, direction); // 重新计算-并把空间的计算结果同步到gltfWalls中
				}
				
			    // 移动墙体
			    let curSpaceWall = [];
			    for (let index = 0; index < this.gltfWalls.length; index++) {
			        const element = this.gltfWalls[index];
			        if(spaceObj.spaceId == element.spaceId){
			            curSpaceWall.push(element);
			        }
			    }
				
				//移动的是西方的墙壁 和 南方的墙壁，该空间的几何体中心则移动变化
				if(direction == 'W' || direction == 'S'){
					spaceObj.rightCenter = true;
				}
				//移动的是东方的墙壁 和 北方的墙壁，该空间的几何体中心则不移动变化
				if(direction == 'E'|| direction == 'N'){
					spaceObj.rightCenter = false;
				}
				spaceObj.direction = direction
			    // 排序墙体数据
			    curSpaceWall.sort(function(a,b){return a.wallModelData.id -b.wallModelData.id});
			    curSpaceWall.sort(function(a,b){return a.wallDirection.localeCompare(b.wallDirection)})
			
				console.log("移动的墙体：", spaceObj, direction, curSpaceWall);
				// return;
			
				
				for (let index = 0; index < curSpaceWall.length; index++) {
					const element = curSpaceWall[index];
					console.log("重新计算墙体-墙体数据：", element, element);
					this.drawModel(element.wallModelData, spaceObj, element, true)
				}
				// }
			},
			// 空隙自动补签逻辑
			autoCreateWall(directionIndex, spaceObj){
			
				let direction = ""
				switch (directionIndex) {
					case 1:
						direction = "N"
						break;
					case 2:
						direction = "S"
						break;
					case 3:
						direction = "W"
						break;
					case 4:
						direction = "E"
						break;
					default:
						break;
				}
			
				// 东西墙 检查 南北墙关联空间  南北墙 检查 东西墙关联空间
				if(direction == "E" || direction == "W"){
					if(spaceObj.quadrant == 3 || spaceObj.quadrant == 4){ // 南边空间
						console.log("南北朝向墙自动补齐", this.leftSpaces, this.rightSpaces)
						
						
			
						this.selectedWall("N");
						this.checkIsAutoCreateWall("N", spaceObj)
			
						
			
						this.selectedWall("S");
						this.checkIsAutoCreateWall("S", spaceObj)
			
						let autoWall = this.gltfAutoWalls.find(item=>{
							return item.spaceId == spaceObj.spaceId ;
						})
			
						if(autoWall){
							console.log("南北朝向墙自动补齐---", autoWall, this.gltfAutoWalls)
							if(autoWall.wallDirection == "E"){
								autoWall.obj.position.x = (spaceObj.centerX + (spaceObj.spaceWidth / 2) - 5) / 100
							}
							 
						}
						
					}else{ // 北边关联空间
			
					}
				}else{
					if(spaceObj.quadrant == 3 || spaceObj.quadrant == 4){ // 南边空间
						
						console.log("东西朝向墙自动补齐", this.leftSpaces, this.rightSpaces)
						
						this.selectedWall("E");
						this.checkIsAutoCreateWall("E", spaceObj)
			
						this.selectedWall("W");
						this.checkIsAutoCreateWall("W", spaceObj)
			
						
						
					}else{ // 北边关联空间
			
					}
				}
				
			},
			// 检测是否需要补强
			checkIsAutoCreateWall(direction, spaceObj){
				var that = this;
				// 判断南边墙是否需要补充
				if(this.rightSpaces.length == 0){
					console.log("不需要补墙1", direction, this.gltfAutoWalls)
					return;
				}
				const n = (direction == "S" || direction == "E") ? 1 : -1; // 南北方向计算系数
			
				console.log("自动补墙", this.leftSpaces, this.rightSpaces);
			
				let px = 0;
				let pz = 0;
				let sx = 1;
				let sz = 1;
				let rightids = []
				if(spaceObj.quadrant == 3){
			
					// 左边空间的最大值
					let leftMaxValue = 0;
					for (let index = 0; index < this.leftSpaces.length; index++) {
						const element = this.leftSpaces[index];
						if(direction=="S" || direction == "N"){
							const curvalue = element.centerX + element.spaceWidth / 2 
							if(leftMaxValue < curvalue){
								leftMaxValue = curvalue
							}
						}else{
							leftMaxValue += (-element.centerY + element.spaceHeight / 2)
						}
					}
					// rightSpaces右边最大值
					let rightMaxValue = 0;
					for (let index = 0; index < this.rightSpaces.length; index++) {
						const element = this.rightSpaces[index];
						if(direction=="S" || direction == "N"){
							const curvalue = element.centerX + element.spaceWidth / 2
							if(rightMaxValue < curvalue){
								rightMaxValue = curvalue
							}
						}else{
							rightMaxValue += -element.centerY + element.spaceHeight / 2
						}
						rightids.push(element.spaceId)
					}
			
					// 是否有墙
					const index = this.gltfWalls.findIndex(item=>{
						// console.log("墙面模型", item)
						return spaceObj.spaceId == item.spaceId && item.wallDirection == direction;
					})
			
					// 有墙，左边墙>右边墙，计算南北墙
					if(index != -1 && leftMaxValue > rightMaxValue && (direction == "S" || direction == "N")){
						console.log("不需要补墙251",index, leftMaxValue, rightMaxValue)
						// 是否补过墙
						const autoWall = this.gltfAutoWalls.find(item=>{
							return item.rightids.indexOf(spaceObj.spaceId) != -1 && item.wallDirection == (direction == "S" ? "N": "S");
						})
						if(autoWall){
							let cube = autoWall.obj;
							if(cube){
								cube.scale.set(0,0,0);
							}
						}
						return
					}
					// 有墙，左边墙>右边墙，计算东西墙
					if(index != -1 && leftMaxValue > rightMaxValue && (direction == "E" || direction == "W")){
						console.log("不需要补墙252",index, leftMaxValue, rightMaxValue, spaceObj.spaceId, direction, this.gltfAutoWalls)
						const autoWall = this.gltfAutoWalls.find(item=>{
							return item.rightids.indexOf(spaceObj.spaceId) != -1 && item.wallDirection == (direction == "E" ? "W": "E");
						})
						if(autoWall){
							let cube = autoWall.obj;
							if(cube){
								cube.scale.set(0,0,0);
							}
						}
						return
					}
			
					let wallOffset = index != -1 ? -5 : 5;
			
					console.log("空间最大值", leftMaxValue, rightMaxValue, direction, index);
					const cubeW = Math.abs(leftMaxValue - rightMaxValue);
			
					if(direction=="S" || direction == "N"){
						px = (Math.min(leftMaxValue, rightMaxValue) + cubeW / 2) / 100
						pz = (-spaceObj.centerY + spaceObj.spaceHeight * n / 2 + wallOffset * n) / 100;
						sx =  cubeW / 10 ;
						// 长边有墙
					}else{
						px = (spaceObj.centerX + spaceObj.spaceWidth * n / 2  + wallOffset * n) / 100;
						pz = (Math.max(leftMaxValue, rightMaxValue) - cubeW / 2) / 100
						sz = cubeW / 10;
					}
			
			
			
			
				}else{
					let leftMinValue = 0;
					for (let index = 0; index < this.leftSpaces.length; index++) {
						const element = this.leftSpaces[index];
						if(direction=="S" || direction == "N"){
							leftMinValue += (element.centerX - element.spaceWidth / 2)
						}else{
							leftMinValue += (-element.centerY + element.spaceHeight / 2)
						}
					}
					// rightSpaces右边最大值
					let rightMinValue = 0;
					for (let index = 0; index < this.rightSpaces.length; index++) {
						const element = this.rightSpaces[index];
						if(direction=="S" || direction == "N"){
							rightMinValue += (element.centerX - element.spaceWidth / 2)
						}else{
							rightMinValue = (-element.centerY + element.spaceHeight / 2)
						}
						rightids.push(element.spaceId)
					}
			
			
					const index = this.gltfWalls.findIndex(item=>{
						// console.log("墙面模型", item)
						return spaceObj.spaceId == item.spaceId && item.wallDirection == direction;
					})
			
					if(index != -1 && leftMinValue < rightMinValue && (direction == "S" || direction == "N")){
						console.log("不需要补墙251")
						return
					}
			
					if(index != -1 && leftMinValue > rightMinValue && (direction == "E" || direction == "W")){
						console.log("不需要补墙252")
						return
					}
			
					let wallOffset = index != -1 ? -5 : 5;
			
					console.log("空间最大值", leftMinValue, rightMinValue);
					const cubeW = Math.abs(leftMinValue - rightMinValue);
			
					if(leftMinValue > rightMinValue && index == -1 && (direction == "S" || direction == "N")){
						console.log("不需要补墙241", leftMinValue, rightMinValue)
			
						const autoWall = this.gltfAutoWalls.find(item=>{
							return item.rightids.indexOf(spaceObj.spaceId) != -1 && item.wallDirection == (direction == "S" ? "N": "S");
						})
						if(autoWall){
							let cube = autoWall.obj;
							if(cube){
								cube.scale.set(0,0,0);
							}
						}
						return 
					}
					if(leftMinValue < rightMinValue && index == -1 && (direction == "E" || direction == "W")){
						console.log("不需要补墙242", leftMinValue, rightMinValue)
			
						const autoWall = this.gltfAutoWalls.find(item=>{
							return item.rightids.indexOf(spaceObj.spaceId) != -1 && item.wallDirection == (direction == "W" ? "E": "W");
						})
						if(autoWall){
							let cube = autoWall.obj;
							if(cube){
								cube.scale.set(0,0,0);
							}
						}
						return 
					}
					if(direction=="S" || direction == "N"){
						px = (Math.max(leftMinValue, rightMinValue) - cubeW / 2) / 100
						pz = (-spaceObj.centerY + spaceObj.spaceHeight * n / 2  + wallOffset * n) / 100;
						sx = cubeW / 10;
					}else{
						px = (spaceObj.centerX + spaceObj.spaceWidth * n / 2  + wallOffset * n) / 100;
						pz = (Math.max(leftMinValue, rightMinValue) - cubeW / 2) / 100
						sz = cubeW / 10;
					}
				}
			
				console.log("空间最大值", px, pz, sx, sz, this.gltfAutoWalls);
			
				// 寻找是否已添加过墙面
				const autoWall = this.gltfAutoWalls.find(item=>{
					return (item.spaceId == spaceObj.spaceId && item.wallDirection == direction)
					|| (item.rightids.findIndex(it=>{ return it == spaceObj.spaceId})!=-1 && item.wallDirection == direction == "S"?"N":"S")
					|| (item.rightids.findIndex(it=>{ return it == spaceObj.spaceId})!=-1 && item.wallDirection == direction == "E"?"W":"E")
				})
			
				if(this.curWallDirection == "S"){
					if(spaceObj.southId > 0){
						return 
					}
				}
				if(this.curWallDirection == "E"){
					if(spaceObj.eastId > 0){
						return 
					}
				}
				if(this.curWallDirection == "N"){
					if(spaceObj.northId > 0){
						return 
					}
				}
			
				if(this.curWallDirection == "W"){
					if(spaceObj.westId > 0){
						return 
					}
				}
			
				if(autoWall){
					console.log("修改补墙的信息", px, pz, sx, sz);
					let cube = autoWall.obj;
					cube.position.set(px,0,pz);
					cube.scale.set(sx,1,sz);
				}else{
					console.log("添加补墙的信息", px, pz, sx, sz);
			
					that.loader.load(wallType[0].url, ( gltf ) => {
					let cube = gltf.scene;
			
					cube.position.set(px,0,pz);
					cube.scale.set(sx,1,sz);
					that.scene.add(cube);
					let md = {
						obj:cube, 
						wallDirection:direction, 
						spaceId:spaceObj.spaceId,
						quadrant:spaceObj.quadrant,
						rightids:rightids
					};
					that.gltfAutoWalls.push(md);
					// console.log("模型加载成功", that.gltfAutoWalls, spaceObj.spaceId);
				});
				}
			},
			// 墙体缩放逻辑
			wallTransform(spaceObj, direction, moveOut, moveValue){
			    console.log(`移动的空间的id：${spaceObj.spaceId};移动方向：${direction};是否外移：${moveOut};移动距离：${moveValue}`)
			},
			updateWallModels(){
				let that = this;
				console.log("开始替换墙体模型", this.leftSpaces, this.rightSpaces, this.gltfWalls);
				let promise_list = [];

				// const gltfWalls = JSON.parse(JSON.stringify(this.gltfWalls))
				this.gltfWalls.forEach((item,index) => {
					promise_list.push(
						new Promise((resolve, reject) => {
							this.loadChangeWallModels(item, resolve);
						})
					)
				});

				Promise.all(promise_list).then(()=>{
					this.$nextTick(()=>{
						let newArr = [];
						const newWalls = that.gltfWalls.filter(it=>{
							return !it.isDidWall
						})
						that.gltfWalls = newWalls;
						console.log("加载完成2",newWalls, newArr, that.gltfWalls, that.wallList);
					})
				})
			},
			
        }
    }
</script>
<style lang="scss" scoped>
	@import "./webgl_rxdz_test.scss";
</style>