<template>
	<view class="index">
		<!-- 头部功能组件 -->
		<cu-loadding :show="show" />
		<!-- header -->
		<cu-custom bgColor="bg-gradual-blue">
			<view slot="content">{{ value.title }}</view>
		</cu-custom>
		<!-- section -->
		<!-- 富文本 -->
		<rich-text style="width: 100vw;" :nodes="value.describe"></rich-text>
		<!-- 输入表单 -->
		<view class="titles" style="background-color: #f60d11;">
			<view class="bg-pink light"></view>
			<view>填写信息</view>
		</view>
		<view style="background-color: #f60d11;" class="from padding-lr padding-bottom">
			<view style="border-radius: 20rpx;" class="bg-white padding-bottom padding-top-xl">
				<form>
					<view class="cu-form-group">
						<view class="title text-bold text-black">门店名称</view>
						<view style="flex: 1;" class="text-bold text-black">{{ value.branch_name }}</view>
					</view>
					<view class="cu-form-group">
						<view class="title text-bold text-black">门店地址</view>
						<view style="flex: 1;" class="text-bold text-black">{{ value.branch_address }}</view>
						<text style="color:#f60d11;" class="cuIcon-locationfill"></text>
					</view>
					<view class="cu-form-group">
						<view class="title text-bold text-black">服务电话</view>
						<view style="flex: 1;" class="text-bold text-black">{{ value.branch_tel }}</view>
						<van-icon size="16" color="#f60d11" name="phone" />
					</view>
					<view class="cu-form-group">
						<view class="title text-bold text-black">填写姓名</view>
						<input type="text" class="text-bold text-black" v-model="formData.name" placeholder="请输入车型" />
					</view>
					<view class="cu-form-group">
						<view class="title text-bold text-black">填写车型</view>
						<input type="text" class="text-bold text-black" v-model="formData.model" placeholder="请输入车型" />
					</view>
					<view class="cu-form-group">
						<view class="title text-bold text-black">车牌号码</view>
						<view style="flex: auto;"><key-code :value.sync="formData.number" /></view>
					</view>
					<view class="cu-form-group">
						<view class="title text-bold text-black">手机号码</view>
						<input type="number" confirm-type="done" @confirm="submit" class="text-bold text-black" v-model="formData.tel" placeholder="请输入手机号码" />
					</view>
					<view class="cu-form-group justify-center">
						<view style="width: 300rpx;">
							<van-button :loading="loading" color="#f60d11" @click="submit" size="small" block round type="info">提交信息</van-button>
						</view>
					</view>
				</form>
			</view>
		</view>
		<!-- 历史购买记录 -->
		<view class="titles " style="background-color: #f60d11;">
			<view class="bg-pink light"></view>
			<view class="text-center">已有{{ historyData.totalResult }}人购买</view>
		</view>
		<view style="background-color: #f60d11;" class="padding-lr padding-bottom">
			<view style="border-radius: 20rpx;flex-wrap: wrap;" class="padding-bottom padding-top-xl bg-white ">
				<view class="flex padding-tb">
					<view style="width: 20%;" class="text-center text-bold text-black">序号</view>
					<view style="width: 25%;" class="text-center text-bold text-black">车牌号码</view>
					<view style="width: 25%;" class="text-center text-bold text-black">卡卷状态</view>
					<view style="width: 30%;" class="text-center text-bold text-black">购买时间</view>
				</view>
				<view v-for="(item, index) of historyData.value" :key="index" class="flex padding-tb-sm border">
					<view style="width: 20%;" class="text-center text-cut">{{ index + 1 }}</view>
					<view style="width: 25%;" class="text-center text-cut">{{ item.number }}</view>
					<view style="width: 25%;" class="text-center text-cut">已经领取</view>
					<view style="width: 30%;" class="text-center text-cut">{{ item.create_time }}</view>
				</view>
				<view v-if="btnShow" class="flex justify-center padding">
					<view style="width: 300rpx;"><van-button color="#f60d11" @click="more" size="small" block round type="info">查看更多</van-button></view>
				</view>
			</view>
		</view>
		<!-- footer -->
		<!-- 个人中心 -->
		<view
			@click="personal"
			style="width:120rpx ;height:120rpx;box-shadow: 0rpx 0rpx 20rpx #aaa;position: fixed;right: 40rpx;bottom: 30vh;z-index: 9999;"
			class=" bg-orange light round padding-sm flex align-center justify-center"
		>
			<view class="text-center ">
				<text class="cuIcon-peoplefill  text-xl"></text>
				<view class="text-xs">个人中心</view>
			</view>
		</view>
		<!-- 生成海报 -->
		<view
			@click="pic"
			style="width:120rpx ;height:120rpx;box-shadow: 0rpx 0rpx 20rpx #aaa;position: fixed;right: 40rpx;bottom: 18vh;z-index: 9999;"
			class=" bg-orange light round padding-sm flex align-center justify-center"
		>
			<view class="text-center ">
				<text class="cuIcon-pic  text-xl"></text>
				<view class="text-xs">生成海报</view>
			</view>
		</view>
		<!-- 底部功能栏 -->
		<view style="height: 50px;">
			<van-submit-bar :loading="loading" :price="value.amount * 100" button-text="立即购买" @submit="submit">
				<view @click="consult">
					<van-icon name="service-o"></van-icon>
					<text>咨询</text>
				</view>
			</van-submit-bar>
		</view>
		<!-- 微信快捷登录 -->
		<van-dialog
			message="尚未登录"
			confirmButtonText="微信快捷登录"
			:show="dialog"
			id="van-dialog"
			show-cancel-button
			@close="dialog = false"
			confirm-button-open-type="getPhoneNumber"
			@getphonenumber="getphonenumber"
		/>
	</view>
</template>

<script>
import keyCode from './components/keyCode.vue';
import Dialog from '@/wxcomponents/vant/dist/dialog/dialog';
export default {
	components: {
		keyCode
	},
	data() {
		return {
			show: true, //加载
			btnShow: true, //查看更多
			loading: false, //立即支付
			dialog: false, //微信快捷登录
			value: {},
			// 提交文本
			formData: {
				name: '',
				tel: '',
				model: '',
				number: ''
			},
			// 购买数据
			historyData: {
				totalResult: '',
				currentPage: 1,
				totalPage: 1,
				value: []
			}
		};
	},
	onLoad(options) {
		this.getOptions(options);
		this.initRequest();
	},
	// 分享朋友
	onShareAppMessage: function(e) {
		return {
			title: this.value.title,
			// imageUrl:""
			path: `/pages/index/index?customer_id=${this.$store.state.userInfo.user_id || ''}&activity_id=${this.$store.state.userInfo.activity_id}`
		};
	},
	// 分享朋友圈
	onShareTimeline: function(res) {
		return {
			title: this.value.title,
			// imageUrl:"",
			query: `customer_id=${this.$store.state.userInfo.user_id || ''}&activity_id=${this.$store.state.userInfo.activity_id}`
		};
	},

	methods: {
		// 接受参数
		getOptions(options) {
			var result = {};
			if (options.scene) {
				result = this.$global.qrcodeValue(options.scene);
			} else {
				result = options;
			}
			console.log(result);
			this.$store.commit('userInfo', result);
		},
		// 微信快捷登录
		async getphonenumber(e) {
			try {
				var { encryptedData, iv } = e.detail;
				var { openid, appid, activity_id } = this.$store.state.userInfo;
				var res = await this.$global.request({ url: '/customer/wxbind/', method: 'post', data: { openid, appid, activity_id, encryptedData, iv } });
				if (res.data.token) uni.setStorageSync('token', 'JWT ' + res.data.token);
				this.$store.commit('userInfo', res.data);
				uni.showToast({
					icon: 'none',
					title: '登录成功'
				});
			} catch (err) {
				this.showErr(err);
			} finally {
				this.show = false;
			}
		},
		// 报错
		showErr(content) {
			content = JSON.stringify(content) === '{}' ? '未知错误' : content;
			uni.showModal({
				content,
				showCancel: false,
				success: res => console.log(res)
			});
		},
		// 进入页面请求
		async initRequest() {
			try {
				var { appid, code } = await this.codeAppid();
				// codeSession
				var res = await this.$global.request({
					url: '/customer/code2Session/',
					method: 'post',
					data: {
						code,
						appid,
						activity_id: this.$store.state.userInfo.activity_id || ''
					}
				});
				if (res.data.token) uni.setStorageSync('token', 'JWT ' + res.data.token);
				this.$store.commit('userInfo', { appid, code, ...res.data });
				// 活动详情
				res = await this.$global.request({
					url: '/customer/activity/detail/',
					method: 'get',
					data: {
						activity_id: this.$store.state.userInfo.activity_id
						// appid:this.$store.state.userInfo.appid
					}
				});
				// 富文本处理
				res.data.describe = this.$global.richTextChange(res.data.describe);
				this.value = res.data;
				// 已有人购买
				this.payed();
			} catch (err) {
				this.showErr(err);
			} finally {
				this.show = false;
			}
		},
		// 请求购买情况
		async payed() {
			try {
				var { currentPage, totalPage, value } = this.historyData;
				var res = await this.$global.request({
					url: '/customer/order/activity_order/',
					method: 'get',
					data: {
						activity_id: this.$store.state.userInfo.activity_id,
						limit: 5,
						page: currentPage
					}
				});
				currentPage++;
				totalPage = res.totalPage;
				value = value.concat(res.data);
				if (currentPage > totalPage) this.btnShow = false;
				this.historyData = { value, currentPage, totalPage, totalResult: res.totalResult };
			} catch (err) {
				this.showErr(err);
			}
		},
		// 获取 code appid
		codeAppid() {
			return new Promise((resolve, reject) => {
				const appid = uni.getAccountInfoSync().miniProgram.appId;
				uni.login({ success, fail: err => reject(err) });
				function success(res) {
					var { code } = res;
					resolve({ code, appid });
				}
			});
		},
		// 提交信息
		async submit() {
			// 验证登录状态
			if (!uni.getStorageSync('token')) {
				this.dialog = true;
				return false;
			}
			try {
				this.loading = true;
				var res = await this.$global.request({
					url: '/customer/order/',
					method: 'post',
					header: {
						'Content-Type': 'application/x-www-form-urlencoded',
						Authorization: uni.getStorageSync('token')
					},
					data: {
						appid: this.$store.state.userInfo.appid,
						activity_id: this.$store.state.userInfo.activity_id,
						activity: this.$store.state.userInfo.activity_id,
						openid: this.$store.state.userInfo.openid,
						recommend_member: this.$store.state.userInfo.customer_id || '',
						...this.formData
					}
				});
				this.signature(res.data);
			} catch (err) {
				this.showErr(err);
			} finally {
				this.loading = false;
			}
		},
		// 支付签名
		signature(data) {
			uni.requestPayment({
				timeStamp: data.timeStamp,
				nonceStr: data.nonceStr,
				package: data.package,
				signType: data.signType,
				paySign: data.paySign,
				success() {
					uni.showToast({
						icon: 'none',
						title: '支付成功'
					});
				},
				fail() {
					uni.showToast({
						icon: 'none',
						title: '支付失败'
					});
				}
			});
		},
		// 查看更多
		more() {
			this.payed();
		},
		// 我要咨询
		consult() {
			if (this.value.branch_tel)
				uni.makePhoneCall({
					phoneNumber: this.value.branch_tel
				});
		},
		// 个人中心
		personal() {
			uni.navigateTo({
				url: '/pages/login/index'
			});
		},
		// 生成海报
		pic() {
			// 验证登录状态
			if (!uni.getStorageSync('token')) {
				this.dialog = true;
				return false;
			}
			uni.navigateTo({
				url: '/pages/pic/index'
			});
		}
	}
};
</script>

<style lang="scss" scoped>
.index {
	.titles {
		padding-top: 30rpx;
		position: relative;
		> view:nth-child(1) {
			position: relative;
			width: 340rpx;
			height: 40rpx;
			left: calc(50% - 170rpx);
			&::before {
				content: '';
				position: absolute;
				display: table;
				border-right: 20rpx solid transparent;
				border-top: 40rpx solid #f60d11;
			}
			&::after {
				content: '';
				position: absolute;
				right: 0;
				display: table;
				border-left: 20rpx solid transparent;
				border-top: 40rpx solid #f60d11;
			}
		}
		> view:nth-child(2) {
			border-radius: 15rpx;
			width: 300rpx;
			color: #f60d11;
			position: absolute;
			left: calc(50% - 150rpx);
			box-sizing: border-box;
			top: 25rpx;
			padding: 20rpx 0;
			text-align: center;
			font-size: 34rpx;
			background-image: linear-gradient(to bottom, #fff, #f9bcc7);
		}
	}
}
</style>
