<template>
	<view class="page-list">
		<!-- 头部单位选择 -->
		<view class="filter-header">
			<view class="filter-row">
				<view class="unit-select-btn" >
					<u-input style="color: #333;" v-model="selectUnit.UnitName" :clearable="false" type="select"
						placeholder="请选择单位工程"  @click="handleShowUnit" />
				</view>
				<view class="refresh-btn" @click="handleRefresh">
					<u-icon name="reload" :size="36" :class="{ rotating: loading }"></u-icon>
				</view>
			</view>
		</view>

		<!-- 列表内容 -->
		<scroll-view class="list-scroll" scroll-y @scrolltolower="loadMore" refresher-enabled
			:refresher-triggered="refreshing" @refresh="handleRefresh">
			<view class="list-wrap">
				<view v-for="(item, index) in list" :key="index" class="card-item deliver-card" @click="clickTap(item)">
					<view class="card-header">
						<text class="card-title">{{ item.TrainNumber || '--' }}</text>
						<text class="card-status" :style="{ background: getStatusBg(item.State) }">
							{{ getStatus(item.State) }}
						</text>
					</view>
					<view class="card-body">
						<view class="card-row">
							<text class="row-label">单位名称</text>
							<text class="row-value">{{ item.UnitId || '--' }}</text>
						</view>
						<view class="card-row">
							<text class="row-label">驾驶员</text>
							<text class="row-value">{{ item.DriverName || '--' }}</text>
						</view>
						<view class="card-row">
							<text class="row-label">驾驶员电话</text>
							<text class="row-value">{{ item.DriverPhone || '--' }}</text>
						</view>
						<view class="card-row">
							<text class="row-label">车牌号</text>
							<text class="row-value">{{ item.LicensePlateNumber || '--' }}</text>
						</view>
						<view class="card-row">
							<text class="row-label">联系人</text>
							<text class="row-value">{{ item.ContactName || '--' }}</text>
						</view>
						<view class="card-row">
							<text class="row-label">联系人电话</text>
							<text class="row-value">{{ item.ContactPhone || '--' }}</text>
						</view>
					</view>
				</view>

				<!-- 空状态 -->
				<u-empty v-if="!loading && list.length === 0" mode="list" text="暂无数据"></u-empty>

				<!-- 加载提示 -->
				<view v-if="loading && list.length > 0" class="loading-more">
					<u-loading mode="circle" size="32"></u-loading>
					<text>加载中...</text>
				</view>

				<!-- 没有更多 -->
				<view v-if="!loading && isFinished && list.length > 0" class="no-more">
					<text>— 没有更多了 —</text>
				</view>
			</view>
		</scroll-view>

		<!-- 新增按钮 -->
		<view class="fab-btn" @click="goAdd">
			<u-icon name="plus" :size="60" color="#ffffff"></u-icon>
		</view>
		
		<!-- 单位选择弹窗 -->
		<nbd-select v-model="showUnitSelect" v-model:model="selectUnit" :show-search="true" title="选择单位"
			:list="unitList" label-key="UnitName" value-key="UnitId" @confirm="handleUnitConfirm" />
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted
	} from 'vue'
	import {
		useUserStore
	} from '@/store'
	import {
		storeToRefs
	} from 'pinia'
	import { reqUnitByProjectIdUnitType } from '@/api/base'
import { reqTrainNumberList } from '@/api/hj'

	const userStore = useUserStore()
	const {
		currentProject
	} = storeToRefs(userStore)

	// ===== 数据 =====
	const list = ref([])
	const loading = ref(false)
	const refreshing = ref(false)
	const isFinished = ref(false)
	const pageindex = ref(1)
	const pagesize = 15

	// ===== 单位选择 =====
	const selectUnit = ref({
		UnitId: '',
		UnitName: '全部单位'
	})
	const showUnitSelect = ref(false)
	const unitList = ref([{
		UnitId: '',
		UnitName: '全部单位'
	}])

	// ===== 状态映射 =====
	const getStatus = (val) => {
		const map = {
			'0': '未发货',
			'1': '已发货',
			'2': '已签收'
		}
		return map[String(val)] || '--'
	}

	const getStatusBg = (val) => {
		const colorMap = {
			'0': '#999',
			'1': '#ffa726',
			'2': '#4caf50'
		}
		return `rgba(${val === '0' ? '153,153,153' : val === '1' ? '255,167,38' : '76,175,80'}, 0.1); color: ${colorMap[String(val)] || '#999'}`
	}

	// ===== 单位选择 =====
	const handleShowUnit = async () => {
		const res = await reqUnitByProjectIdUnitType(currentProject.value.ProjectId)
		unitList.value = [{ UnitId: '', UnitName: '全部单位' }, ...(res.data || [])]
		showUnitSelect.value = true
	}

	const handleUnitConfirm = (item) => {
		selectUnit.value = item
		showUnitSelect.value = false
		handleRefresh()
	}

	// ===== 列表数据 =====
	const getList = async () => {
		if (loading.value || (!refreshing.value && isFinished.value)) return

		loading.value = true

		try {
			const res = await reqTrainNumberList({
				projectId: currentProject.value?.ProjectId || '',
				pageIndex: pageindex.value,
				pageSize: pagesize,
				unitId: selectUnit.value?.UnitId || ''
			})

			const data = res.data.getDataList || []

			if (data.length < pagesize) {
				isFinished.value = true
			}

			if (refreshing.value) {
				list.value = data
			} else {
				list.value = [...list.value, ...data]
			}
		} catch (error) {
			console.error('加载数据失败:', error)
			uni.showToast({
				title: '加载失败，请重试',
				icon: 'none'
			})
		} finally {
			loading.value = false
			refreshing.value = false
		}
	}

	// ===== 刷新 =====
	const handleRefresh = () => {
		pageindex.value = 1
		isFinished.value = false
		list.value = []
		getList()
	}

	// ===== 加载更多 =====
	const loadMore = () => {
		if (!loading.value && !isFinished.value) {
			pageindex.value++
			getList()
		}
	}

	// ===== 跳转 =====
	const goAdd = () => {
		uni.navigateTo({
			url: '/pipe/deliver/detail'
		})
	}

	const clickTap = (item) => {
		uni.navigateTo({
			url: `/pipe/deliver/detail?id=${item.Id}&from=1`
		})
	}

	// ===== 生命周期 =====
	onMounted(() => {
		handleRefresh()
	})
</script>
