<template>
	<view class="container">
		<view class="box">
			<view class="tit">请填写预约信息</view>
			<view class="row none" v-if="isreal == 1">
				<view class="row_tit">
					<image src="https://wechat-img-file.oss-cn-beijing.aliyuncs.com/doorToDoor/reser_icon1.png" mode="" />
					请选择上门时间
				</view>

				<view class="row_con" @click="changeShow">
					{{time}}
					<image src="https://wechat-img-file.oss-cn-beijing.aliyuncs.com/water_filter/filter_more.png" mode="" />
				</view>
			</view>
			<view class="row none" v-if="isreal == 2">
				<view class="row_tit">
					<image src="https://wechat-img-file.oss-cn-beijing.aliyuncs.com/doorToDoor/reser_icon2.png" mode="" />
					请选择服务时间
				</view>
				<view class="row_con" @click="changeShow2">
					{{serTime}}
					<image src="https://wechat-img-file.oss-cn-beijing.aliyuncs.com/water_filter/filter_more.png" mode="" />
				</view>
			</view>
			<view class="gray"></view>
			<view class="row">
				<view class="row_tit">
					<image src="https://wechat-img-file.oss-cn-beijing.aliyuncs.com/doorToDoor/reser_icon3.png" mode="" />
					联系人姓名
				</view>

				<view class="row_con">
					<input
						type="text"
						placeholder="请填写联系人姓名"
						placeholder-style="font-size: 26rpx;color: #999999;"
						:value="name"
						data-name='name'
						@input="headerInputClick"
					/>
				</view>

			</view>
			<view class="row">
				<view class="row_tit">
					<image src="https://wechat-img-file.oss-cn-beijing.aliyuncs.com/doorToDoor/reser_icon4.png" mode="" />
					联系人电话
				</view>

				<view class="row_con">
					<input
						type="number"
						maxlength="11"
						placeholder="请填写联系人电话"
						placeholder-style="font-size: 26rpx;color: #999999;"
						:value="phone"
						data-name='phone'
						@input="headerInputClick"
					/>
				</view>
			</view>
			<view class="row">
				<view class="row_tit">
					<image src="https://wechat-img-file.oss-cn-beijing.aliyuncs.com/doorToDoor/reser_icon5.png" mode="" />
					请选择服务地址
				</view>
				<view class="row_con" @click="changeArea">

					{{citys}}
					<image src="https://wechat-img-file.oss-cn-beijing.aliyuncs.com/water_filter/filter_more.png" mode="" />
				</view>
			</view>
			<view class="row none">
				<view class="row_tit">
					<image src="https://wechat-img-file.oss-cn-beijing.aliyuncs.com/doorToDoor/reser_icon5.png" mode="" />
					详细地址
				</view>

				<view class="row_con">
					<input
						type="text"
						placeholder="请填写详细地址"
						placeholder-style="font-size: 26rpx;color: #999999;"
						:value="add"
						data-name='add'
						@input="headerInputClick"
					/>
				</view>
			</view>
			<view class="gray"></view>
			<view class="doorToDoor">
				<view class="doorToDoor_tit">是否上门服务</view>
				<view class="selectItem" @click="changeCir(1)">
					<view :class="['cir', isreal == 1 ? 'active' : '']"></view>
					是
				</view>
				<view class="selectItem" @click="changeCir(2)">
					<view :class="['cir', isreal == 2 ? 'active' : '']"></view>
					否
				</view>
			</view>
			<view class="gray"></view>
			<view class="row none">
				<view class="row_tit2">
					<image src="https://wechat-img-file.oss-cn-beijing.aliyuncs.com/doorToDoor/reser_icon6.png" mode="" />
					<input
						type="text"
						placeholder="给商家捎句话"
						placeholder-style="font-size: 26rpx;color: #999999;"
						:value="msg"
						data-name='msg'
						@input="headerInputClick"
					/>
				</view>
			</view>
			<view class="gray"></view>

			<view class="agree">
				<view :class="['cir', agree ? 'active' : '']" @click="changeAgree"></view>

				<view @click="changeShow3">
					我已阅读并同意服务合同中的内容
				</view>
			</view>

			<view class="btn" @click="submit">提交申请 </view>
		</view>

		<u-datetime-picker
			:show="show"
			mode="datetime"
			:closeOnClickOverlay="true"
			:minDate="minDate"
			:formatter="formatter"
			@confirm="onInput"
			@cancel="onClose"
			@close="onClose"
		/>
		
		
		<areaPopup :show="show2"  @selectArea='headerAreaClick' @close='onClose' />



		<u-popup :show="show3" mode="center" @close="onClose" round="20rpx" closeOnClickOverlay>
		<view class="pop_body">
			<view class="popBox">
				<view class="tit2">服务声明</view>
				乙方指定的家政服务人员须遵守以下行为准则：
				1）遵守国家各项法律、法规和社会公德；执行《公民道德建设实施纲要》，自尊自强，爱岗敬业；遵守企业各项规章制度，维护经营者和甲方的合法权益。
				2）遵守职业道德，尊重甲方生活习俗，主动适应甲方，视甲方如亲人，不虐待所照看的老、幼、病、残人员；不泄露甲方隐私；不参与甲方家庭及邻里的矛盾纠纷，不传闲话，以免激化矛盾；不向甲方借钱或索要财物；在离开甲方家庭时，要主动打开自己的包裹让其检查，以示尊重。
				3）遵守合同条款，不无故违约，不无故要求换户或不辞而别。如与甲方发生矛盾，出现甲方侵犯家政服务人员合法权益，或变更服务地址、服务工种等，无论何种原因家政服务人员均应先行告知经营者，不要擅自处理。
				4）努力学习服务技能，完成经营者和甲方安排的工作任务。对不会使用的器具，未经经营者指导和甲方允许不要使用。未经甲方同意不使用其通讯工具和电脑等设备。
				5）保证自身和甲方的安全。不要与异性成、青年人同居一室；不带亲朋好友在甲方家中停留或食宿；不擅自外出或夜不归宿，如有特殊情况不能按时返回，要征得甲方同意；要注意防火、防盗。
				　第九条 服务人员仪态仪表 　　乙方指定的家政服务人员须遵守以下仪态仪表要求： 　　（1）讲究个人卫生，着装整洁大方，不能过于随意，不穿紧身衣裤或过于暴露的服装。 　　（2）佩戴饰物要适当，不浓妆艳抹，不留长指甲和涂指甲油。
				3）言谈举止大方得体，与甲方交流时要正视对方，不要左顾右盼，不能双臂交叉或双手插在兜里。
			</view>
		<view class="know" @click="onClose">我已知晓</view>
		</view>
	</u-popup>
	
	</view>
</template>

<script>
	import {
		apiArr
	} from '../../../api/communityService';
	import { apiPay } from '../../../api/pay';
	import {
		request,
		isPhone
	} from '../../../utils';


	export default {
		data() {
			return {
				time: "", //上门时间
				serTime: "", //服务时间
				name: "", //姓名
				phone: "", //电话
				citys: "", //服务地址
				add: "", //详细地址
				isreal: 1, //是否上门

				msg: "", //信息
				id: "",
				agree: false, //是否阅读同意
				type: "1", //1上门时间 2服务时间
				info: "",

				GoodsMsg: "", //商户信息
				orderMsg: "",

				show: false,
				show2: false,
				show3: false,
				minDate: new Date().getTime(),
				formatter(type, value) {
					if (type === 'year') {
						return `${value}年`;
					}
					if (type === 'month') {
						return `${value}月`;
					}
					if (type === 'day') {
						return `${value}日`;
					}
					return value;
				},
			}
		},
		methods: {
			async init(id) {
				const res = await request(apiArr.serverInfo, 'POST', {
					appoint_id: Number(id)
				});
				this.info = res;
				uni.setNavigationBarTitle({
					title: res.title
				})

			},

			changeShow() {
				this.show = !this.show;
				this.type = 1;
			},
			
			//
			changeShow2() {
				this.show = !this.show;
				this.type = 2;
			},
			
			// 关闭弹窗选择器
			onClose(){
				this.show = false;
				this.show2 = false;
				this.show3 = false;
			},
			
			// 时间选择器点击确定
			onInput(event){
				const date = new Date(event.value); // 获取选中的 Date 对象
				const year = date.getFullYear(); // 获取年份
				const month = date.getMonth() + 1; // 获取月份（注意月份从 0 开始，需要 +1）
				const day = date.getDate(); // 获取日期
				const hours =date.getHours()
				const minutes = date.getMinutes(); 
				const time = `${year}-${month}-${day} ${hours}:${minutes}`;
				console.log('time', time, 'type', this.type);
				this.show = false;
				if(this.type == 1){
					this.time = time;
				}else{
					this.serTime = time;
				}
			},
			
			// input 输入框输入值、
			headerInputClick(e) {
				console.log('eeee', e)
				const { name } = e.currentTarget.dataset;
				const { value } = e.detail;
				this[name] = value;
			},
			
			// 地址选择弹窗
			changeArea(){
				this.show2 = true;
			},
			
			headerAreaClick(data) {
				console.log('接受参数值', data);
				this.citys = `${data.confirmProv.name}${data.confirmCity.area_name}${data.confirmDist.business_name}`;
				this.show2 = false;
			},
			
			changeCir(e){
				this.isreal = e
			},
			
			// 打开服务合同弹窗
			changeShow3(){
				this.show3 = true
			},
			
			// 同意服务合同
			changeAgree(){
				this.agree = !this.agree;
			},
			
			
			async submit() {
				console.log('他啥都', this);
				if(this.isreal == '1'){
					if(!this.time){
						uni.showToast({
							title: '请选择上门时间',
							icon:"none"
						})
						return
					}
				}else{
					if(!this.serTime){
						uni.showToast({
							title: '请选择服务时间',
							icon:"none"
						})
						return
					}
				}
				if(!this.name){
					uni.showToast({
						title: '请填写联系人姓名',
						icon:"none"
					})
					return
				}
				if(!this.phone){
					uni.showToast({
						title: '请填写联系人电话',
						icon:"none"
					})
					return
				}
				if(!isPhone(this.phone)){
					uni.showToast({
						title: '请填写正确电话',
						icon:"none"
					})
					return
				}
				if(!this.citys){
					uni.showToast({
						title: '请选择服务地址',
						icon:"none"
					})
					return
				}
				if(!this.add){
					uni.showToast({
						title: '请填写详细地址',
						icon:"none"
					})
					return
				}
				if(!this.agree){
					uni.showToast({
						title: '请阅读合同内容',
						icon:"none"
					})
					return
				}
				let svctime
				if(this.isreal == '1'){
					svctime = this.time
				}else{
					svctime = this.serTime
				}
				uni.showLoading({
					title: '申请中...',
					mask:true
				})
				const res = await request(apiArr.createServerOrder, 'POST', {
					addr: this.citys + this.add,
					appoint_id: this.info.appoint_id,
					capon_id: 0,
					cate_id: this.info.cate_id,
					name: this.name,
					order_type: this.type,
					shop_id: this.info.shop_id,
					svctime,
					tel: this.phone
				}, { silent: false });
				this.orderMsg = res;
				this.getGoodsMsg(res)
			},
			
			//获取商户id
			async getGoodsMsg(val){
				try {
					console.log('123131', val);
					const res = await request(apiArr.getCurrentShopMsg, 'POST', {
						shop_id :Number(val.shop_id ),
					}, { silent: false })
					this.GoodsMsg = res;
					this.pay();
				} catch (error) {
					uni.hideLoading();
					console.log('获取商户接口异常，', error)
				}
			},
			
			async pay(){
				try {
					const res = await request(apiPay.pay, 'POST', {
						address: this.citys + this.add,
						goods_id: String(this.orderMsg.order_id),
						merchant_no: this.GoodsMsg.merchant_no,
						out_trade_no: this.orderMsg.order_sn,
						quantity: 1,
						remark: this.msg,
						subject: this.info.title,
						term_no: this.GoodsMsg.term_no,
						total_amount: String(this.info.price * 100),
						// total_amount:String(1),
						user: String(uni.getStorageSync('userId')),
						user_id: uni.getStorageSync('openId')
					}, { silent: false })
					
					const {resp_data,msg} = res.data
					uni.hideLoading()
					console.log(res,'res');
					if(msg == '成功'){
						const provider = await getProviderPromise('payment');
						console.log('获取当前支付渠道', provider);
						uni.requestPayment({
							provider: provider[0],
							timeStamp: String(resp_data.acc_resp_fields.time_stamp),
							nonceStr: String(resp_data.acc_resp_fields.nonce_str),
							package: String(resp_data.acc_resp_fields.package),
							signType: String(resp_data.acc_resp_fields.sign_type),
							paySign: String(resp_data.acc_resp_fields.pay_sign),
							success(res){
								this.queryPay() 
							},
							fail(fal){
								console.log('支付异常', fal);
							}
						})
					}
					
				} catch (error) {
					uni.hideLoading();
					console.log('拉卡拉支付接口异常，', error)
				}
			},
			
			
			async queryPay(){
				try {
					const res = await request(apiPay.queryPay, 'POST', {
						merchant_no: this.GoodsMsg.merchant_no,
						term_no: this.GoodsMsg.term_no,
						out_trade_no: this.orderMsg.order_no
					});
					if(res.statusCode == '200'){
						uni.showToast({
							title: '支付成功！',
						})
					}else{
						uni.showToast({
							title: res.msg,
						})
					}
				} catch (error) {
					uni.hideLoading();
					console.log('交易查询接口异常，', error)
				}
			},
			
		},
		onLoad(options) {
			this.id = options.id;
			this.init(options.id);
		}
	}
</script>

<style>
	@import url("./index.css");
</style>