<template>
	<view>
		<scroll-view scroll-x class="navigation_wrap">
			<view class="uni-scroll-view-content" :style="{ paddingTop: `${statusBarHeight}px` }">
				<uni-badge class="uni-badge-left-margin" :text="realtimeData[index]?.order_num" absolute="rightTop" size="small" v-for="(item, index) in category" :key="index">
					<view :class="current == index && 'active'" @tap="onChangeTab(index)">
						<view class="box">
							<view class="tab_title">{{ item?.category_name }}</view>
						</view>
						<view class="tab_line"></view>
					</view>
				</uni-badge>
			</view>
		</scroll-view>

		<scroll-view scroll-y v-if="orderData && orderData?.length">
			<view class="card service_wrap" v-for="(item, index) in orderData" :key="index" @tap="handleOrderDetail(item?.id)" :data-id="item.id">
				<view style="position: relative">
					<image class="service_thumbnail" :src="item?.project?.icon" mode="aspectFill" />
					<view
						style="position: absolute; top: 0; font-size: 23upx; width: 250upx; text-align: center; background: #ffffffbb; padding: 10upx; color: red; font-weight: 600"
						v-if="item?.type == 2"
					>
						预约订单
					</view>
				</view>
				<view style="width: 400upx">
					<view class="service_title">
						<text>{{ item?.project?.name }}</text>

						<text class="service_extra_order" style="font-weight: 400; color: #999; font-size: 24upx">
							<text class="service_extra_order_num">≤ {{ item?.distance }}</text>
							Km
						</text>
					</view>
					<view class="service_detail">
						<text>{{ item?.address }}</text>
					</view>
					<view class="service_extra" style="justify-content: space-between">
						<view style="display: flex; align-items: center">
							<image src="/static/common/timer.png" mode="aspectFill" class="service_extra_image" />
							<text class="service_extra_text">{{ item?.minute }}分钟</text>
						</view>
						<view class="service_footer">
							<view class="service_footer_price">
								<text class="text-xs">分成</text>
								<text class="service_footer_price_prefix">￥</text>
								<text>{{ item?.order_price }}</text>
							</view>
						</view>
					</view>
					<view class="service_footer">
						<view class="service_footer_price">
							<text class="service_footer_price_prefix">￥</text>
							<text>{{ item?.price }}</text>
						</view>
						<view>
							<button class="submit_btn disabled_btn" :data-id="item?.id" v-if="isFastSuccess(item)">已抢单</button>
							<button class="submit_btn" :data-id="item?.id" @tap.stop="handleFastOrder" v-else>立即抢单</button>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>
		<view v-else>
			<view class="service_wrap" style="padding: 18upx 0px 10upx; display: flex; flex-direction: column; align-items: center">
				<image mode="widthFix" src="/static/common/no_order.png" class="commend_icon" style="width: 455upx; height: 259upx; margin-top: 20upx" />
				<text style="font-size: 28upx; font-weight: 400; color: #999999; margin-top: 30upx">{{ locationMessage[current] }}</text>
			</view>
		</view>

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

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

const statusBarHeight = ref(0);
const current = ref(0);
const locationMessage = ref([]);
const category = reactive([]);
const address = ref({
	city: null,
	district: null,
	street: null,
	location: {}
});
const realtimeOpen = ref(true);
const realtimeData = ref([]);
const params = reactive({
	page: 1,
	category_id: 0,
	type: 8
});
const orderData = ref([]);
const userData = ref();

function timeStamp(value) {
	const date = new Date(value * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
	const year = date.getFullYear();
	const month = ('0' + (date.getMonth() + 1)).slice(-2);
	const sdate = ('0' + date.getDate()).slice(-2);
	const hour = ('0' + date.getHours()).slice(-2);
	const minute = ('0' + date.getMinutes()).slice(-2);
	const second = ('0' + date.getSeconds()).slice(-2);
	// 拼接
	return `${year}-${month}-${sdate} ${hour}:${minute}`;
}

const getProjectCategory = () => {
	request({
		url: '/api/jsProjectCategory/getList',
		method: 'GET',
		success: (res) => {
			console.log('项目分类', res.data?.data);
			category.push(...res.data?.data);
			params.category_id = res.data?.data[current.value]?.id;
		},
		fail: () => {},
		complete: () => {}
	});
};

const onChangeTab = (index) => {
	console.log('切换选项卡', index);
	locationMessage.value[index] = '';
	if (current.value !== index) {
		current.value = index;
		params.category_id = category[current.value]?.id;
	}
};

const getOrderNumber = () => {
	request({
		url: '/api/userjs/getClassifyOrderNum',
		data: {},
		success: (res) => {
			//console.log(res);
			console.log('实时订单数', res);
			//   that.arrnum = res.data.data;

			if (res.data?.code == 10001) {
				console.log('10001');
				realtimeOpen.value = false;
			}
			if (res.data?.code == 1) {
				realtimeData.value = res.data?.data;
				realtimeOpen.value = true;
			}
		},
		fail: () => {},
		complete: () => {}
	});
};

const handleOrderDetail = (order_id) => {
	uni.navigateTo({ url: `/pages/order/detail?id=${order_id}` });
};
const getUserInfo = () => {
	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);
				uni.showToast({
					title: '登录已失效，请重新登录',
					duration: 2000,
					icon: 'none',
					success: () => {
						uni.navigateTo({
							url: '/pages/account/login'
						});
					}
				});
			}
		},
		fail: () => {},
		complete: () => {}
	});
};

const isFastSuccess = (order) => {
	const fast_number_list = order.fast_number_list;
	let isFast = -1;
	if (fast_number_list && fast_number_list?.length) isFast = fast_number_list.indexOf(userData.value?.js?.id);
	return isFast == -1 ? false : true;
};
const getOrderList = (next = true, showLoading = true) => {
	showLoading && uni.showLoading();
	request({
		url: '/api/userjs/getFastOrderList',
		data: params,
		success: (res) => {
			console.log('订单列表', res);
			if (res.data?.code == 1) {
				orderData.value = res.data?.data;
			}
		},
		fail: () => {},
		complete: () => {
			showLoading && uni.stopPullDownRefresh();
			showLoading && uni.hideLoading();
		}
	});
};

const handleFastOrder = (e) => {
	const id = e.currentTarget.dataset.id;
	uni.showModal({
		title: '提示',
		content: '确定要抢单吗?',
		success(res) {
			// 用户确定要删除
			if (res.confirm) {
				//return
				uni.showLoading({
					content: '加载中',
					mask: true
				});
				request({
					url: '/api/userjs/jeidanPost',
					method: 'POST',
					data: {
						order_id: id
					},
					success: (res) => {
						console.log('快速抢单', res);
						if (res.data?.code == 1) {
							uni.showToast({
								title: '抢单报名成功，等待客户选择',
								duration: 2000,
								icon: 'none'
							});
							getOrderList(false, false);
						} else {
							uni.showToast({
								title: res.data.msg,
								duration: 2000,
								icon: 'none'
							});
						}
					},
					fail: () => {},
					complete: () => {
						setTimeout(() => {
							uni.hideLoading();
						}, 2000);
					}
				});
			}
		}
	});
};

const initLocation = () => {
	statusBarHeight.value = uni.getSystemInfoSync().statusBarHeight;
	const address_storage = uni.getStorageSync('address');
	address.value = address_storage;
	console.log('初始化');
	realtimeOpen.value = true;
	getProjectCategory();
	uni.$on('realtimeOrderOpen', changeRealtimeOpen);
};

const changeRealtimeOpen = (e) => {
	realtimeOpen.value = !!e;
};
const renderData = async () => {
	console.log('渲染');
	realtimeOpen.value = true;
	uni.pageScrollTo({ scrollTop: 0, duration: 0 });
	getOrderList();
	getOrderNumber();
	getUserInfo();
	const realtime = setInterval(() => {
		if (realtimeOpen.value) {
			getOrderNumber();
		} else clearInterval(realtime);
	}, 3000);
	// const new_address = await getLocation();
	// if (new_address) address.value = new_address;
};

onLoad((option) => {
	initLocation();
});
onShow(() => {
	address.value = uni.getStorageSync('address');
	renderData();
});
watch(
	() => params.category_id,
	() => {
		getOrderList();
	}
);

watch(
	() => realtimeOpen.value,
	(newVal) => {
		console.log('newVal', newVal);
	}
);
watch(
	() => realtimeData.value,
	(newVal, oldVal) => {
		console.log('新值', newVal);
		console.log('旧值', oldVal);
		newVal.forEach((element, index) => {
			if (oldVal.length) {
				const old_element = oldVal[index];
				element['id'] == old_element['id'] && element['order_num'] != old_element['order_num'] && current.value == index && getOrderList();
			}
		});
	},
	//深度监听
	{ deep: false }
);
</script>
<style lang="scss" scoped>
.navigation_wrap {
	padding: 20upx 20upx 0upx;

	.uni-badge--x {
		margin: 20upx 0;
	}
}
</style>
