<template>
	<view class="content">
		<view :style="{ marginTop: statusBarHeight }"></view>

		<swiper class="screen-swiper" circular :indicator-dots="bannerConfig.indicatorDots"
			:autoplay="bannerConfig.autoplay" :interval="bannerConfig.interval" :duration="bannerConfig.duration">
			<swiper-item v-for="(item, index) in bannerData" :key="index">
				<image :src="item.image" mode="aspectFill"></image>
			</swiper-item>
		</swiper>
		<uni-card class="navigate_card">
			<uni-notice-bar showIcon :text="noticeData" backgroundColor="#DCFCF1" color="#07D69E" :speed="80"
				class="text-sm">
				<image mode="aspectFit" src="/static/logo.png" class="notice_icon"></image>
			</uni-notice-bar>

			<view class="badge_card_wrap">
				<view class="badge_card_avatar">
					<image class="card_thumbnail" :src="userData?.js?.avatar || '/static/account/avatar.png'"
						mode="aspectFill"
						style="width: 200upx; height: 200upx; border: 4px solid #ccc0cb; border-radius: 50%" />

					<view
						style="font-size: 18px; font-weight: bold; font-family: cursive; padding: 20upx; color: #333; height: 90upx">
						{{ userData?.js?.name }}
					</view>

					<view class="location_wrap">
						<image src="/static/order/location.png" mode="aspectFill" class="location_icon"></image>
						<text class="location_text">
							{{ address?.city? `${address?.province}${address?.city}${address.district}${address.street}` : emptyAddress }}
						</text>
					</view>

					<uni-tag :circle="true" :text="userData?.js ? (userData?.js?.is_work ? '营业' : '休息') : '未登录'"
						:type="userData?.js ? (userData?.js?.is_work ? 'warning' : '') : 'error'" size="small"
						style="position: absolute" />
				</view>
				<view class="badge_card_content">
					<view style="display: flex; justify-content: space-between; padding: 15upx 90upx">
						<uni-tag text="个人信息" type="primary" />
						<view>
							<text style="color: #21925e"
								@tap.stop="handleToUserInfo">{{ userData?.js?.js_status == 1 ? '认证通过' : '立即前往' }}</text>
						</view>
					</view>
					<view style="display: flex; justify-content: space-between; padding: 15upx 90upx">
						<uni-tag text="技师认证" type="primary" />
						<view>
							<text style="color: #21925e"
								@tap.stop="handleToCertification">{{ userData?.js?.js_status == 1 ? '认证通过' : '立即前往' }}</text>
						</view>
					</view>
					<view style="display: flex; justify-content: space-between; padding: 15upx 90upx">
						<view style="width: 200upx">
							<uni-tag text="服务项目" type="primary" />
						</view>
						<view><text style="color: #21925e" @tap.stop="handleToProject">立即前往</text></view>
					</view>
				</view>
				<view class="badge_card_action">
					<button style="background: #f5a625; color: #fff; border-radius: 24upx; width: 160upx"
						class="mini-btn" type="default" size="mini" @tap="handlePostSite">
						定 位
					</button>
					<button style="color: #fff; border-radius: 24upx; width: 160upx"
						:style="{ background: userData?.js?.is_work ? '#E43D33' : '#07d69e' }" class="mini-btn"
						type="default" size="mini" @tap="handleWork">
						{{ userData?.js?.is_work ? '下 钟' : '上 钟' }}
					</button>
				</view>
			</view>
			<uni-grid :column="3" :show-border="false" :square="false" v-if="false">
				<uni-grid-item v-for="(item, index) in navigateData" :index="index" :key="index">
					<view class="grid-item-box" style="background-color: #fff">
						<image mode="aspectFit" :src="item?.icon" class="navigate_icon"></image>
						<text class="navigate_title text-sm">{{ item?.name }}</text>
					</view>
				</uni-grid-item>
			</uni-grid>
		</uni-card>
		<view style="position: relative; top: -60upx">
			<image mode="widthFix" src="/static/common/slogan.png" style="width: 100%; padding: 0 20upx; z-index: 0">
			</image>
		</view>

		<swiper class="screen-swiper" circular :indicator-dots="bannerConfig.indicatorDots"
			:autoplay="bannerConfig.autoplay" :interval="bannerConfig.interval" :duration="bannerConfig.duration"
			style="margin: 0 20upx; min-height: 200upx; height: 200upx; position: relative; top: -40upx" v-if="false">
			<swiper-item v-for="(item, index) in subBannerData" :key="index">
				<image :src="item.image" mode="aspectFill" style="border-radius: 20upx"></image>
			</swiper-item>
		</swiper>

		<uni-grid :column="2" :showBorder="false" style="padding: 0 10upx; position: relative; top: -20upx"
			v-if="false">
			<uni-grid-item v-for="(item, index) in goodsData" :index="index" :key="index">
				<view style="margin: 10upx; overflow: hidden; border-radius: 10upx">
					<image mode="aspectFill" :src="item?.icon"></image>
				</view>
			</uni-grid-item>
		</uni-grid>

		<view class="footer">
			<image mode="widthFix" src="/static/common/footer.png" />
		</view>

		<callAlarm />
	</view>
</template>

<script setup>
	import { ref, reactive } from 'vue';
	import { onLoad, onShow, onPullDownRefresh } from '@dcloudio/uni-app';
	import request from '/common/request.js';
	import getLocation from '/common/getLocation.js';
	import callAlarm from '/components/callAlarm.vue';

	const statusBarHeight = ref(0);
	const bannerConfig = reactive({
		indicatorDots: false,
		autoplay: true,
		interval: 5000,
		duration: 500
	});

	const address = ref({});
	const emptyAddress = ref('未获得定位！请点击定位更换地点');
	const bannerData = ref();
	const subBannerData = ref();
	const noticeData = ref('涉嫌私下交易，禁止技师接单的处罚通知!');
	const goodsData = ref();
	const navigateData = ref([{
			name: '技师认证',
			icon: '/static/index/verify.png'
		},
		{
			name: '开通服务',
			icon: '/static/index/project.png'
		},
		{
			name: '新手教程',
			icon: '/static/index/question.png'
		}
	]);
	const userData = ref();

	const handleWork = () => {
		if (!userData.value) {
			handleToLogin();
			return;
		}

		if (userData.value?.js?.js_status != 1) {
			if (!userData.value?.js?.js_status == 2) {
				uni.showToast({
					title: '请重新进行技师信息认证',
					duration: 1500,
					icon: 'none'
				});
				return;

			}
			uni.showToast({
				title: '请先进行技师信息认证并等待审核结果',
				duration: 1500,
				icon: 'none'
			});
			return;
		}

		uni.showLoading();
		request({
			url: '/api/userjs/setWorkTime',
			method: 'POST',
			data: {
				is_work: !userData.value?.js?.is_work
			},
			success: (res) => {
				console.log('上下钟', res);
				uni.showToast({
					title: res.data.msg,
					duration: 1500,
					icon: 'none'
				});
				if (res.data?.code == 1) {
					setTimeout(() => {
						getUserInfo();
					}, 1000);
				}
			},
			fail: () => {},
			complete: () => {
				uni.stopPullDownRefresh();
				setTimeout(() => {
					uni.hideLoading();
				}, 1500);
			}
		});
	};
	const handlePostSite = async () => {
		if (!userData.value) {
			handleToLogin();
			return;
		}
		const new_address = await getLocation();
		await getGeocode(new_address?.location?.lat, new_address?.location?.lng);
		address.value = uni.getStorageSync('address');
		console.log('获取定位', new_address);
		const latitude = new_address?.location?.lat;
		const longitude = new_address?.location?.lng;

		if (!latitude || !longitude) {
			uni.showToast({
				title: '获取位置失败,请重新定位',
				duration: 1500,
				icon: 'none'
			});
			return;
		}
		uni.showLoading();
		request({
			url: '/api/userjs/addPostSite',
			method: 'POST',
			data: {
				lat: latitude,
				long: longitude,
				nation: new_address?.nation,
				province: new_address?.province,
				city: new_address?.city,
				district: new_address?.district,
				street: new_address?.street,
				street_number: new_address?.street_number
			},
			success: (res) => {
				console.log('添加定位', res);
				if (res.data?.code == 1) {
					uni.showToast({
						title: res.data?.msg,
						duration: 1500,
						icon: 'none'
					});
					// getGeocode(latitude, longitude);
				}
			},
			fail: () => {},
			complete: () => {
				setTimeout(() => {
					uni.hideLoading();
				}, 1500);
			}
		});
	};

	const handleToLogin = () => {
		uni.navigateTo({
			url: '/pages/account/login'
		});
	};
	const handleToUserInfo = () => {
		uni.navigateTo({
			url: '/pages/account/setting'
		});
	};

	const handleToCertification = () => {
		uni.navigateTo({
			url: '/pages/account/certification'
		});
	};

	const handleToProject = () => {
		uni.switchTab({
			url: '/pages/project/index'
		});
	};
	onLoad((option) => {
		statusBarHeight.value = uni.getSystemInfoSync().statusBarHeight;
		initData();
	});
	onShow((option) => {
		uni.$emit('realtimeOrderOpen', false);

		getUserInfo();
		getPostSite();
	});

	const initData = () => {
		const addressStorage = uni.getStorageSync('address');
		if (addressStorage) address.value = addressStorage;
		getInitData();
	};

	const getPostSite = () => {
		request({
			url: '/api/userjs/getPostSite',
			method: 'POST',
			success: (res) => {
				console.log('技师定位数据', res);
				console.log('经纬度', res.data?.data?.lat);
				console.log('经纬度', res.data?.data?.lng);
				if (res.data?.code == 1) {
					const latitude = res.data?.data?.lat;
					const longitude = res.data?.data?.lng;
					if (!address.value?.location || address.value.location.lat !== latitude || address
						.value.location.lng !== longitude)
						getGeocode(latitude, longitude);
					// uni.request({
					// 	url: 'https://restapi.amap.com/v3/geocode/regeo?parameters',
					// 	method: 'GET',
					// 	data: {
					// 		key: '3c813127122a372b7b0a6f0db7eb911e',
					// 		location: `${longitude},${latitude}`
					// 	},
					// 	success: (res) => {
					// 		console.log('高德地址', res);
					// 		address.value = res.data?.regeocode?.formatted_address;
					// 	}
					// });
				}
			},
			fail: () => {},
			complete: () => {}
		});
	};

	const getGeocode = async (latitude, longitude) => {
		return new Promise((resolve, reject) => {
			return uni.request({
				// url: 'https://api.luokuang.com/v2/search/reverse?ak=EE172078158336222860E89C41DA444414EB02CEE4BACDC69FDNZOH2XLMU6557&radius=&lon=117.124909&lat=39.133927&categories=',
				url: `https://api.luokuang.com/v2/search/reverse?ak=EE1720783281948228787B497622B814F58816BB392367AA4EEYF1W3DBFR6557&lon=${longitude}&lat=${latitude}&size=1&coord_type=WGS84`,
				success(res) {
					console.log('逆编译res', res)
					const result = res.data?.result[0]
						?.properties;
					address.value.province = result?.province
					address.value.city = result?.city
					address.value.district = result?.county
					address.value.street = result?.street
					address.value.location = {
						lng: longitude,
						lat: latitude
					};

					console.log('address', address.value)
					uni.setStorageSync('address', address
						.value);
					resolve(res)
				},
				fail: (err) => reject(err),
			})
		});




		return;
		let key = 'd8ee08d704acd692b06fc465d2eb6106'; // 高德WebKey
		// // #ifdef APP-PLUS
		// const system = uni.getSystemInfoSync(); // 获取系统信息
		// if (system.platform === "android")
		// 	key = "d8ee08d704acd692b06fc465d2eb6106"; // "e7703ba0579394ad136d69fb5c8e9920";
		// else
		// 	key = "1b8f006c331a6ac3f2d4df500c5843d2";
		// // #endif

		uni.request({
			url: 'https://restapi.amap.com/v3/geocode/regeo?parameters',
			method: 'GET',
			data: {
				key,
				location: `${longitude},${latitude}`
			},
			success: (res) => {
				console.log('高德地址', res);
				address.value = res.data?.regeocode?.formatted_address;
			}
		});
	};

	const getInitData = () => {
		uni.showLoading();
		request({
			url: '/api/js/index',
			success: (res) => {
				console.log('技师index数据', res);
				if (res.data?.code == 1) {
					bannerData.value = res.data?.data?.banner;
					goodsData.value = res.data?.data?.goods;
					subBannerData.value = res.data?.data?.banner2;
					// navigateData.value = res.data?.data?.nav;
				}
				//   that.arr = res.data.data.goods;
				//   that.banner = res.data.data.banner;
				//   that.banner2 = res.data.data.banner2;
				//   that.nav = res.data.data.nav;
				// that.userInfo = res.data.data;
			},
			fail: () => {},
			complete: () => {
				uni.stopPullDownRefresh();
				uni.hideLoading();
			}
		});
	};

	const getUserInfo = () => {
		uni.showLoading();
		request({
			url: '/api/user/getInfo',
			method: 'GET',
			success: (res) => {
				console.log('客户信息', res);
				if (res.data.code == 1) {
					userData.value = res.data?.data ?? {};
					uni.$emit('fastOrderNum', true);
					uni.$emit('receiveOrdernum', true);
				} else if (res.data.code == 10001) {
					uni.removeStorageSync('token');
					uni.removeStorageSync('id');
					uni.$emit('fastOrderNum', false);
					uni.$emit('receiveOrdernum', false);
				}
			},
			fail: () => {},
			complete: () => {
				uni.hideLoading();
				uni.stopPullDownRefresh();
			}
		});
	};
</script>

<style lang="scss" scoped>
	.uni-noticebar {
		border: 1upx solid #07d69e33;
		border-radius: 8upx;
	}

	.grid-item-box {
		flex: 1;
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 30upx 0 0;

		.navigate_icon {
			width: 100upx;
			height: 100upx;
		}

		.navigate_title {
			// font-size: 29upx;
			color: #333333;
			padding: 10upx 0 10upx;
		}
	}

	.content {
		.navigate_card {
			position: relative;
			top: -40upx;
			background: linear-gradient(to bottom, #ffffff55, #fff);
			padding: 0upx !important;
			margin: 0 20upx !important;
			z-index: 1;

			.uni-noticebar {
				margin-bottom: 0;
			}

			.category_content {
				display: flex;
				justify-content: space-around;
				margin-top: 24upx;

				.category_item_wrap {
					display: flex;
					flex-direction: column;
					align-items: center;

					.category_icon {
						width: 100upx;
						height: 100upx;
						border-radius: 64upx;
					}

					.category_title {
						padding: 16upx 0 8upx;
						font-weight: 400;
						color: #333333;
					}
				}
			}
		}

		.badge_card_wrap {
			position: relative;
			width: 668upx;
			height: 1070upx;
			background: url('/static/index/badge_card_bg.jpg') center center no-repeat;
			background-size: contain;
			border-radius: 24upx;
			margin: 20upx auto;
			box-shadow: 5upx 5upx 10upx 0upx rgba(26, 26, 26, 0.1);

			.badge_card_avatar {
				position: absolute;
				top: 200upx;
				width: 100%;
				display: flex;
				justify-content: center;
				flex-direction: column;
				align-items: center;
			}

			.badge_card_content {
				position: absolute;
				top: 600upx;
				width: 100%;
			}

			.badge_card_action {
				position: absolute;
				width: 100%;
				display: flex;
				justify-content: space-evenly;
				bottom: 50px;

				uni-button {
					&::after {
						border: 0;
					}
				}
			}
		}

		.location_wrap {
			display: flex;
			align-items: center;
			max-width: 600upx;
			height: 100upx;
			overflow: hidden;

			.location_icon {
				width: 32upx;
				height: 32upx;
			}

			.location_text {
				margin-left: 10upx;
				max-width: 550upx;
			}
		}
	}
</style>