<template>
	<view class="pagecontent page-content my-bg">
		<cu-custom bgColor="bg-blue">
			<block slot="content">首页</block>
		</cu-custom>
		<view class="fixed">
			<view class="bg-blue pagestart">
				<view class="cu-bar search">
					<!-- <view class="text-xxl margin-left  text-center bg-blue">
						<view class="cuIcon-scan"></view>
					</view> -->
					<view class="margin-left text-center">
						<text>{{locationName}}</text>
						<text class="cuIcon-triangledown"></text>
					</view>
					<view class="search-form radius" @tap="InputFocus">
						<text class="cuIcon-search"></text>
						<input disabled :adjust-position="false" type="text" placeholder="搜索油站名称" confirm-type="search" />
					</view>
				<!-- 	<view class="">
						阿三
					</view> -->
				</view>
			</view>
			<!-- 红色背景四个 -->
			<view class="bg-blue padding pagestarttwo">
				<view class="grid col-4 text-center ">
					<view class="text-xxl" @tap="openScan">
						<view class="cuIcon-scan">
						</view>
						<text class="text-df">
							扫一扫
						</text>
					</view>
					<view class="text-xxl" @tap="showQr">
						<view class="cuIcon-qr_code">

						</view>
						<text class="text-df">
							付款码
						</text>
					</view>
					<view class="text-xxl" @tap="toCards">
						<view class="cuIcon-vipcard">

						</view>
						<text class="text-df">
							加油卡
						</text>
					</view>
					<view class="text-xxl" @tap="toOrders">
						<view class="cuIcon-form">

						</view>
						<text class="text-df">
							订单中心
						</text>
					</view>
				</view>
			</view>
		</view>
		<view class="placeholder-hidden">

			<view class="bg-blue pagestart">
				<view class="cu-bar search">
					<view class="text-xxl margin-left  text-center bg-blue">
						<!-- <view class="cuIcon-scan"></view> -->
					</view>

				</view>
			</view>
			<!-- 红色背景四个 -->
			<view class="bg-blue padding pagestarttwo">
				<view class="grid col-4 text-center ">
					<view class="text-xxl">
						<view class="cuIcon-scan">
						</view>
						<text class="text-df">
							扫一扫
						</text>
					</view>
					<view class="text-xxl">
						<view class="cuIcon-qr_code">

						</view>
						<text class="text-df">
							付款码
						</text>
					</view>
					<view class="text-xxl">
						<view class="cuIcon-vipcard">

						</view>
						<text class="text-df">
							加油卡
						</text>
					</view>
					<view class="text-xxl">
						<view class="cuIcon-form">

						</view>
						<text class="text-df">
							订单中心
						</text>
					</view>
				</view>
			</view>
		</view>
		<!-- 广告图片开始 -->
		<view class="my-bg padding">
			<view class="" >
				<!-- <swiper autoplay interval='5000' style="width: 100%;height: 204rpx;" class="swiper" circular >
					<swiper-item @click="swiperClick(item,index)" v-for="(item,index) in swiperArray">
						<image :src="item.src" style="width: 100%;"  mode="widthFix"></image>
					</swiper-item>
					<swiper-item>
						<ad unit-id="adunit-fae65289bc72095d" ad-intervals="30"></ad>
					</swiper-item>
				</swiper> -->
				<image :src="starUrl+'banner.png'" style="width: 100%;" mode="widthFix"></image>
			</view>
		</view>
		<!-- 筛选开始 -->
		<view class="screentop bg-white  padding-top " @tap="scrollScreen">
			<!-- <view class="">
				<sl-filter @result="filterRes" reflexTitle ref="slFilter" :menuList="menuList"></sl-filter>
			</view> -->
			<view class="  ">
				<view class="" v-if="siteList.length>0">
					<site-item v-for="(item,index) in siteList" :key="item.id" :site-item="item" :first="index==0" :listHeight="listHeight"
						class="cu-list menu-avatar cu-item" @tap="toDetail(item)">
					</site-item>
				</view>
				<view class="" v-else>
					<my-empty></my-empty>
				</view>
			</view>
		</view>
		<msg-models :showAuthFrror="showAuthFrror" @hideOneModal="hideModel"></msg-models>
		<three-sites @hideOneModal="showThreeSites=false" :showThreeSites="showThreeSites"></three-sites>
	</view>
</template>

<script>
	import msgModels from '../../components/showModels.vue'
	import accountApi from '@/api/account.js'
	import threeSites from '@/components/three-sites.vue'
	import oilSiteApi from '@/api/oil-site.js'
	import siteItem from '@/components/site-item/site-item.vue'
	import Financial from '@/api/Financial.js'
	// import slFilter from '@/components/sl-filter/sl-filter.vue'
	export default {
		components: {
			siteItem,
			threeSites,
			msgModels
			// slFilter
		},
		data() {
			return {
				swiperArray:[
					// {
					// 	src:this.global.starUrl+'banner.png',
					// 	link:''
					// },
					{
						src: 'https://xoil-public.oss-cn-beijing.aliyuncs.com/WMP-IMG/banner-2dwk.png',
						link: 'https://tengxun.hkzj168.com/?ChannelId=20220831152210221048473'
					},
				],
				listHeight:160,
				siteInfo: {

				},
				getCount: 0,
				siteId: '',
				showAuthFrzen: uni.getStorageSync('showAuthFrzen') ? uni.getStorageSync('showAuthFrzen') : 0,
				showAuthFrror: false,
				showThreeSites: false,
				filterData: {},
				menuList: uni.getStorageSync('filterData') ? uni.getStorageSync('filterData') : [{
						title: '渠道',
						isMutiple: false,
						key: 'channelCode',
						detailList: [{
							title: "全部",
							value: ""
						}]
					},
					{
						title: '0#轻柴油',
						key: 'oilProductCode',
						isMutiple: false,
						detailList: [{
							title: "全部",
							value: ""
						}]
					},
					{
						title: '品牌',
						key: 'siteBrand',
						isSort: true,
						isMutiple: false,
						detailList: [{
							title: "全部",
							value: ""
						}]
					}
				],
				siteList: [],
				height: 0,
				starUrl: this.global.starUrl,
				qqMapKey: this.global.qqMapKey,

				imgURL: this.global.imgURL + 'index/',
				location: uni.getStorageSync('location'),
				InputBottom: 0,
				show: false,
				locationName: '',
				title: 'Hello',
				cuIconList: [{
						iconUrl: 'icon-1.png',
						// icon: 'location',
						color: 'red',
						badge: 120,
						name: '附近油站'
					},
					{
						iconUrl: 'icon-2.png',
						color: 'orange',
						badge: 0,
						name: '线路规划'
					},
					// {
					// 	iconUrl: 'icon-3.png',
					// 	color: 'yellow',
					// 	badge: 0,
					// 	name: '实体油卡'
					// },
					{
						iconUrl: 'icon-4.png',
						color: 'olive',
						badge: 0,
						name: '消费分析'
					},
					{
						iconUrl: 'icon-5.png',
						color: 'cyan',
						badge: 0,
						name: '消息中心'
					},
					{
						iconUrl: 'icon-6.png',
						color: 'red',
						badge: 0,
						name: '优惠券'
					},
					{
						iconUrl: 'icon-7.png',
						color: 'purple',
						badge: 0,
						name: 'ETC'
					},
					// {
					// 	iconUrl: 'icon-8.png',
					// 	// icon: 'taxi',
					// 	color: 'mauve',
					// 	badge: 0,
					// 	name: '违章查询'
					// },
					{
						iconUrl: 'icon-9.png',
						color: 'purple',
						badge: 0,
						name: '我的车辆'
					},

					{
						iconUrl: 'iocn-10.png',
						color: 'cyan',
						badge: 0,
						name: '操作说明'
					},

				]
			};
		},
		onTabItemTap(res){
			this.showThreeSites =false
		},
		onLoad() {
			this.reverseGeocoder(this.location)
			this.refreshLocation()
			
			// if (!uni.getStorageSync('filterData')) {
			// 	this.getFilterData()
			// }
		},
		onPullDownRefresh() {
			this.refreshLocation()

			setTimeout(function() {
				uni.stopPullDownRefresh()
			}, 800);
		},
		onShow() {
			const token = uni.getStorageSync('Authorization')
			const openid = uni.getStorageSync('openid')
			if (token && openid) {
				this.getAuthInfo()
			} else {
				uni.showToast({
					title: '您还没有登录哦',
					icon: "none"
				})
			}
			uni.navigateTo({
				// url: `/BagStation/orderDetail/orderDetail?id=XOILAWMP202107070000025117`
			})
			// uni.redirectTo({
			//   url:'/BagStation/pages/makeOrder/makeOrder'
			//   // url:'/BagStation/pages/makeOrder/payResult?status=success'
			// })
			// url:'/BagStation/pages/makeOrder/payResult?status=success'
		},
		beforeCreate() {},
		onReady() {
			// this.getSiteList()
		},

		methods: {
			toManagement(){
				const user = uni.getStorageSync('user');
				if(user){
					Financial.findHomePageReport({customerId:user.id}).then(res=>{
						if(res.data){
							uni.navigateTo({
								url:`../../../Financial/pages/estimate/index?data=${encodeURIComponent(JSON.stringify(res.data))}`
							})
						}else{
							uni.navigateTo({
								url:'../../../Financial/pages/index?guide=1'
							})
						}
					});
				}else{
					uni.showToast({
						title: '请先登录！',
						icon: 'none'
					})
				}
			},
			swiperClick(item,index) {
				if(!item?.link) return
				switch (Number(index)) {
					// case 0:
					// 	this.goCall()
					// 	break;
					 default:
					 // console.log('item.link')
						uni.navigateTo({
							url: '/pages/tabbar/home/link?url=' +   encodeURIComponent(JSON.stringify(item.link)) 
						})
				}
			},
			goToPage(url) {
				if (!url) return;
				uni.navigateTo({
					url
				});
			},
			getAmount() {
				accountApi.getTotalOilCardInfo().then(res => {
					if (res.code == 20000) {
						this.userTotal = res.data
					}
				})
			},
			refreshLocation() {
				uni.getLocation({
					type: 'wgs84',
					success: (res) => {
						uni.setStorageSync('location', res)
					},
					complete: () => {
						this.getSiteList()
						// // console.log('made')
					},

				});
			},
			hideModel(name) {
				if (name == 'auth') {
					this.showAuthFrror = false
					if (this.showAuthFrzen <= new Date().getTime()) {
						// 一小时后再提示
						uni.setStorageSync('showAuthFrzen', new Date().getTime() + 10 * 1000)
						// uni.setStorageSync('showAuthFrzen', new Date().getTime() + 1 * 60 * 60 * 1000)
					}
				}
			},
			getAuthInfo() {
				oilSiteApi.getUserAuthInfo().then(res => {
					if (res.code === 20000) {
						this.getAmount()
						this.getSiteList()
						// realStatus: 0   vehicleStatus: 0
						if (this.showAuthFrzen <= new Date().getTime()) {
							this.showAuthFrror = res.data.realStatus && res.data.vehicleStatus ? false :
								true
						}
					}
				})
			},
			goCall() {
				return
				uni.makePhoneCall({
					phoneNumber: '4008-56-5355'
				})
			},
			reverseGeocoder(location) {
				this.selLocation = location
				this.$qqmapsdk.reverseGeocoder({
					location: location,
					success: (res) => {
						// console.log(res)
						this.locationName = res.result.address_component.city
					},
					fail: (res) => {
						// console.log(res)
					}
				})
			},
			shadoumeiyou(index) {
				if (index == 0) {
					uni.switchTab({
						url: '/pages/tabbar/station/stationList'
					})
				} else if (index == 1) {
					const referer = '星油云'; //调用插件的app的名称
					// const endPoint = JSON.stringify({
					// 	name: '油站',
					// 	latitude: 39.89631551,
					// 	longitude: 116.323459711
					// });
					// wx.navigateTo({
					// 	url: 'plugin://routePlan/index?key=' + this.qqMapKey + '&referer=' + referer +
					// 		'&endPoint=' + endPoint
					// })
					 uni.removeStorageSync("origins")
					     uni.removeStorageSync("destination")
					wx.navigateTo({
					      url:'../../../BagStation/pages/routePlain/routePlain'})
				} else if (index == 8) {
					this.goToPage('/BagAuth/pages/agreeMent/OperationGuide')
				}
				// else if(index==8){
				// 	uni.navigateTo({
				// 		url: '/BagStation/myCars/myCars'
				// 	})
				// }
				else {
					uni.showToast({
						title: '功能暂无',
						icon: 'none'
					})
				}
			},

			showQr() {
				// uni.navigateTo({
				// 	url: '/BagStation/pages/stationDetail/stieQr'
				// })
				this.showThreeSites = true
			},
			toCards() {
				uni.navigateTo({
					url: '/BagMoney/pages/oilCards/oilCards'
				})
			},
			toOrders() {
				uni.switchTab({
					url: '/pages/tabbar/order/orderList/orderList'
				})
			},
			filterRes(val) {
				this.filterData = val
				this.getSiteList()
			},

			getSiteList() {
				let params = {
					currentPage: 1,
					pageSize: 10,
					params: { //类型：Object  必有字段  备注：// 筛选对象
						// longitude: 117.157817, //  必有字段  备注：// 当前位置经度
						// latitude: 31.802472, //  必有字段  备注：// 当前位置维度
						// siteBrand: "", //   备注：// 石油品牌 ( 1-中国石油 2-中国石化 3-壳牌 4-民营 5-中海油 6-京博 7-中化石油 8-其他 )
						// channelCode: "", //   备注：// 渠道编码 ( OIL：星油 WJY：万金油 LV：老吕（找油网） TY：团油 YDJY：一点加油（壳牌）)
						// oilProductCode: "0#" //   备注：// 油号选择 ( 0# 92# 92#)
						clientBelong:'ZHONGPIN',
						comprehensiveSort:1,
						zpDisable:'ENABLE',
						sort: "juli", //类型：String  必有字段  备注：// 智能排序 ( price：价格最低 juli：距离最近 ) 默认距离排序
						...uni.getStorageSync('location'),
						...this.filterData,
					}

				}
				if (!uni.getStorageSync('user')) {
					oilSiteApi.readOnlySites(params).then(res => {
						this.getCount++
						if (res.code == 20000) {
							// console.log(res.data.list)
							this.siteList = res.data.list
						} else {
							if (this.getCount == 1) {
								setTimeout(() => {
									this.getSiteList()
								}, 1000)


							} else {
								uni.getSetting({
									success: (resSet) => {
										if (resSet.authSetting['scope.address'] == false) {
											uni.showMode({
												title: '请您打开定位权限',
												content: '用于获取您当前位置附近的油站',
												confirmText: '去设置',
												success: (res) => {
													if (res.confirm) {
														uni.openSetting({

														})
													}
												}
											})
										}
									}
								})
							}
						}
					})
				} else {
					oilSiteApi.getSiteLists(params).then(res => {
						if (res.code == 20000) {
							this.siteList = res.data.list
						}
					})
				}
			},
			toDetail(item) {
				let itemS = encodeURIComponent(JSON.stringify(item))
				// console.log(uni.getStorageSync('user'))
				// return 
				if (uni.getStorageSync('user')) {
					uni.navigateTo({
						url: `/BagStation/pages/stationDetail/stationDetail?item=${itemS}`,
						fail: (err) => {
							// console.log(err)
						},
						success: () => {
							// console.log('err')
						}
					})
				} else {
					uni.showModal({
						title:'请您登录',
						content:"登录中品加油才可以加油 |˛˙꒳​˙)♡",
						confirmText:'去登陆',
						success: (res) => {
							if(res.confirm){
								uni.reLaunch({
									url:'../../../BagAuth/pages/login/login'
								})
							}
						}
					})
				}
			},
			getFilterData() {
				oilSiteApi.getCheckInfo().then(res => {
					if (res.code == 20000) {
						let channelCodes = []
						res.data.channelCodes.map(item => {
							channelCodes.push({
								title: item.name,
								value: item.id
							})
						})
						let productCodes = []
						res.data.productCodes.map(item => {
							productCodes.push({
								title: item.name,
								value: item.id
							})
						})
						let siteBrands = []
						res.data.siteBrands.map(item => {
							siteBrands.push({
								title: item.name,
								value: item.id
							})
						})
						// console.log(channelCodes, productCodes, siteBrands)
						this.menuList[0].detailList.concat(channelCodes)
						this.menuList[1].detailList.concat(productCodes)
						this.menuList[2].detailList.concat(siteBrands)
						uni.setStorageSync('filterData', this.menuList)
						// this.$refs.slFilter.resetMenuList(this.menuList)
					}
				})
			},
			onSelected(res) {
				// console.log(res)
			},
			dateChange(d) {
				uni.showToast({
					icon: 'none',
					title: d
				})
			},
			InputFocus(e) {
				uni.switchTab({
					url: '/pages/tabbar/station/stationList'
				})
			},
			InputBlur(e) {
				this.InputBottom = 0
			},
			nameSelect(value, item) {
				this.title2 = item.text
				// console.log(item)
			},
			typeSelect(value, item) {
				// console.log(item)
				this.title1 = item.text
			},
			optionSelect(value, item) {
				// console.log(item)
				this.title3 = item.text
			},
			// 扫码逻辑开始
			getSiteInfo(id) {
				let data2 = {
					...uni.getStorageSync('location'),
					siteId: id
				}
				oilSiteApi.getSiteDetails(data2).then(res => {
					if (res.code == 20000) {
						this.siteInfo = res.data
						if (res.data.oilSiteChannelDetailsVos.length == 1 && res.data.oilSiteChannelDetailsVos[0]
							.activePay) {
							uni.setStorageSync('tempScanSite', this.siteInfo)
							this.makePay()
						} else {
							this.toDetail(this.siteId)
						}
					}
				})
			},

			makePay() {
				uni.navigateTo({
					url: `/BagStation/pages/makeOrder/makeOrder?siteId=${this.siteId}`
				})
			},
			getScanRes(code) {
				let data2 = {
					qrCode: code
				}
				oilSiteApi.getScanRes(data2).then(res => {
					if (res.code == 20000) {
						this.siteId = res.data.siteId
						this.getSiteInfo(this.siteId)
					}
				})
			},
			scan1() {
				// 测试用
				this.getScanRes('fixed_1371293944539422720')
			},
			openScan() {
				uni.scanCode({
					scanType: 'qrCode',
					onlyFromCamera: false,
					success: (res) => {
						// console.log(res.result)
						this.getScanRes(res.result)
					},
					fail: (err) => {
						uni.showToast({
							title: err
						})
					}
				})
			},
			//结束
			scrollScreen() {
				// console.log('吸顶判断')
				uni.createSelectorQuery().selectViewport().scrollOffset(res => {
					let view = uni.createSelectorQuery().in(this).select(".screentop");
					let cuBar = uni.createSelectorQuery().in(this).select(".cu-bar");
					view.boundingClientRect(data => {
						cuBar.boundingClientRect(dataCu => {
							if (data.top > dataCu.top) {
								uni.pageScrollTo({
									scrollTop: data.top - dataCu.top,
									duration: 0,
								});
							}
						}).exec();
					}).exec();
				}).exec();
			}
		}
	};
</script>

<style scoped>
	.bottom-bar {
		position: relative;
		padding-top: 50px;
		margin-bottom: 0;
		margin-top: 0;
	}

	.main-topbar>>>.cu-bar {
		height: 380rpx !important;
		z-index: 0 !important;
	}

	.main-topbar>>>.cu-bar .content {
		padding-bottom: 300rpx;
	}

	.bottom-bar-fixed {
		position: fixed;
		bottom: 0;
		padding-top: 70rpx;
		width: 100%;
	}

	.main-money {
		position: relative;
		z-index: 1;
	}

	.van-tag {
		display: inline-block;
		padding: 0.3rem 0.4rem;
		position: absolute;
		right: 1px;
		font-size: 12px;
		top: 25%;
		background-color: #b9ffca;
		border-radius: 10rem 0 0 10rem;
		border-color: transparent;
	}

	.screentop {
		min-height: 50vh;
	}

	.cu-list.menu-avatar>.cu-item {
		height: 175rpx;
	}

	.fixed {
		width: 750upx;
		position: fixed;
		z-index: 2;
	}


	.placeholder-hidden {
		opacity: 0;
	}

	.my-icon-sm {
		display: inline-block;
		width: 70upx;
		text-align: center;
		max-height: 70upx;
		overflow: hidden;
	}

	.my-icon-sm .text-sm {
		line-height: 1rem;
	}
</style>
