<template>
	<u-popup :show="visible" mode="center" :round="20" :closeOnClickOverlay="false" :zIndex="99999"
		@close="handleCancel" class="batch-revoke-popup">
		<view class="popup-content">
			<view class="popup-header">
				<text class="popup-title">批量撤回工单</text>
				<view class="close-btn" @click="handleCancel">×</view>
			</view>





			<!-- 工单列表（使用myCard） -->
			<scroll-view class="popup-body" scroll-y @scrolltolower="loadMore">
				<view v-for="(item, idx) in workOrderList" :key="item.id">
					<myCard :item="item" :index="idx + 1" :columns="cardColumns" :title="item.code"
						:status="getStatusText(item.status)" :showRadio="true" selectionMode="multiple"
						:checkboxValue="selectedIds" @radioChange="onRadioChange"
						@checkboxChange="onCheckboxChange" :showDetail="false" />
				</view>
				<view v-if="loading && workOrderList.length === 0" class="empty-tip">
					<u-empty text="加载中..." mode="loading"></u-empty>
				</view>
				<view v-if="!loading && workOrderList.length === 0" class="empty-tip">
					<u-empty text="暂无工单数据"></u-empty>
				</view>
				<view class="loadmore-text" v-if="!isEnd && workOrderList.length > 0">加载更多...</view>
				<view class="loadmore-text" v-if="isEnd && workOrderList.length > 0">没有更多了</view>
			</scroll-view>

			<view class="popup-footer">
				<u-button type="default" @click="handleCancel">取消</u-button>
				<u-button type="primary" :loading="revokeLoading" @click="handleBatchRevoke">
					批量撤回
				</u-button>
			</view>
		</view>
		<u-toast ref="uToast"></u-toast>
	</u-popup>
</template>

<script>
	import myCard from './myCard.vue';
	import {
		producetaskrulerecordQueryRecordWorkOrderPage,
		batchRevokeOrder,
	} from '@/api/recordRules/index';


	export default {
		components: {
			myCard
		},
		props: {
			pageName: {
				type: String,
				default: 'productionRecords',
			},
		},
		data() {
			return {
				visible: false,
				revokeLoading: false,
				planCode: 0,


				selectedIds: [], // 多选选中的id数组
				workOrderList: [],
				page: 1,
				size: 10,
				isEnd: false,
				loading: false,
				searchForm: {
					keyword: '',
					productLineId: '',
					teamId: '',
					status: '',
				},
				dateRange: [],
				teamList: [],
				productLineList: [],
				statusList: [{
						value: 0,
						label: '未报工'
					},
					{
						value: 1,
						label: '执行中'
					},
					{
						value: 2,
						label: '已执行'
					},
				],
				// myCard的列配置（与原来表格列对应）
				cardColumns: [
					[{
						label: '计划单号',
						prop: 'planCode',
						className: 'perce100'
					}],
					[{
						label: '记录规则名称',
						prop: 'ruleName',
						className: 'perce100'
					}],
					[{
							label: '场站名称',
							prop: 'productLineName',
							className: 'perce50'
						},
						{
							label: '班组',
							prop: 'teamName',
							className: 'perce50'
						},
					],
					[{
						label: '工单生成时间',
						prop: 'createTime',
						className: 'perce100'
					}],
					[{
						label: '执行人',
						prop: 'executeUsers',
						className: 'perce100',
						formatter: (row) => row.executeUsers?.map(i => i.userName).join(',') || '',
					}],
				],
				planTypeList: {
					productionRecords: 2,
					steamInjectionInspectionRecord: 3,
					solidWasteRecord: 4,
					qualityTestRecords: 5,
					QualityInspection: 7,
					boilerOperationRecord: 6,
					HaulSlag: 8,
					TransportAsh: 9,
				},
			};
		},
		created() {
			// this.loadTeamList();
			// this.loadProductLineList();
		},
		methods: {
			open(planCode) {
				this.visible = true;
				this.planCode = planCode;
				this.selectedIds = [];
				this.workOrderList = [];
				this.page = 1;
				this.isEnd = false;
				this.searchForm = {
					keyword: '',
					productLineId: '',
					teamId: '',
					status: ''
				};
				this.dateRange = [];
				this.loadWorkOrders();
			},
			setMode(mode) {
				this.selectedIds = [];
			},

			onCheckboxChange({
				checked,
				item,
			}) {
				if (checked) {
					this.selectedIds.push(item.id)
				} else {
					this.selectedIds = this.selectedIds.filter(id => id != item.id)
				}


			},

			async loadWorkOrders() {
				if (this.loading || this.isEnd) return;
				this.loading = true;
				try {
					const params = {
						pageNum: this.page,
						size: this.size,
						keyword: this.searchForm.keyword || this.planCode,
						productLineId: this.searchForm.productLineId,
						teamId: this.searchForm.teamId,
						status: this.searchForm.status !== '' ? this.searchForm.status : 1,
						planType: this.planTypeList[this.pageName],
					};
					if (this.dateRange && this.dateRange.length === 2) {
						params.createTimeStart = this.dateRange[0];
						params.createTimeEnd = this.dateRange[1];
					}
					const res = await producetaskrulerecordQueryRecordWorkOrderPage(params);
					const list = res.list || [];
					if (this.page === 1) {
						this.workOrderList = list;
					} else {
						this.workOrderList.push(...list);
					}
					this.isEnd = list.length < this.size || (this.workOrderList.length >= (res.total || 0));
					this.page++;
				} catch (error) {
					this.$refs.uToast.show({
						type: 'error',
						message: '加载工单失败'
					});
				} finally {
					this.loading = false;
				}
			},
			handleSearch() {
				this.page = 1;
				this.workOrderList = [];
				this.isEnd = false;
				this.loadWorkOrders();
			},
			loadMore() {
				if (!this.isEnd && !this.loading) this.loadWorkOrders();
			},
			getStatusText(status) {
				const map = {
					0: '未报工',
					1: '执行中',
					2: '已执行'
				};
				return map[status] || '';
			},
			handleCancel() {
				this.visible = false;
				this.selectedIds = [];
			},
			async handleBatchRevoke() {
			
				const ids = this.selectedIds
				if (ids.length === 0) {
					this.$refs.uToast.show({
						type: 'warning',
						message: '请至少选择一个工单'
					});
					return;
				}
				this.revokeLoading = true;
				try {
					await batchRevokeOrder(ids);
					this.$refs.uToast.show({
						type: 'success',
						message: `成功撤回 ${ids.length} 个工单`
					});
					this.visible = false;
					this.$emit('refresh');
				} catch (error) {
					console.log(error)
					this.$refs.uToast.show({
						type: 'error',
						message: '撤回失败，请重试'
					});
				} finally {
					this.revokeLoading = false;
				}
			},
		},
	};
</script>

<style lang="scss" scoped>
	.batch-revoke-popup {
		.popup-content {
			width: 90vw;
			max-width: 700px;
			height: 85vh;
			background: #f5f7fb;
			border-radius: 32rpx;
			display: flex;
			flex-direction: column;
			overflow: hidden;
		}

		.popup-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 30rpx;
			background: #fff;
			border-bottom: 2rpx solid #eef2f6;

			.popup-title {
				font-size: 36rpx;
				font-weight: bold;
			}

			.close-btn {
				font-size: 60rpx;
				color: #8e9aae;
			}
		}

		.mode-switch {
			display: flex;
			background: #fff;
			padding: 16rpx 30rpx;
			border-bottom: 2rpx solid #eef2f6;

			.mode-item {
				flex: 1;
				text-align: center;
				font-size: 28rpx;
				padding: 12rpx 0;
				border-radius: 48rpx;
				background: #f5f7fb;
				color: #8e9aae;
				margin-right: 20rpx;

				&.active {
					background: $theme-color;
					color: #fff;
				}

				&:last-child {
					margin-right: 0;
				}
			}
		}

		.search-wrapper {
			background: #fff;
			padding: 20rpx 30rpx;
			border-bottom: 2rpx solid #eef2f6;

			.search-form {
				display: flex;
				flex-wrap: wrap;
				gap: 20rpx;

				>* {
					flex: 1;
					min-width: 200rpx;
				}

				.search_btn {
					width: 140rpx;
					background: $theme-color;
					color: #fff;
					border-radius: 48rpx;
				}
			}
		}

		.popup-body {
			flex: 1;
			overflow-y: auto;
			padding: 20rpx 24rpx;
		}

		.empty-tip {
			margin-top: 100rpx;
		}

		.loadmore-text {
			text-align: center;
			font-size: 26rpx;
			color: #aaa;
			padding: 24rpx 0 40rpx;
		}

		.popup-footer {
			display: flex;
			padding: 20rpx 30rpx 30rpx;
			border-top: 2rpx solid #eef2f6;
			gap: 20rpx;
			background: #fff;

			.u-button {
				flex: 1;
				border-radius: 48rpx;
			}
		}
	}
</style>