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

<script>
    const util = require('@/utils/util.js').default;
	const config = require('@/services/urlConfig.js');
	import {
		Toast
	} from 'mint-ui';
	import router from "@/router";
	import touchHandle from '@/mixins/touchHandle.js';
	import commonPageMethod from '@/mixins/commonPageMethod.js';
	import spaceTypes from '@/static/spaceTypesIE.js';
// const app = getApp(); //获取应用实例
// import requestConfig from '@/static/lib/requestConfig.js';
// import commonPageMethod from '@/common/commonPageMethod.js';
// import commonMethod from '@/common/commonMethod.js';
export default {
    mixins: [touchHandle,commonPageMethod],
    /**
     * 页面的初始数据
     */
    data() {
        return {
            pvId: 'p_2cmina_23080403',
            locusBehaviorName: "我的定制",
            locusValue: "",
            locusName: "",
            pvCurPageName: "submit_ret",
            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,

            shareUserId: null, // 分享者ID
            id: '',//方案库id

            currImgIdx:0,
            tabIndex: 0,
            // featureImgList: [],
            hardboundEffect: [],//当前swiper数据列表对象
            form: {},
			tabData:[],
            number: '',
			plotHeadDeafultImg: 'https://dm.static.elab-plus.com/mini-program/plotHeadDeafultImg.png', // 地块人物默认头像
			showPhoneModel:false,
			gsImage:'',
			layoutStruct:null,
			expand:null,
			likeCount:0,//喜欢的人数
			unlikedCount:0,//不喜欢人数
			total:0,//总人数
			typeStatus:0,//显示是否喜欢的视图 ，1 显示 0 不显示
			proportion:50,	//显式比例
			headList:[],
			showUserInput:false,	//是否显示手机号留电弹窗
			repeatFlag:false,	//防止重复请求
			name:'',	//用户称呼
			tel:'',	//手机号
			verifyCode:'',//验证码
			verifyText:'',	//验证码提示
			isSend:false,
			showPopup:false,
			isIOS:false,
		}
    },
    /**
     * 生命周期函数--监听页面加载
     */
    mounted(options) {
        console.log("***onLoad-webgl_rxdz_text_customize***", this.$route.query)
        const that = this;
        this.houseId = this.$route.query.houseId?this.$route.query.houseId:'';
        this.id = this.$route.query.id?this.$route.query.id:'';
		this.typeStatus = this.$route.query.typeStatus?this.$route.query.typeStatus:0;
		let isIOS = !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
		this.isIOS = isIOS;
		if(!this.id){
			Toast({
				message: '没有数据！',
			});
			return false;
		}else{
			this.getIdData();
			setTimeout(()=>{
				this.likeOrView()
			},500)
		}
    },
	computed: {
		userId() {
			return this.$store.state.userId;
		},
	},

    methods: {
		showPop() {
			this.showUserInput = true;
		},
		hidePop() {
			this.showUserInput = false;
		},
		getVerifyCode: function () { //验证码
		    if (this.isSend) {
		        return
		    }
		    this.isSend = true;
		    if (!/^1\d{10}$/.test(this.tel)) {
		        Toast({
		        	message: '输入的手机号不合法',
		        });
		        this.isSend = false
		        return;
		    }
		    this.querySendCode(); //发送验证码接口
		},
		// 发送验证码接口
		async querySendCode() {
		    let time = 60;
		    let time1 = setInterval(() => {
		        if (time > 0) {
		            time = time - 1;
		            this.verifyText = time + 's'
		        } else {
		            this.isSend = false;
		            this.verifyText = '重新发送';
		            clearInterval(time1)
		        }
		    }, 1000)
		    const res = await requestConfig('send', {
		        phoneNumber: this.tel,
				"sign": "Elab未来人居",
				"verifyType": 1,
		        houseId: this.houseId || ''
		    });
		    if (res && res.success) {
		
		    } else {
		        this.isSend = false;
				Toast({
					message: '系统提示:网络错误',
				});
		    }
		},
		async sendPhone() {
		    console.log("sendPhone", this.verifyCode)
		    if (!/^1\d{10}$/.test(this.tel)) {
				Toast({
					message: '输入的手机号不合法',
				});
		        return;
		    }
			if (!this.verifyCode) {
				Toast({
					message: '没有验证码',
				});
			    return;
			}
			let codeData = {
				mobile: this.tel,
				code: this.verifyCode,
				verifyType: 1,
				
				// mobile: this.tel,
				// type: 'verification.code',
				// verifycode: this.verifyCode
				
				// mobile: this.tel,
				// leavePhoneCustomerId:this.userId || '',
				// code: this.verifyCode,
				// houseId:this.houseId,
				// source:2,
				// fromPlatform:'前测',
				// terminal:'7',
			};
		    const validateCodeRes = await requestConfig('validate', codeData);
		    if (validateCodeRes && !validateCodeRes.success) { //成功
				Toast({
					message: '验证码输入错误',
				});
		        return
		    } else {
		        this.fakeLeavePhone()
		    }
			this.isSend = false;
		},
		async fakeLeavePhone(){
			let signParam = {
			    brandCustomerId: this.userId || '',
			    brandId: $config.brandId,
			    mobile: this.tel || '',
			    houseId: this.houseId || '',
				source: 2,
				type: 2,
				terminal: 7
			};
			// 获取登录用户的shareToken
			const signres = await requestConfig('leavephone', signParam, true);
			if (signres && signres.success) {
				// let shareToken = signres.single;
				// console.log('刷新分享秘钥，当前为：', shareToken)
				// let parm = {
				// 	houseId: this.houseId || '',
				// 	scene:  "",
				// 	brandCustomerId: this.userId || '',
				// 	brandId: $config.brandId,
				// 	mobile: this.tel || '',
				// 	shareSign: shareToken,
				// 	gdt_vid: "",
				// 	url: window.location.href,
				// };
				// let result = await requestConfig('authorizedMobile', parm, true);
				// if(result && result.success){
				// 	Toast({
				// 		message: '留电成功',
				// 	});
				// }
				Toast({
					message: '留电成功',
				});
				this.showUserInput = false;
			}
			
		},
		blurInput(e) {
		    this.tel = e.detail.value || ''
		},
		blurCode(e) {
		    this.verifyCode = e.detail.value || ''
		},
		swiperChangeImg(e){
            console.log("***swiperChangeImg***",e);
			this.currImgIdx = e.detail ? e.detail.current : e;
			this.gsImage =  this.hardboundEffect[this.currImgIdx];//获取高斯模糊的图片
        },
		rightScroll(){//右滑
			if(this.currImgIdx <= (this.hardboundEffect.length - 1) && this.currImgIdx > 0){
				this.$refs.carousel.prev();
			}
		},
		leftScroll(){//继续生成
			if(this.currImgIdx != this.hardboundEffect.length - 1){
				if(this.currImgIdx<this.hardboundEffect.length - 1){
					this.$refs.carousel.next();
				}
			}
		},
		//去往首页
		toIndex(){
			if(window.__wxjs_environment === 'miniprogram'){
				this.pvCloseHandle();//小程序跳转会主动杀死关闭当前页面-不经过页面框架跳转关闭逻辑-所以需要主动触发关闭埋点
				wx.miniProgram.redirectTo({url: '/pages/index/index?houseId='+this.houseId})
			}else{
				let url = $config.min_uri + "pages/index/index?houseId=" + this.houseId
				// window.location.href = shottingImg;
				window.open(url)
			}
		},
		//联系我们
        conectUS(){
			if(window.__wxjs_environment === 'miniprogram'){
				this.pvCloseHandle();//小程序跳转会主动杀死关闭当前页面-不经过vue跳转关闭逻辑-所以需要主动触发关闭埋点
				wx.miniProgram.navigateTo({url: '/pages/transfer/transfer?event=openCustomerServiceChat&houseId='+this.houseId})
			}else{
				// this.$message.warning("敬请期待");
				this.showPop();
			}
		},
		async share(){
			if(window.__wxjs_environment === 'miniprogram'){
				// Toast({
				// 	message: '请点击右上角发起分享',
				// });
				this.showPopup = true;
				// wx.miniProgram.navigateTo({url: '/pages/transfer/transfer?event=openCustomerServiceChat&houseId='+this.houseId})
			}else{
				// window.location.href = shottingImg;
				let ind =  window.location.href.indexOf('?');
				let webUrl = window.location.href.substr(0,ind) + "?houseId=" + this.houseId +"&id=" + this.id + "&typeStatus=1"+ "&brandId=" + $config.brandId;
				let url = '';
				if (window.self !== window.top) {
					url = $config.min_uri + "pages/webView/webView?view=" + encodeURIComponent(webUrl) + "&title=梦想设计";
				} else {
					url = webUrl;
				}
				console.warn("***复制***",url);
				if(this.isIOS){
					navigator.clipboard.writeText(url);
					// const permission = await navigator.permissions.query({ name: 'clipboard-write' });
					// if (permission.state === 'denied') {
					// 	return console.error("Damn, we don't have permissions to do this")
					// }
					// try{
					// 	await navigator.clipboard.writeText(url) // 写入文本
					// }catch(e){
					// 	console.error("Error while copying text!",e)
					// }
				}else{
					var textArea = document.createElement("textarea");
					textArea.value = url;
					document.body.appendChild(textArea);
					textArea.select();
					document.execCommand('copy');
					document.body.removeChild(textArea);
				}
				Toast({
					message: '链接已复制',
				});
			}
		},
		async likeOrView(type){
			let userId = this.userId || '';
			let params = {
				busId: this.id,
				brandId: $config.brandId,
				houseId:this.houseId,
				userId,
				type:1,
			};
			if(type==1){//喜欢
				params.likeed = 1
			}else if(type==2){//不喜欢
				params.likeed = 0
			}
			if(this.repeatFlag){
				return false
			}
			this.repeatFlag = true;
			// params.userId = this.userId;
			const res = await requestConfig('add', params);
			if (res.success && type) {
				this.layoutStruct.clickLike = params.likeed;
				if(this.total){
					if(type==1){
						this.likeCount = this.likeCount + 1
					}else{
						this.unlikedCount = this.unlikedCount + 1
					}
					// if(userId != this.layoutStruct.userId){
					// 	this.total ++;
					// }
					this.proportion = parseInt((this.likeCount / (this.likeCount + this.unlikedCount))*100);
				}
			}
			// this.getIdData();
			this.repeatFlag = false;
		},
		async getIdData(){
			let userId = this.userId || '';
			let params = {
				id: this.id,
				brandId: $config.brandId,
				houseId:this.houseId,
				userId,
				type:'QIANCE',
			};
			if(this.shareUserId){//分享时 不带用户id
				delete params.userId
			}
			// params.userId = this.userId;
			const res = await requestConfig('getCustomizedRecord', params);
            if (res.success && res.list && res.list[0]) {
                let single = res.list[0];
				this.tabIndex = 0;//表明是户型首图
				this.tabData = [];
				if(single.expand){
					let list = JSON.parse(single.expand);
					let ind = list.findIndex(it=>it.name == '户型偏好');
					this.expand = list.slice(ind);
				}
				this.layoutStruct = JSON.parse(JSON.stringify(single));
				
				this.likeCount = this.layoutStruct.liked;//喜欢的人数
				this.unlikedCount = this.layoutStruct.unliked;//不喜欢人数
				this.total = this.layoutStruct.total;//总人数
				if((this.likeCount + this.unlikedCount)>0){
					this.proportion = parseInt((this.likeCount / (this.likeCount + this.unlikedCount))*100);
				}
                // this.number = single.landCode
                this.form = single.layoutStruct[0];
				this.headList = this.layoutStruct.heads || [];
                this.hardboundEffect = this.form.layoutImgCustomized? [this.form.layoutImgCustomized] : [];//赋值轮播图
				let data = {
					name : this.form.layoutName,
					imgUrl : this.form.layoutImgCustomized,
					hardboundEffect:[this.form.layoutImgCustomized],
					gsImage:this.form.layoutImgCustomized,
					area:this.form.layoutArea,
				}
                this.tabData.push(data);
				this.form.houseJson = this.form.houseJson.filter((item)=>{
					return item.spaceName && item.spaceName.length>0 && item.spaceType!=11 && item.hardboundEffect && item.hardboundEffect[0]
				})
				this.form.houseJson.sort(function(a,b){return parseFloat((b.spaceWidth * b.spaceHeight) / 10000) -parseFloat((a.spaceWidth * a.spaceHeight) / 10000)});
				this.form.houseJson.forEach((item,index)=>{
					//获取面积
					let curSpaceArea = parseFloat((item.spaceWidth * item.spaceHeight) / 10000).toFixed(1);
					let text = item.spaceName;
					if(item.spaceId && item.spaceType){
						text = spaceTypes[item.spaceType - 1];
						if(item.spaceType==15 && item.layoutSpaceType){
							text = spaceTypes[item.layoutSpaceType - 1]; 
						}
					}
					let data = {
						name : text,
						imgUrl : item.hardboundEffect[0],
						hardboundEffect:item.hardboundEffect,
						gsImage:item.hardboundEffect[0],
						area:item.spaceId?curSpaceArea:'',
					}
					this.tabData.push(data);
				})
				this.gsImage = this.form.layoutImgCustomized;//获取高斯模糊的图片
            }else{
				Toast({
					message: '作品未找到！',
				});
			}
        },
        changeTab(id){
            if(id == this.tabIndex){
                return
            }
            this.tabIndex = id;
            this.currImgIdx = 0;
			this.hardboundEffect = this.tabData[id].hardboundEffect? this.tabData[id].hardboundEffect : [];//赋值轮播图
			this.gsImage = this.tabData[id].gsImage;//获取高斯模糊的图片
            let param = {
                type: 'CLK', //埋点类型
                clkId: 'clk_2cmina_23080421', //点击ID
                clkName: 'roomretpic_clk', //点击前往的页面名称
                clkParams: {
                    type: this.tabData[this.tabIndex].name,
                    locusName: "房间名称",
                }
            };
            util.trackRequest(param);
        },
        
        catchTouchMove: function() {
            return false;
        },
        
        toMode(){
			let data = {
				houseId:this.houseId,
				id:this.id,
			}
			router.push({
				name: "webgl_rxdz_look",
				query:data
			});
			let param = {
				type: 'CLK', //埋点类型
				clkId: 'clk_2cmina_23080420', //点击ID
				clkName: 'checkroom_clk', //点击前往的页面名称
				clkParams: {
					locusName: "查看户型",
				}
			};
			util.trackRequest(param);
		},
    }
    
}
</script>
<style lang="scss" scoped>
	@import "./webgl_rxdz_text_customize.scss";
</style>
<style lang="css" scoped>
	/* @import "@/common/css/common.css"; */
</style>