<template>
	<view class="flex-col justify-start relative page" :style="{ backgroundImage: 'url(' + bkgPubilcPath + ')'}">
	  <view class="flex-row justify-between items-center section_2 pos" @click="openPopup">
	    <view class="flex-row items-center">
	      <image
	        class="shrink-0 image"
	        :src="clothesRentUrl + '/clothesRentSubmitOrder/lxr.png'"
	      />
	      <text class="ml-10 font text">{{ contactInfo.name }} {{ contactInfo.phone }}</text>
	    </view>
	    <view class="flex-row">
	      <text class="font_2 text_2">更换联系人</text>
	      <image
	        class="ml-2 shrink-0 image_2"
	        :src="clothesRentUrl + '/clothesRentSubmitOrder/yjt.png'"
	      />
	    </view>
	  </view>
	  <view class="flex-col section_3 pos_2">
	    <view class="flex-row justify-between">
	      <view class="flex-row">
	        <image
	          class="image_3"
	          :src="publicPath + clothesInfo.image"
	        />
	        <view class="flex-col items-start group_2 ml-15">
	          <text class="font text_3">{{ clothesInfo.name }}</text>
	          <text class="mt-64 font_3">¥{{ clothesInfo.price.toFixed(2) }}</text>
	        </view>
	      </view>
	      <view class="flex-col items-center self-start group" @click="nav">
	        <image
	          class="image_4"
	          :src="clothesRentUrl + '/clothesRentSubmitOrder/nav.png'"
	        />
	        <text class="font_2 text_4 mt-11">提货地址</text>
	      </view>
	    </view>
	    <view class="flex-row justify-between items-baseline group_3">
	      <text class="font">租赁天数</text>
	      <text class="font_3 text_5">X{{ period }}</text>
	    </view>
	    <view class="flex-row justify-between items-baseline group_4">
	      <text class="font text_6">总计</text>
	      <text class="text_7">¥{{ totalAmount.toFixed(2) }}</text>
	    </view>
	  </view>
	  <view class="flex-row justify-between items-center section_4 pos_3">
	    <view class="flex-row items-baseline">
	      <text class="font_4 text_8">定金:</text>
	      <text class="font_4 text_9">¥{{ totalAmount.toFixed(2) }}</text>
	    </view>
	    <view class="flex-col justify-start items-center text-wrapper" @click="wxPayFd">
			<text class="font text_10">确定</text>
		</view>
	  </view>
	</view>
	
	<uni-popup ref="popup" background-color="#fff">
		<view class="popup-content">
			<contactsComponentVue></contactsComponentVue>
		</view>
	</uni-popup>
	
	<!-- 遮罩层 -->
	    <view v-if="isShow" class="overlay"></view>
	
</template>

<script setup>
	import {nextTick, onMounted, onUnmounted, ref} from 'vue'
	import { clothesRentUrl } from '../../../common/globalImagesUrl';
	import { onLoad } from "@dcloudio/uni-app";
	import { baseUrl } from '../../../api/request';
	import { publicPath,bkgPubilcPath } from '../../../common/globalImagesUrl';
	import emitter from '../../../utils/emitter';
	import { JudgeIsNullity, dealResult } from '../../../common/globalFunction';
	import contactsComponentVue from '../../order/component/contactsComponent.vue';
import { getFonts } from '../../../common/globalFont';
	const period = ref(0)
	let id = 0
	const clothesInfo = ref({})
	const contactInfo = ref({})
	const totalAmount = ref(0)
	const cookie = wx.getStorageSync('cookie')
	const popup = ref(null)
	
	//防抖相关变量
	let wxPayTimer = null;
	let loading = false;
	let isLoading = ref(false)
	let isShow = ref(false)
	
	
	const openPopup = () => {
		popup.value.open('bottom')
	}
	
	const closeHandler = () => {
		nextTick(() => {
			if (popup.value) {
				popup.value.close()
			}
		})
	}
	
	const contactsNowInfoHandler = (val) => {
		contactInfo.value = val
	}
	
	const delContactByIdHandler = (val) => {
		if (contactInfo.value.id === val) {
			contactInfo.value = {}
			contactInfo.value.name = '请选择联系人'
		}
	}
	
	const updateContactObjHandler = (val) => {
		if (contactInfo.value.id === val.id) {
			contactInfo.value = val
		}
	}
	
	
	onLoad((options) => {
		id = JSON.parse(options.id)
		period.value = JSON.parse(options.period)
		getFonts()
	})
	
	onMounted(() => {
		getClothesInfoById()
		getDefaultContact()
		
		emitter.on('close', closeHandler)
		
		emitter.on('contactsNowInfo', contactsNowInfoHandler)
		
		emitter.on('delContactById', delContactByIdHandler)
		
		emitter.on('updateContactObj', updateContactObjHandler)
	})
	
	onUnmounted(() => {
		
		emitter.off('close', closeHandler)
		
		emitter.off('contactsNowInfo', contactsNowInfoHandler)
		
		emitter.off('delContactById', delContactByIdHandler)
		
		emitter.off('updateContactObj', updateContactObjHandler)
	})
	
	const getClothesInfoById = async () => {
		const res = await uni.request({
			url: baseUrl + '/clothes/get/label/id',
			method: 'POST',
			header: {
				cookie
			},
			data: {
				id
			}
		})
		clothesInfo.value = res.data.data
		let singlePrice = clothesInfo.value.price
		totalAmount.value = singlePrice * period.value
	}
	
	
	const nav = () => {
		wx.openLocation({
			latitude: 45.867741,
			longitude: 126.560037,
			name: '哈尔滨师范大学(松北校区)',
			address: '黑龙江省哈尔滨市呼兰区利民经济开发区师大路1号',
			success: (res) => {
			console.log(res)
			}
		})
	}
	
	
	
	//获取用户默认联系人
	const getDefaultContact = async () =>{
		const res = await uni.request({
			url: baseUrl + '/contacts/list',
			method: 'POST',
			header: {
				cookie: wx.getStorageSync('cookie')
			}
		})
		if(res.data.code === 1) {
			console.log('联系人数组---->',res.data.data);
		}
		let contactArr = res.data.data
		for(let key in contactArr) {
			if(contactArr[key].isDefault === 1) {
				contactInfo.value = contactArr[key]
			}
		}
		if (JudgeIsNullity(contactInfo.value.name)) {
			contactInfo.value.name = '请选择联系人'
		}
	}
	
	
	const wxPayFd = () => {  //微信支付按钮防抖
		if (JudgeIsNullity(contactInfo.value.phone) || JudgeIsNullity(contactInfo.value.id)) {
			uni.showToast({
				title: '请选择联系人',
				icon: 'error'
			})
			return ;
		}
		clearTimeout(wxPayTimer)
		showLoading()
		isShow.value = true
		wxPayTimer = setTimeout(async () => {
			await createOrder()
		}, 1000)
	}
	function showLoading() {  //加载弹窗
	  if (!loading) {
	    wx.showLoading({
	      title: '加载中...',
	    });
	    loading = true;
		isLoading.value = true
	  }
	}
	function hideLoading() {  //关闭弹窗
	  if (loading) {
	    wx.hideLoading();
	    loading = false;
		isLoading.value = false
	  }
	}
	
	
	
	const createOrder = async () => {  
		const res = await uni.request({   
			url: baseUrl + '/clothesRent/add',
			method: 'POST',
			header: {
				cookie: wx.getStorageSync('cookie')
			},
			data: {
				clothesId: id,
				contactsId: contactInfo.value.id,
				rentDays: period.value
			}
		})
		if (!dealResult(res)) {
			hideLoading()
			isShow.value = false
			return 
		} 
		wxPay(res.data.data)
	}
	
	
	const wxPay = async ( oid )=> {  //传入订单id
		try {
			const res = await uni.request({
				url: baseUrl + '/wechat/payment/clothesRent/create',
				method: 'POST',
				header: {
					'cookie': wx.getStorageSync("cookie")
				},
				data: { id: oid }
			})
			const paymentData = res.data.data
			wx.requestPayment({
				appid: paymentData.appId,
				nonceStr: paymentData.nonceStr,
				package: paymentData.packageVal,
				paySign: paymentData.paySign,
				timeStamp: paymentData.timeStamp,
				signType: paymentData.signType,
				success(res) {
					uni.showModal({
						content: '支付成功',
						showCancel: false
					})
					console.log('支付成功res--->',res);
				},
				fail(e) {
					uni.showModal({
						content: '支付失败,原因为:' + e.errMsg,
						showCancel: false
					})
					console.log('e.errMsg--->',e.errMsg);
				},
				complete() {
					uni.redirectTo({
						url: '/pages/clothesRent/clotherRentOrderList/clotherRentOrderList'
					})
				}
			})
			
		}catch(error) {
			console.error('支付请求失败',error);
			uni.showModal({
				content: '支付请求失败,请重试',
				showCancel: false
			})
		}
	}
	
	
	
</script>

<style scoped lang="scss">
.overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.4);  /* 半透明黑色背景 */
  z-index: 999;
}
.popup-content {
	height: 800rpx;
}
.ml-15 {
  margin-left: 28.13rpx;
}
.mt-11 {
  margin-top: 20.63rpx;
}
.page {
  background-color: #ffffff;
  background-size: 100% 100%;
  background-repeat: no-repeat;
  width: 100%;
  overflow-y: auto;
  overflow-x: hidden;
  height: 100vh;
}
.section_2 {
  padding: 30rpx 15rpx 30rpx 24.38rpx;
  background-color: #ffffff;
  border-radius: 18.75rpx;
}
.pos {
  position: absolute;
  left: 22.5rpx;
  right: 24.38rpx;
  top: 37.5rpx;
}
.image {
  width: 50.63rpx;
  height: 50.63rpx;
}
.font {
  font-size: 30rpx;
  font-family: FangZhengFonts;
  line-height: 28.84rpx;
  color: #323232;
}
.text {
  color: #818181;
  line-height: 25.89rpx;
}
.font_2 {
  font-size: 26.25rpx;
  font-family: FangZhengFonts;
  line-height: 25.54rpx;
}
.text_2 {
  margin: 3.75rpx 0;
  color: #e79ea1;
}
.image_2 {
  width: 30rpx;
  height: 30rpx;
}
.section_3 {
  padding: 25.75rpx 18.75rpx;
  background-color: #ffffff;
  border-radius: 18.75rpx;
}
.pos_2 {
  position: absolute;
  left: 22.5rpx;
  right: 24.38rpx;
  top: 168.75rpx;
}
.image_3 {
  border-radius: 9.38rpx;
  width: 161.25rpx;
  height: 176.25rpx;
}
.group_2 {
  margin-top: 3.75rpx;
}
.text_3 {
  line-height: 29.18rpx;
}
.font_3 {
  font-size: 30rpx;
  font-family: FangZhengFonts;
  line-height: 20.04rpx;
  color: #323232;
}
.group {
  // margin-right: 22.5rpx;
}
.image_4 {
  width: 46.88rpx;
  height: 46.88rpx;
}
.text_4 {
  color: #323232;
  line-height: 25.22rpx;
}
.group_3 {
  margin-top: 37.5rpx;
}
.text_5 {
  margin-right: 18.75rpx;
}
.group_4 {
  margin-top: 22.5rpx;
}
.text_6 {
  line-height: 28.13rpx;
}
.text_7 {
  color: #c35c5d;
  font-size: 33.75rpx;
  font-family: FangZhengFonts;
  line-height: 22.54rpx;
}
.section_4 {
  padding: 26.25rpx;
  background-color: #ffffff;
}
.pos_3 {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
}
.font_4 {
  font-size: 37.5rpx;
  font-family: FangZhengFonts;
}
.text_8 {
  color: #323232;
  line-height: 34.42rpx;
}
.text_9 {
  margin-left: -7.5rpx;
  color: #c35c5d;
  line-height: 25.05rpx;
}
.text-wrapper {
  margin-right: 3.75rpx;
  padding: 22.5rpx 0;
  background-color: #e79ea1;
  border-radius: 187.5rpx;
  width: 241.88rpx;
  height: 76.88rpx;
}
.text_10 {
  color: #ffffff;
  line-height: 28.01rpx;
}
@import url(../../../common/css/global.css);
</style>