<template>
	<view>
		<!-- ===================================== 搜索栏 ===================================== -->
		<view class="header-bar">
			<view class="city" @click="handleCitySelect">
				<view class="city-name">{{ city }}</view>
				<u-icon name="arrow-down" color="#fff" size="32"></u-icon>
			</view>
			<u-search placeholder="搜索停车点" :show-action="false" @search="handleSearch" v-model="keyword"></u-search>
			<!-- <u-icon class="scan" name="scan" color="#fff" size="48" @click="$refs.uToast.show({title: '建设中'})"></u-icon> -->
		</view>

		<!-- ===================================== 轮播图 ===================================== -->
		<u-swiper :list="bannerList" border-radius="0" mode="none" @click="swiperClick"></u-swiper>

		<!-- ===================================== 城市选择器 ===================================== -->
		<u-city-select v-model="cityOpen" @city-change="cityChange" :areaCode='["52", "5201"]'></u-city-select>

		<!-- ===================================== 滚动信息栏 ===================================== -->
		<view class="notice-bar-wrap u-flex" v-if="noticeList.length >= 1"
			@click="openPage('pages/message/message', true)">
			<u-icon custom-prefix="custom-icon" size="50" name="xiaoxi" color="#008CFF"></u-icon>
			<u-notice-bar class="u-flex-1" mode="vertical" :autoplay="true" :list="noticeList" :volume-icon="false"
				bg-color="#fff" color="#727272" :more-icon="true"></u-notice-bar>
		</view>

		<!-- ===================================== 宫格菜单 ===================================== -->
		<u-card :show-head="false" :show-foot="false" border-radius="16" margin="20rpx 40rpx" padding="30">
			<view class="content-nav" slot="body">
				<view class="content-nav-item" v-for="(grid, index) in gridList" :key="'g-' + index"
					@click="openPage(grid.url, true)">
					<view class="content-nav-item-icon-wrap">
						<u-image :src="grid.imageUrl" :width="grid.width || '95rpx'" :height="grid.height || '95rpx'"
							:mode="grid.mode || 'heightFix'"></u-image>
					</view>
					<view class="content-nav-item-icon-text">{{grid.title}}</view>
				</view>
			</view>
		</u-card>

		<u-card :show-head="false" :show-foot="false" border-radius="16" margin="20rpx 40rpx" padding="30">
			<view slot="body" class="myorders">
				<view class="myorders-item">当前已缴费<text style="color: #008CFF;">{{ totalCount || '0'}}</text>笔，合计<text
						style="color: #008CFF;">{{totalActualAmount || '0'}}</text>元</view>
				<view class="myorders-item">当前欠费<text style="color: #FF482B;">{{totalPayCount||'0'}}</text>笔，合计<text
						style="color: #FF482B;">{{ totalPayAmount || '0' }}</text>元</view>
			</view>
		</u-card>
		<!-- ===================================== 无停车信息 ===================================== -->
		<view class="empty-data-box" v-if="!orderList || orderList.length < 1">
			<u-empty text="暂无停车信息" mode="list"></u-empty>
		</view>

		<!-- ===================================== 停车列表 ===================================== -->
		<template v-for="(item, index) in orderList">
			<u-card :show-foot="false" border-radius="16" margin="20rpx 40rpx" padding="30">
				<view class="pending-order-head" slot="head">
					<view class="pending-order-head-left">
						<b>P</b>
						{{ item.roadName }}
					</view>
					<view class="pending-order-head-right" @click="  onRoadInfo(item)">
						<u-icon class="arrow-down" name="arrow-down" size="32" color="#aaa"></u-icon>
					</view>
				</view>
				<view class="pending-order-body" slot="body">
					<view class="pending-order-body-nav">
						<view class="nav-item nav-manual" @click="orderNavclick()" :class="{ active: orderNav == 0 }">
							手动缴费</view>
						<view class="nav-item nav-auto" @click="orderNavclick()" :class="{ active: orderNav == 1 }">无感支付
						</view>
					</view>
					<view class="pending-order-body-wrap" v-show="orderNav == 0">
						<view class="pending-order-body-left">
							<view class="car-number">{{ item.vehicleNo }}</view>
							<view class="item-cell">
								<span class="pending-order-body-left-label">入场时间：</span>
								<span>{{ item.inTime }}</span>
							</view>
							<view class="item-cell">
								<span class="pending-order-body-left-label">出场时间：</span>
								<span>{{item.outTime || '未出场' }}</span>
							</view>
							<view class="item-cell">
								<span class="pending-order-body-left-label">预计金额：</span>
								<span>{{ item.payAmount || 0 }}</span>
							</view>
							<view class="item-cell" v-if="item.vehicleNo==''">
								<span class="pending-order-body-left-label">车牌信息：</span>
								<span class="pending-order-body-center-label" @click="addvehicleNo(item.orderId)">添加车牌</span>
							</view>
							<view class="item-cell" v-else>
								<span class="pending-order-body-left-label">车牌信息：</span>
								<span >{{ item.vehicleNo }}</span>
								<!-- <span class="pending-order-body-right-label" @click="changevehicleNo(item.orderId)">更换</span> -->
							</view>
							<!-- <view class="item-cell">
                <span class="pending-order-body-left-label">出场时间:</span>
                <span>{{item.outTime||'停放中'}}</span>
              </view>
              <view class="item-cell">
                <span class="pending-order-body-left-label">停留时间:</span>
                <span>{{item.duration||'停放中'}}</span>
              </view>
              <view class="item-cell cost">
                <span class="pending-order-body-left-label">停车费用:</span>
                <span>
                  <span class="number" v-if="item.payAmount">￥{{item.payAmount}}</span>
                  <span class="number" v-else>停放中</span>
                </span>
              </view>-->
						</view>
						<view class="pending-order-body-right">
							<view class="order">停车泊位:{{ item.spaceName }}</view>
						</view>
						<view class="go-pay-wrap" v-if="Number(item.deviceType) !== 2">
							<view class="go-pay" @click="goPay(item.id)" v-if="item.payAmount != 0">出场缴费</view>
							<view class="go-pay1" v-else>出场缴费</view>
						</view>
					</view>
					<view class="pending-order-body-wrap" v-show="orderNav == 1">
						<view v-if="contractStatus == 0" class="nosign">
							<view class="nosign1">您的车牌未签约贵州银行无感支付</view>
							<view class="nosign2">请下载贵州银行手机银行app进行签约</view>
						</view>
						<view v-if="contractStatus == 1" class="sign">
							<view class="sign1">您已签约贵州银行无感支付</view>
							<view class="sign2">停车出场时将默认使用无感支付进行支付</view>
						</view>
					</view>
				</view>
			</u-card>
		</template>

		<!-- ===================================== 优惠活动 ===================================== -->
		<view class="promotion-box">
			<view class="promotion-title">
				<text>优惠活动</text>
			</view>
			<view class="promotion-banner">
				<u-swiper :list="promotionBannerList" @click="promotionBannerClick" height="221"></u-swiper>
			</view>
		</view>

		<!-- ===================================== 绑定车牌号弹框 ===================================== -->
		<u-modal v-model="bindCarShow" title="绑定车牌号" :show-cancel-button="true" confirm-text="去绑定"
			content="首次使用请先绑定您的车牌" @confirm="$u.route({ url: 'pages/myCars/myCars' })"></u-modal>

		<!-- ===================================== 停车场信息弹框 ===================================== -->
		<u-popup class="popup-order-details" v-model="showOrderDetails" mode="center" width="90%" border-radius="20">
			<view class="popup-order-details-til">停车场信息</view>
			<view class="popup-order-details-con">
				<dl>
					<dt>路段名称：</dt>
					<dd>{{ popupOrderDetails.roadName }}</dd>
				</dl>
				<dl>
					<dt>路段编码：</dt>
					<dd>{{ popupOrderDetails.roadNo }}</dd>
				</dl>
				<dl>
					<dt>联系人：</dt>
					<dd>{{ popupOrderDetails.manager }}</dd>
				</dl>
				<dl>
					<dt>联系电话：</dt>
					<dd @click="phoneCall(popupOrderDetails.telephone)">{{ popupOrderDetails.telephone }}</dd>
				</dl>
			</view>
			<view class="popup-order-details-footer" @click="closeOrderDetails">知道了</view>
		</u-popup>

		<!-- ===================================== 支付方式弹框 ===================================== -->
		<PaymentMethod
			:payWayPop="payWayPop"
			:curOrderList="curOrderList"
			:jumpUrl="jumpUrl"
			@closePaymentMethod="closePaymentMethod"
		></PaymentMethod>
		
		<!-- ===================================== 0元提示弹出层 ===================================== -->
		<u-modal
			v-model="jumpMsgModal"
			:content="jumpMsgContent"
			:show-title="false"
			:show-confirm-button="false"
		/>
		<u-toast ref="uToast" />
		
		<!-- ===================================== 添加车牌弹出层 ===================================== -->
		<u-popup class="popup-vehicleNo" v-model="ShowaddvehicleNo" mode="center" border-radius="20" width="710rpx" height="auto">
			<view class="popup-vehicleNo-title">添加车牌</view>
			<view class="popup-vehicleNo-center"></view>
			<view class="popup-vehicleNo-content">
				<view class="new-plate-number">
					<view class="message-input-wrap" @click="messageInputClick">
						<u-message-input :maxlength="8" width="70" font-size="50" :disabled-keyboard="true" v-model="newPlateNumber"></u-message-input>
					</view>		
				</view>
			</view>
			<view class="popup-vehicleNo-select">暂无绑定车牌</view>
			<view class="vehicleNo-btn">
				<u-button type="primary" @click="handleAddCar">确认</u-button>
				<u-button type="primary" plain @click="ShowaddvehicleNo=false">取消</u-button>
			</view>
		</u-popup>
		
		<u-action-sheet :list="colorList" @click="confirmColor" v-model="colorShow"></u-action-sheet>
		<u-keyboard ref="uKeyboard" mode="car" @change="keyboardChange" @confirm="keyboardConfirm" @backspace="backspace" v-model="keyboardshow" ></u-keyboard>
		
		<!-- ===================================== 更换车牌弹出层 ===================================== -->
		<u-popup class="popup-vehicleNo" v-model="ShowchangevehicleNo" mode="center" border-radius="20" width="710rpx" height="auto">
			<view class="popup-vehicleNo-title">更换车牌</view>
			<view class="popup-vehicleNo-center"></view>
			<view class="popup-vehicleNo-content">
				<view class="new-plate-number">
					<view class="message-input-wrap" @click="messageInputClick">
						<u-message-input :maxlength="8" width="70" font-size="50" :disabled-keyboard="true" v-model="newPlateNumber"></u-message-input>
					</view>
				</view>
			</view>
			<view class="popup-vehicleNo-select">
				<u-collapse ref="refValue">
					<u-collapse-item title="点击选择车牌" align="center" >
						<u-cell-group >
							<u-cell-item  :title="item.vehicleNo" v-for="(item, index) in groupList"  :key="index" :arrow="false" >
								<u-radio-group v-model="selectvalue"  @change="radioGroupChange">
									<u-radio  :name="item.vehicleNo" :key="index"></u-radio>
								</u-radio-group>
							</u-cell-item>
						</u-cell-group>
					</u-collapse-item>
				</u-collapse>
			</view>
			<view class="vehicleNo-btn">
				<u-button type="primary" @click="handleAddCar">确认</u-button>
				<u-button type="primary" plain @click="ShowchangevehicleNo=false">取消</u-button>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import getUrlParams from '../../utils/getUrlParams.js'
	import PaymentMethod from '@/pages/paymentMethod/paymentMethod.vue'
	import { jsonp } from 'vue-jsonp'
	export default {
		components: {
			PaymentMethod
		},
		data() {
			return {
				orderid:'',
				selectvalue: null,
				groupList: [],
				radiogroupList: [],
				keyboardshow: false,
				colorShow: false,
				colorList:[
					{text:'蓝色',colorCode:0}
					,{text:'黄色',colorCode:1}
					,{text:'黑色',colorCode:2}
					,{text:'白色',colorCode:3}
					,{text:'绿色',colorCode:4}
					,{text:'其他',colorCode:99}
				],
				vehicleColor:0,
				newPlateNumber:'',
				//更换车牌弹窗
				ShowchangevehicleNo: false,
				//添加车牌弹窗
				ShowaddvehicleNo: false,
				// 城市选择框
				cityOpen: false,
				// 选中城市
				city: '贵州省',
				// 搜索框值
				keyword: '',
				// 轮播图
				bannerList: [{
					image: require('@/static/img/index-banner01.png')
				}],
				// 订单列表
				orderList: [],
				// 微信code
				code: null,
				// 手动,无感
				orderNav: '',
				// 绑定车询问弹窗
				bindCarShow: false,
				// 是否线上订单细节
				showOrderDetails: false,
				// 订单详情
				popupOrderDetails: [],
				// 消息列表
				noticeList: [],
				// 优惠活动广告图
				promotionBannerList: [{
						id: 1,
						image: '/static/img/promotion-banner-1.png',
						title: '1分钱停车'
					},
					{
						id: 2,
						image: '/static/img/promotion-banner-2.png',
						title: '八折停车'
					}
				],
				// 签约状态
				contractStatus: '',
				vehicleId: '',
				recordList: [],
				// 支付方式弹框
				payWayPop: false,
				// 订单号
				curOrderList: [],
				// 当前位置经纬度
				latLongItude: {},
				// 跳转地址
				jumpUrl: '',
				// 宫格菜单列表
				gridList: [{
						url: 'pages/payLists/payLists',
						imageUrl: '../../static/img/index-content-nav-01.png',
						title: '停车缴费'
					},
					{
						url: 'pages/favourableActivity/favourableActivity',
						imageUrl: '../../static/img/index-content-nav-02.png',
						title: '优惠活动'
					},
					{
						url: 'pages/myCars/myCars',
						imageUrl: '../../static/img/index-content-nav-03.png',
						title: '车辆管理'
					},
					{
						url: 'pages/searchparking/searchparking',
						imageUrl: '../../static/img/index-content-nav-04.png',
						title: '我的停车'
					}
				],
				totalActualAmount: '', //缴费总额
				totalPayAmount: '', //应支付总额
				totalCount: '', //缴费总笔数 
				totalPayCount: '', //应支付总笔数
				// 0元提示框
				jumpMsgModal: false,
				// 0元提示内容
				jumpMsgContent: ''
			}
		},
		onLoad(page) {
			const locationLocaturl = window.location.href
			// 微信聚合支付完成跳转过来重定向到详情页
			const type = getUrlParams(locationLocaturl, 'type')
			if (type && type === 'jumpurl') {
				const jumpurl = localStorage.getItem('jumpUrl')
				if (jumpurl) {
					uni.showLoading({
						title: '正在跳转中...'
					})
					setTimeout(() => {
						uni.hideLoading()
						location.href = jumpurl
					}, 0)
				}
			}
			// 0元支付情况添加一个加载层
			const jumpMsg = getUrlParams(locationLocaturl, 'jumpMsg')
			if (jumpMsg) {
				this.jumpMsgModal = true
				this.jumpMsgContent = jumpMsg
				setTimeout(() => {
					this.jumpMsgModal = false
				}, 3000)
			}
		},
		onShow() {
			this.handleGetIndexData()
			this.getLocation()
			const locationLocaturl = window.location.search
			this.code = getUrlParams(locationLocaturl, 'code')
			if (this.code && !this.$store.state.vuex_wxinfo.openId) {
				this.handleGetWXInfo(this.code)
			};
		},
		methods: {
			radioGroupChange(e){
				this.newPlateNumber = e
			},
			// 获取车辆列表
			handlegetMycars(){
				let that = this;
				this.$u.api.getMycars()
					.then(res=>{
						if (res.code === 200) {
							this.groupList = res.data.rows;
							this.radiogroupList = res.data.rows;
							this.$nextTick(() => {
								// dom元素更新后执行，因此这里能正确打印更改之后的值
								console.log(that.$refs.refValue.init()) // 改变了的值
							})
						} else {
							this.$refs.uToast.show({
								title: res.msg,
								type: 'error'
							})
						}
					})
			},
			//更换车牌信息
			changevehicleNo(id){
				this.orderid = id;
				this.ShowchangevehicleNo = true;
				this.handlegetMycars();
			},
			// 添加车辆
			handleAddCar(){
				if(!this.$u.test.carNo(this.newPlateNumber)){
					this.$refs.uToast.show({
						title: '请正确填写车牌号',
						type: 'error',
					});
					return
				}
				let param = {
					orderId: this.orderid,
					vehicleNo: this.newPlateNumber,
					vehicleColor: this.vehicleColor,
				};
				let that = this;
				this.$u.api.bindVehicleNo(param)
					.then(res=>{
						if (res.code === 200) {
							this.$refs.uToast.show({
								title: res.msg,
								type: 'success',
							});
							that.handleGetIndexData();
							that.ShowchangevehicleNo = false;
						} else {
							this.$refs.uToast.show({
								title: res.msg,
								type: 'error',
							});
						}
					})
			},
			//新增车牌
			addvehicleNo(){
				this.ShowaddvehicleNo = true;
			},
			
			// 点击输入框
			messageInputClick(){
				this.keyboardshow = true;
			},
			// 按键被点击(点击退格键不会触发此事件)
			keyboardChange(val) {
				// 将每次按键的值拼接到value变量中，注意+=写法
				this.newPlateNumber += val;
			},
			// 退格键被点击
			backspace() {
				// 删除value的最后一个字符
				if(this.newPlateNumber.length) this.newPlateNumber = this.newPlateNumber.substr(0, this.newPlateNumber.length - 1);
			},
			// 键盘输入完成后确认
			keyboardConfirm(){
				this.colorShow = true;
			},
			// 确认颜色
			confirmColor(e){
				this.vehicleColor = this.colorList[e].colorCode;
			},
			//添加车牌
			addvehicleNo(id){
				this.orderid = id;
				this.ShowaddvehicleNo = true;
			},
			// 定位
			getLocation() {
				const that = this
				if (navigator.geolocation) {
					// 判断是否有这个对象
					navigator.geolocation.getCurrentPosition(function(pos) {
						that.latLongItude = {
							latitude: pos.coords.latitude,
							longitude: pos.coords.longitude
						}
						that.latitude = pos.coords.latitude
						that.longitude = pos.coords.longitude
						that.getCityNameByLonLat(that.latLongItude)
					}, function(err) {
						// 错误处理
						switch (err.code) {
							case 1:
								alert('位置服务被拒绝。')
								break
							case 2:
								alert('暂时获取不到位置信息。')
								break
							case 3:
								alert('获取信息超时。')
								break
							default:
								alert('未知错误。')
								break
						}
					})
				} else {
					alert('当前系统不支持GPS API')
				};
			},
			// 通过经纬度获取地区详细信息
			getCityNameByLonLat({
				longitude,
				latitude
			} = {}) {
				const that = this
				uni.showLoading({
					title: '加载中',
					mask: true
				})
				const str = `output=jsonp&key=BOGBZ-2BZ33-O4L32-Y3QJR-PGN66-RFFEL&location=${latitude},${longitude}`
				jsonp('https://apis.map.qq.com/ws/geocoder/v1/?' + str, {}).then(res => {
					uni.hideLoading()
					if (res.status == 0) {
						if (res.result.ad_info) {
							that.city = res.result.ad_info.district
						}
					}
				})
			},
			// 轮播图点击
			swiperClick(item) {
				this.$u.route({
					url: 'pages/bannerDetails/bannerDetails',
					params: {
						id: this.bannerList[item].id
					}
				})
			},
			// 切换无感和手动
			orderNavclick() {
				uni.showLoading({
					title: '加载中'
				});
				console.log('this.recordList[1]', this.recordList[1]);
				console.log('orderNav', this.orderNav)
				if (!this.recordList[1]) {
					uni.hideLoading();
					return
				}
				this.$u.api.feePay({
						vehicleId: this.recordList[1]
					})
					.then(res => {
						console.log('res', res);
						if (res?.code == 200) {
							this.handleGetIndexData()
						} else {

							// this.$refs.uToast.show({
							//   title: res?.msg,
							//   type: 'error'
							// })
						}
						uni.hideLoading()
					}).catch(err => {
						console.log('orderNavclick err', err)
					})
			},
			/**
			 * 跳转页面
			 * path 跳转路径
			 * flag 是否存储
			 * */
			openPage(path, flag) {
				this.$u.route({
					url: path
				})
				if (flag) {
					uni.setStorage({
						key: 'messageBack',
						data: 'pages/index/index'
					})
				}
			},
			// 搜索
			handleSearch() {
				uni.reLaunch({
					url: `/pages/parkingLists/parkingLists?keyword=${this.keyword}`
				})
			},
			// 城市选择
			handleCitySelect() {
				this.cityOpen = true
			},
			// 城市选择下拉变化
			cityChange(e) {
				if (e.area) {
					this.city = e.area.label
				} else if (e.city) {
					this.city = e.city.label
				} else {
					this.city = e.province.label
				}
			},
			// 获取首页数据
			handleGetIndexData() {
				uni.showLoading({
					title: '加载中'
				})
				this.$u.api.getIndexData()
					.then(res => {
						if (res.code === 200) {
							// 轮播
							const bannerList = []
							const banner = res.data?.advs
							banner.forEach(item => {
								const obj = {
									image: item.bannerUrl,
									id: item.id,
									name: item.name,
									content: item.content
								}
								bannerList.push(obj)
							})
							if (bannerList.length > 0) {
								this.bannerList = bannerList
							}
							// 是否有绑定车牌: 没有则通过弹框去绑定
							const vehicleList = res.data?.vehicleList ?? []
							if (vehicleList.length === 0) {
								this.bindCarShow = true
							}
							// 无感和手动
							const enableFeepay = []
							const orderList = res.data?.orderList ?? []
							orderList.forEach(item => {
								if (item.enableFeepay) {
									enableFeepay.push(item.enableFeepay)
								} else {
									enableFeepay.push(0)
								}
								enableFeepay.push(item.vehicleId)
								if (item.contractStatus) {
									enableFeepay.push(item.contractStatus)
								} else {
									enableFeepay.push(0)
								}
							})
							this.totalActualAmount = res.data?.payedInfo?.totalActualAmount
							this.totalCount = res.data?.payedInfo?.totalCount
							this.totalPayAmount = res.data?.payingInfo?.totalPayAmount
							this.totalPayCount = res.data?.payingInfo?.totalCount
							this.recordList = enableFeepay
							this.orderNav = enableFeepay[0]
							this.contractStatus = enableFeepay[2]
							this.orderList = res.data.orderList
							// 消息提示
							const newsList = []
							const news = res.data?.news ?? []
							news.forEach(item => {
								newsList.push(item.content)
							})
							this.noticeList = newsList
							uni.hideLoading()
						} else {
							this.$refs.uToast.show({
								title: res.msg,
								type: 'error'
							})
							uni.hideLoading()
						}
					})
			},
			// 去支付,选择支付方式
			goPay(orderId) {
				const href = location.href.split('#')
				this.jumpUrl = href[0] + '#/pages/center/order/orderDetails/orderDetails?orderId=' + orderId + '&type=open'
				this.payWayPop = true
				this.curOrderList = []
				this.curOrderList.push(orderId)
			},
			// 获取路段详情
			onRoadInfo(item) {
				this.$u.api.roadInfoById({
						id: item.roadId
					})
					.then(res => {
						this.popupOrderDetails = res.data
						this.showOrderDetails = true
					}).catch(err => {
						this.$refs.uToast.show({
							title: '系统异常',
							type: 'error'
						})
					})
			},
			// 关闭路段详情弹框
			closeOrderDetails() {
				this.showOrderDetails = false
			},
			// 打电话
			phoneCall(phone) {
				uni.makePhoneCall({
					phoneNumber: phone
				})
			},
			/**
			 * 点击优惠活动的广告图
			 * */
			promotionBannerClick(cur) {
				this.promotionBannerList.forEach((item, index) => {
					if (cur === index) {
						this.$u.route({
							url: 'pages/favourableActivity/favourableActivity',
							params: {
								title: item.title,
								id: item.id
							}
						})
					}
				})
			},
			// 关闭支付弹框
			closePaymentMethod() {
				this.payWayPop = false
			}
		}
	}
</script>

<style lang="scss" scoped>
	@import "./index.scss";
</style>
