<template src="./webgl_rxdz_test1_env.html">
</template>

<script>
	const util = require('@/utils/util.js').default;
	const config = require('@/services/urlConfig.js');
	import router from "@/router";
	import {
		setStorage,
		getStorage,
		removeItem,
	} from '@/utils/localStorage';
	import {
		Toast
	} from 'mint-ui';
	import { MessageBox } from 'mint-ui';
	import touchHandle from '@/mixins/touchHandle.js';
	// import createImgHandle from '@/mixins/createImgHandle.js';
	import commonPageMethod from '@/mixins/commonPageMethod.js';
	export default {
		mixins: [touchHandle, commonPageMethod],
		/**
		 * 页面的初始数据
		 */
		data() {
			return {
				pvId: 'p_2cmina_21012501',
				locusBehaviorName: "环境偏好",
				locusValue: "",
				locusName: "",
				pvCurPageName: "role_set",
				pvCurPageParams: null,
				navbar: {
					showCapsule: 1,
					title: '环境偏好',
					titleColor: '#fff',
					navPadding: 0,
					navPaddingBg: 'transparent',
					navBarColor: 'transparent',
					navBackColor: 'transparent',
					haveCallback: false, // 如果是 true 会接手 navbarBackClk
					fromShare: false,
					fromProject: 0,
					shareToken: "",
					pageName: this.pvCurPageName,
				},
				houseId: $config.houseIdHs,

				id: '', //题目
				allSelect:false,//是否所有大类都选择了
				currentIndex: 0,
				// featureImgList: [],
				showPhoneModel: false,
				tabIndex: 0, //当前在第几个tab
				optionIndex: -1, //选项选中的序号
				options: [], //选项数据
				aiImagesList: [], //角色数据，单独
				AIImg:'',	//AI生成所需要的垫图
				tabData: [],
				checked:false,	//是否喜欢
				subDataList:[],	//提交的数据对象
				queryObj:null,
			}
		},
		/**
		 * 生命周期函数--监听页面加载
		 */
		mounted(options) {
			console.log("***onLoad-webgl_rxdz_customize***", this.$route.query)
			const that = this;
			this.houseId = this.$route.query.houseId ? this.$route.query.houseId : (this.$store.state.houseId || '');
			let queryObj = getStorage('queryObj') ? JSON.parse(getStorage('queryObj')) : null;
			this.id = this.$route.query.id3 ? this.$route.query.id3 : (queryObj && queryObj.id3?queryObj.id3:'111');
			this.queryObj = queryObj;
			this.queryTestcaseSingle();
		},
		computed: {
			userId() {
				return this.$store.state.userId;
			},
		},

		methods: {
			swiperChangeImg(e) {
				console.log("***swiperChangeImg***", e);
				this.currentIndex = e.detail ? e.detail.current : e;
				this.checked = this.aiImagesList[this.currentIndex].checked;
				// this.optionIndex = this.currentIndex;
				// this.tabData[0].checkedIndex = this.currentIndex;
			},
			rightScroll() { //右滑
				if (this.currentIndex <= (this.aiImagesList.length - 1) && this.currentIndex > 0) {
					this.$refs.carousel.prev();
					this.$forceUpdate()
				}
			},
			leftScroll() { //继续生成
				console.log("***leftScroll***", this.currentIndex,this.aiImagesList.length);
				if (this.currentIndex != this.aiImagesList.length - 1) {
					if (this.currentIndex < this.aiImagesList.length - 1) {
						this.$refs.carousel.next();
					}
					return false;
				}
				// console.log("***leftScroll***",this.currentIndex,this.aiImagesList.length)
				// let obj = {
				// 	imgUrl:this.AIImg,
				// 	prompt:this.options[this.optionIndex].remark,
				// 	negativePrompt:this.options[this.optionIndex].tips,
				// 	tabIndex:this.tabIndex,
				// 	optionIndex:this.optionIndex,
				// }
				// this.startServer(obj);//继续生成下一张
			},
			//点赞喜欢
			changeAIImg() {
				// let lastPage = getCurrentPages()[getCurrentPages().length - 2] ? getCurrentPages()[getCurrentPages().length - 2].$vm : null;
				this.checked = !this.checked;//变更选项
				this.aiImagesList[this.currentIndex].checked = this.checked;
				console.warn("***changeAIImg***",this.checked)
				let img = this.aiImagesList[this.currentIndex].imageUrl;
				let obj = this.options[this.optionIndex].hardboundEffect.find(it=>it.imageUrl==img);
				if(obj){
					obj.checked = this.checked;
				}
			},
			//查询题目数据
			async queryTestcaseSingle() {
				let userId = this.userId || '';
				let params = {
					id: this.id,
					brandId: $config.brandId,
					houseId: this.houseId,
					userId,
				};
				// params.userId = this.userId;
				const res = await requestConfig('queryTestcaseSingle', params);
				if (res.success) {
					let list = res.list;
					list.forEach(it => {
						it.checkedIndex = -1;////增加当前题目用户选择的需要，默认不选中
						it.options.forEach(option=>{
							if(option.imageUrls){
								option.hardboundEffect = option.imageUrls.map(it=>{
									return {
										imageUrl: it,
										checked: false,
										type:'system',//表示系统生成的
									}
								})
							}
							// option.hardboundEffect = [
							// 	{
							// 		imageUrl :option.imageUrl,
							// 		type:'system',//人为添加的
							// 	}
							// ];//AI生成图存放对象
						})
					});
					let envData = getStorage('envData') ? JSON.parse(getStorage('envData')) : null;
					this.tabData = list;
					this.tabData[0].checkedIndex = 0;
					this.optionIndex = 0;
					this.options = this.tabData[0].options; //选项数据
					this.AIImg = this.tabData[0].options[0].imageUrl;//AI生成所需的垫图
					this.aiImagesList = this.tabData[0].options[0].hardboundEffect;
					if(envData && envData.length>0){
						removeItem('envData');//用完后删除
					}else{
						this.submitAnswer()
					}
					
					//初始化待提交的数据对象
					// list.forEach(it=>{
					// 	let obj = {
					// 		fatherContent:it.fatherContent,
					// 		name:it.fatherContent,
					// 		houseId:it.houseId,
					// 		houseName:it.houseName,
					// 		id:it.id,
					// 		hardboundEffect:[]
					// 	}
					// 	this.subDataList.push(obj);
					// });
				}
			},
			//切换大类
			changeTab(id) {
				if (id == this.tabIndex) {
					return
				}
				this.tabIndex = id;
				this.options = this.tabData[this.tabIndex].options; //选项数据
				this.optionIndex = this.tabData[this.tabIndex].checkedIndex; //获取用户已经选中的选项
				if(this.optionIndex>-1){
					this.aiImagesList = this.options[this.optionIndex].hardboundEffect;
					this.checked = this.aiImagesList[this.currentIndex].checked;
				}
				// let param = {
				// 	type: 'CLK', //埋点类型
				// 	clkId: 'clk_2cmina_24012601', //点击ID
				// 	clkName: 'tab_clk', //点击前往的页面名称
				// 	clkParams: {
				// 		type: this.tabData[this.tabIndex].fatherContent,
				// 		locusName: "大类选择",
				// 	}
				// };
				// util.trackRequest(param);
			},
			//切换选项
			changeOption(id) {
				if (id == this.optionIndex) {
					return false;
				}
				this.optionIndex = id;
				this.tabData[this.tabIndex].checkedIndex = this.optionIndex;
				this.allSelect = !this.tabData.some(it=>it.checkedIndex==-1);
				this.AIImg = this.options[this.optionIndex].imageUrl;//AI生成图的垫图
				//替换对应的队列为选中的选项的数组对象
				this.aiImagesList = this.options[this.optionIndex].hardboundEffect;
				this.currentIndex = 0;
				this.$refs.carousel.setActiveItem(0); //切换到第一张
				this.checked = this.aiImagesList[this.currentIndex].checked;
				console.warn("***changeOption***", this.tabData,this.AIImg,this.subDataList)
				// let param = {
				// 	type: 'CLK', //埋点类型
				// 	clkId: 'clk_2cmina_24012602', //点击ID
				// 	clkName: 'option_clk', //点击前往的页面名称
				// 	clkParams: {
				// 		type: this.options[this.optionIndex].content,
				// 		locusName: "选项选择",
				// 	}
				// };
				// util.trackRequest(param);
				this.submitAnswer()
			},
			submitAnswer(){
				let userId = this.userId || '';
				let params = {
					"answerContent": [
						{
							"optionTitle": this.options[this.optionIndex].content,
							"questionTitle": this.tabData[this.tabIndex].subContent,//问题标题
							"subOptionId": this.options[this.optionIndex].id,
							"subQuestionId": this.tabData[this.tabIndex].id,
						}
					],
					brandId: $config.brandId,
					houseId: this.houseId,
					channel:this.queryObj ? this.queryObj.channel : '',
					city:this.queryObj ? this.queryObj.city : '',
					district:this.queryObj ? this.queryObj.district : '',
					province:this.queryObj ? this.queryObj.province : '',
					paperTitle:'',//试卷id
					testThemeId:'',
					testcaseId:this.id,
					uuid:userId,
					xcxCustomerId:userId,
				};
				requestConfig('submitAnswer', params,true);
				let param = {
					type: 'CLK', //埋点类型
					clkId: 'clk_2cmina_24022003', //点击ID
					clkName: 'option_clk', //点击前往的页面名称
					clkParams: {
						locusValue: this.options[this.optionIndex].content,
						locusName: "选项选择",
					}
				};
				util.trackRequest(param);
			},
			catchTouchMove: function() {
				return false;
			},
			//提交结果数据处理
			async resultDataHandle(){
                let otherlist = [];
                this.tabData.forEach(tab=>{
                	let list = tab.options[tab.checkedIndex].hardboundEffect.filter(it=>it.checked==true);//过滤选中的
                	list = list.map(it=>{
                		return it.imageUrl
                	})
                	let obj = tab.options[tab.checkedIndex];
                	let data = {
                		spaceName:tab.fatherName,
                		spaceId:'',
                		hardboundEffect:(list && list.length>0)?list:[obj.imageUrl],
                	}
                	otherlist.push(data);
                })
                setStorage('thirdData', otherlist);//把环境选择的数据存入本地缓存里面，方便后续使用
				let firstData = JSON.parse(getStorage('firstData'));
				let secondData = JSON.parse(getStorage('secondData'));
				let thirdData = JSON.parse(getStorage('thirdData'));
				let curHouseObj = JSON.parse(getStorage('curHouseObj'));
				let spaceList = JSON.parse(getStorage('spaceList'));
				let shottingImg = getStorage('shottingImg');
				let expand = [];//扩展数据
				let checkIndexList = [];
				let userId = this.userId ? this.userId : '';
				let houseData = {
					"layoutId": curHouseObj.id,
					"layoutName": curHouseObj.name,
					"layoutArea": curHouseObj.houseArea,
					"floor": 1,
					"layoutImgCustomized": shottingImg,
					"style": "",
					"houseJson": []
				}
				firstData.forEach(it=>{
					let _dt = {
						name:it.name,
						value:it.selectOptionImageUrl,
					}
					expand.push(_dt);
				})
				secondData.forEach(it=>{
					let _dt = {
						name:it.name,
						value:it.selectOptionName,
					}
					expand.push(_dt);
				})
                thirdData.forEach(it=>{
                	let _dt = {
                		name:it.fatherName,
                		value:it.options[it.checkedIndex].content,
                	}
                	expand.push(_dt);
                    checkIndexList.push(it.checkedIndex);
                })
				// this.tabData.forEach(tab=>{
				// 	let list = tab.options[tab.checkedIndex].hardboundEffect.filter(it=>it.checked==true);//过滤选中的
				// 	list = list.map(it=>{
				// 		return it.imageUrl
				// 	})
				// 	let obj = tab.options[tab.checkedIndex];
				// 	let data = {
				// 		spaceName:tab.fatherName,
				// 		spaceId:'',
				// 		hardboundEffect:(list && list.length>0)?list:[obj.imageUrl],
				// 	}
				// 	otherlist.push(data);
				// 	expand.push({
				// 		name:tab.fatherName,
				// 		value:obj.content,
				// 	});
				// 	checkIndexList.push(tab.checkedIndex);
				// })
				houseData.houseJson = spaceList.concat(otherlist);
				// houseData.expand = expand;
				let param = {
					"brandId": $config.brandId,
					"houseId": this.houseId || curHouseObj.houseId,
					"userId": userId,
					"floot": 1,
					"spaceName": curHouseObj.name,
					"spaceStructure": '',
					"curFloor":1,
					layoutStruct:[houseData],
					type:'QIANCE',
					expand:JSON.stringify(expand),
				}
				console.warn("submitHouse-param: ", param);
				setStorage('envData',checkIndexList);
				const loading = this.$loading({
					lock: true,
					text: '提交中...',
					spinner: 'el-icon-loading',
					background: 'rgba(0, 0, 0, 0.7)'
				});
				let res = await requestConfig("saveCustomizedRecord", param);
				loading.close();
				if(res && res.success && res.single){//提交成功
					let data = {
						houseId:this.houseId || curHouseObj.houseId,
						id:res.single,
					}
					router.push({
						name: "webgl_rxdz_text_customize",
						query:data
					});
				}
			},
			
            //进入下一步
            enterAction() {
            	let index = this.tabData.findIndex(it=>it.checkedIndex==-1);
            	if(index>-1){
            		Toast({
            			message: this.tabData[index].fatherContent + '选项不能为空',
            		});
            		return false;
            	}
                let otherlist = [];
            	this.tabData.forEach(tab=>{
            		let list = tab.options[tab.checkedIndex].hardboundEffect.filter(it=>it.checked==true);//过滤选中的
            		list = list.map(it=>{
            			return it.imageUrl
            		})
            		let obj = tab.options[tab.checkedIndex];
            		let data = {
            			spaceName:tab.fatherName,
            			spaceId:'',
            			selectOptionName:obj.content,
            			hardboundEffect:(list && list.length>0)?list:[obj.imageUrl],
            		}
            		otherlist.push(data);
            	})
            	setStorage('thirdData', otherlist);//把环境选择的数据存入本地缓存里面，方便后续使用
            	let data = {
            		houseId:this.houseId || 100297,
            	}
            	router.push({
            		name: "webgl_rxdz_test_houseList",
            		query:data
            	});
            },
		}

	}
</script>
<style lang="scss" scoped>
	@import "./webgl_rxdz_test1_env.scss";
</style>