<template>
	<view class="container">
		<!-- 自定义标题 -->
		<uni-nav-bar left-icon="left" left-text="返回" background-color="#537CF7" color="#ffffff" @clickLeft="goBack">
			<text class="navbar-title">应急抢险工单</text>
		</uni-nav-bar>
		<!-- 顶部标签切换 -->
		<view class="top-section">
			<view class="tab" :class="{ active: activeTab === 'pending' }" @click="handleTabChange('pending')">待处理工单</view>
			<view class="divider"></view>
			<view class="tab" :class="{ active: activeTab === 'completed' }" @click="handleTabChange('completed')">已完成工单</view>
		</view>
		<!-- 页面内容 -->
		<view class="content">
			<!-- 内容区域 -->
			<view class="content-main">
				<!-- 时间选择器 -->
				<view>
					<uni-datetime-picker v-model="range" type="daterange" />
				</view>

				<!-- 工单类型选择器 -->
				<view class="filter-section">
					<uni-data-select v-model="value" :localdata="options" placeholder="请选择工单类型" />
					<button class="custom-button" type="primary" size="default" @click="onSearch">查询</button>
				</view>

				<!-- 待处理工单 -->
				<view v-if="activeTab === 'pending'" style="overflow: auto; padding-bottom: 200rpx">
					<view v-if="pendingOrders.length > 0" class="order-list">
						<view
							class="order-item"
							v-for="(item, index) in pendingOrders"
							:key="index"
							@click="navigateToDetail(item)"
							:class="{
								'to-handle': item.status === 0,
								'to-dispatch': item.status === 1
							}"
						>
							<view class="status-tag" :class="getLevelClass(item.gdLevel)">
								{{ item.status === 0 ? '待处理' : '待派发' }}
							</view>

							<view class="form-group">
								<view class="item-form">
									<text>工单地址：</text>
									<text class="item-description">{{ item.address }}</text>
								</view>
								<view class="item-form">
									<text>工单类型：</text>
									<dictTag class="item-description" type="gdlx" :value="item.gdType" />
									<text v-if="item.gdType === 0 && item.xdsqm !== null">-</text>
									<dictTag class="item-description" type="xdsqm" :value="item.xdsqm" />
								</view>
								<view class="item-form">
									<text>影响类型：</text>
									<dict-tag class="item-description" type="yxlx" value="1,2,3" />
								</view>
								<view class="item-form">
									<text>录入时间：</text>
									<text class="item-description">{{ item.createTime }}</text>
								</view>
								<view class="item-form" v-if="item.status === 0">
									<text>处理班组：</text>
									<text class="item-description">{{ item.clbz || '暂无' }}</text>
								</view>
							</view>

							<!-- 待处理的操作 -->
							<view class="actionstwo" v-if="item.status === 0">
								<view class="action-text" @click="handleTransfer(item)">工单转派</view>
								<view class="divider-vertical"></view>
								<view class="action-text" @click="handleFeedback(item)">处理反馈</view>
							</view>

							<!-- 待派发的操作 -->
							<view class="actionsone" v-if="item.status === 1">
								<view class="action-text-center" @click="dispatchOrder(item)">立即指派</view>
							</view>
						</view>
					</view>
					<view v-else class="no-data">暂无数据</view>
				</view>

				<!-- 已完成工单 -->
				<view v-if="activeTab === 'completed'">
					<view v-if="completedOrders.length > 0" class="order-list">
						<view class="order-item to-completed" v-for="(item, index) in completedOrders" :key="index" @click="navigateToDetail(item)">
							<view class="completed status-tag">已完成</view>
							<view class="item-form">
								<text>工单地址：</text>
								<text class="item-description">{{ item.address }}</text>
							</view>
							<view class="item-form">
								<text>工单类型：</text>
								<dictTag class="item-description" type="gdlx" :value="item.gdType" />
								<text v-if="item.gdType === 0 && item.xdsqm !== 'null'">-</text>
								<dictTag class="item-description" type="xdsqm" :value="item.xdsqm" />
							</view>

							<view class="item-form">
								<text>影响类型：</text>
								<dict-tag class="item-description" type="yxlx" value="1,2,3" />
							</view>
							<view class="item-form">
								<text>录入时间：</text>
								<text class="item-description">{{ item.createTime }}</text>
							</view>
							<view class="item-form">
								<text>处理班组：</text>
								<text class="item-description">{{ item.deptName }}</text>
							</view>
							<view class="item-form">
								<text>完成时间：</text>
								<text class="item-description">{{ item.completeTime || '' }}</text>
							</view>
						</view>
					</view>
					<view v-else class="no-data">暂无数据</view>
				</view>

				<!-- 底部按钮 -->
				<view class="bottom-btn">
					<button @click="navigateToPage">立即录入</button>
				</view>
			</view>
		</view>
	</view>
</template>

<style scoped>
.no-data {
	text-align: center;
	color: #999;
	font-size: 28rpx;
	margin-top: 50rpx;
}
</style>

<script setup>
import { ref, onMounted } from 'vue';
import { getDicts } from '@/api/system/dict/data';
import { getEmergencyOrderList, getEmergencyTime } from '@/api/emergency/api';

import dictTag from '@/components/dictTag.vue'; // 字典翻译组件

const activeTab = ref('pending');
const range = ref([]);
const value = ref(null);
const options = ref([]);

const navigateToDetail = (item) => {
	uni.navigateTo({
		url: `/pages/homePage/emergencyDetails?orderId=${item.id}&status=${item.status}`,
		success: () => {
			console.log('跳转成功');
		},
		fail: (err) => {
			console.error('跳转失败', err);
		}
	});
};
// 返回
const goBack = () => {
	uni.navigateBack();
};
// 立即录入
const navigateToPage = () => {
	uni.navigateTo({
		url: '/pages/homePage/emergencyEntry'
	});
};
// 分页参数
const queryParams = ref({
	address: '',
	begainTime: '',
	endTime: '',
	gdLevel: null,
	gdType: null,
	parentId: null,
	status: null,
	yxlx: ''
});

// 数据容器
const pendingOrders = ref([]);
const completedOrders = ref([]);

// 获取工单类型字典
const fetchDicts = async () => {
	const response = await getDicts('gdlx', 'xdsqm', 'yxlx');
	options.value = response.data.map((item) => ({
		value: item.dictValue,
		text: item.dictLabel
	}));
};

// 工单等级样式映射
const getLevelClass = (level) => {
	const levelMap = {
		1: 'high-risk',
		2: 'medium-risk',
		3: 'urgent'
	};
	return levelMap[level] || '';
};

// 查询条件
const onSearch = () => {
	// 更新查询参数
	if (range.value && range.value.length >= 2) {
		queryParams.value.begainTime = range.value[0];
		queryParams.value.endTime = range.value[1];
	} else {
		queryParams.value.begainTime = '';
		queryParams.value.endTime = '';
	}
	queryParams.value.gdType = value.value;

	// 重新加载数据
	loadOrders();
};

// 查询工单数据
const loadOrders = async () => {
	if (activeTab.value === 'pending') {
		queryParams.value.status = 0; // 待处理状态
		const res = await getEmergencyOrderList(queryParams.value);
		if (res.code === 200) {
			pendingOrders.value = res.data?.records || [];
		}
	} else if (activeTab.value === 'completed') {
		queryParams.value.status = 2; // 已完成状态
		const res = await getEmergencyOrderList(queryParams.value);
		if (res.code === 200) {
			// 获取已完成工单列表后，为每个工单获取完成时间
			completedOrders.value = await Promise.all(
				(res.data?.records || []).map(async (order) => {
					try {
						const timeRes = await getEmergencyTime({ GdId: order.id });
						return {
							...order,
							completeTime: timeRes.code === 200 ? timeRes.data[0]?.createTime || '暂无' : '暂无'
						};
					} catch (error) {
						return {
							...order
						};
					}
				})
			);
		}
	}
};

// 切换标签时重新加载数据
const handleTabChange = (tab) => {
	activeTab.value = tab;
	loadOrders();
};

// 页面初始化加载数据
onMounted(() => {
	fetchDicts();
	loadOrders();
});
</script>

<!-- 样式 -->
<style scoped>
.container {
	width: 100%;
	height: 100vh;
	display: flex;
	flex-direction: column;
}

/* 自定义导航栏标题字体 */
.navbar-title {
	font-family: 'Alimama ShuHeiTi-Bold';
	width: 100%;
	height: 100%;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 32rpx;
}

/* 内容区域（自动扩展剩余空间） */
.content {
	flex: 1;
	overflow-y: auto;
	background-color: #ffffff;
}

/* 标签切换样式 */
.top-section {
	display: flex;
	height: 90rpx;
	background-color: #f5f8fd;
	font-size: 32rpx;
	box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.1);
	font-family: 'MiSans-Regular';
	/* position: absolute; */
}

/* 分割线 */
.divider {
	width: 1rpx;
	background-color: #dbe5f4;
	height: 32rpx;
	align-self: center;
}

.tab {
	flex: 1;
	text-align: center;
	padding: 20rpx;
	color: black;
}

.tab.active {
	color: #537cf7;
}

/* 主要内容区域 */
.content-main {
	padding: 24rpx;
}

/* 工单类型选择区域 */
.filter-section {
	display: flex;
	margin-top: 20rpx;
	gap: 5%;
}

.custom-button {
	width: 38%;
	display: flex;
	align-items: center;
	justify-content: center;
	text-align: center;
	line-height: normal;
	font-size: 32rpx;
	background-color: #566dff;
}

/* 工单列表样式 */

.order-list {
	margin-top: 25rpx;
	display: flex;
	flex-direction: column;
	gap: 35rpx;
	width: 100%;
	margin-bottom: 20rpx;
	padding-bottom: 60rpx;
}

.order-item {
	width: 100%;
	height: auto;
	border-radius: 25rpx;
	display: flex;
	flex-direction: column;
	position: relative;
	box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
}

/* 状态标签样式 */
.status-tag {
	width: 28%;
	padding: 10rpx;
	border-top-left-radius: 25rpx;
	border-bottom-right-radius: 120rpx;
	font-size: 30rpx;
	margin-bottom: 15rpx;
	color: white;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
	padding-left: 30rpx;
}

.to-handle .status-tag {
	background-color: #eb4646;
}

.to-dispatch .status-tag {
	background-color: #faad14;
}

.completed {
	background-color: #52c41a;
}

/* 待处理工单背景 */
.to-handle {
	background: linear-gradient(to bottom, #ffdddd, #ffffff);
}

/* 待派发工单背景 */
.to-dispatch {
	background: linear-gradient(to bottom, #fff3dd, #ffffff);
}

/* 已完成工单背景 */
.to-completed {
	background: linear-gradient(to bottom, #ddffdd, #ffffff);
}
/* 工单等级标签基础样式 */
.level-tag {
	display: inline-block;
	padding: 2rpx 16rpx;
	width: 120rpx;
	border-radius: 25rpx;
	text-align: center;
	color: white !important;
	font-size: 28rpx;
	margin-left: 10rpx;
}

/* 高危险（红色） */
.level-tag.high-risk {
	background-color: #eb4646;
}

/* 中危险（黄色） */
.level-tag.medium-risk {
	background-color: #faad14;
}

/* 紧急（深红色） */
.level-tag.urgent {
	background-color: #ff4d4f;
}

/* 工单项样式 */
.form-group {
	margin-top: 10rpx;
}

.item-form {
	display: flex; /* 使用flex布局保持同行 */
	align-items: center; /* 垂直居中 */
	margin: 8rpx 0;
	font-size: 30rpx;
	line-height: 1.5;
	padding-left: 30rpx;
	font-family: 'MiSans-Regular';
	overflow: hidden; /* 隐藏溢出内容 */
	white-space: nowrap; /* 禁止换行 */
}

.item-form text:first-child {
	color: #767d9c;
	font-family: 'MiSans-Regular';
	flex-shrink: 0; /* 防止标签被压缩 */
}

/* 内容部分 */
.item-description {
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
	padding-left: 10rpx;
}

/* 操作文字通用样式 */
.action-text,
.action-text-center {
	color: #566dff;
	font-size: 30rpx;
	text-align: center;
	width: 100%;
	font-family: 'MiSans-Regular';
}

/* 左右分开的文字容器 */
.actionstwo {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin: 20rpx;
	gap: 20rpx;
	margin-top: 40rpx;
	font-family: 'MiSans-Regular';
}

/* 居中的文字容器 */
.actionsone {
	display: flex;
	justify-content: center;
	margin: 30rpx;
	margin-top: 80rpx;
}

/* 垂直分隔线 */
.divider-vertical {
	width: 2rpx;
	height: 40rpx;
	background-color: #566dff;
	opacity: 0.5;
}

/* 居中的文字样式 */
.action-text-center {
	text-align: center;
}
/* 已完成的工单 */
.view-detail {
	background-color: #52c41a;
}
.bottom-btn {
	/* margin-top: 60rpx; */
	position: absolute;
	bottom: 0%;
	padding-bottom: 10rpx;
	width: 94%;
	background-color: #fff;
}
.bottom-btn button {
	color: #ffffff;
	background-color: #566dff;
	height: 76rpx;
	font-size: 30rpx;
}
</style>
