<template>
	<u-popup :show="visible" :round="0" :closeOnClickOverlay="false" :zIndex="99999" @close="handleCancel"
		class="u-popup-my">
		<view class="popup-content">
			<view class="popup-header">
				<text class="popup-title">{{ title }}</text>
				<view class="close-btn" @click="handleCancel">×</view>
			</view>

			<scroll-view class="popup-body" scroll-y>
				<view class="page">
					<view class="card-a">
						<!-- 头部 -->
						<view class="a-header">
							<text class="a-main-title">{{ '抄表记录' }}</text>
							<!-- <view class="a-sub">
                <text>📋 {{ title }}</text>
              </view> -->
						</view>

						<!-- 设备信息 -->
						<view class="card-section">
							<view class="section-title">🔧 设备信息</view>
							<view class="info-grid">
								<view class="info-item">
									<text class="info-label">表计设备名称</text>
									<view class="info-value" :class="{ disabled: isView }"
										@click="!isView && openMaterialAdd()">
										{{ form.substanceName || '请选择' }}
									</view>
								</view>
								<view class="info-item">
									<text class="info-label">表计设备编号</text>
									<view class="info-value disabled">
										{{ form.meterEquipmentNumber || '-' }}
									</view>
								</view>
								<view class="info-item">
									<text class="info-label">用能分类</text>
									<view class="info-value disabled">
										{{ form.energyClassificationName || '-' }}
									</view>
								</view>
								<view class="info-item">
									<text class="info-label">能源名称</text>
									<view class="info-value disabled">
										{{ form.energyTypeName || '-' }}
									</view>
								</view>
								<view class="info-item">
									<text class="info-label">表计单位</text>
									<view class="info-value disabled">
										{{ form.unit || '-' }}
									</view>
								</view>
							</view>
						</view>

						<!-- 抄表信息 -->
						<view class="card-section">
							<view class="section-title">📝 抄表信息</view>
							<view class="info-grid">
								<view class="info-item">
									<text class="info-label">抄表人</text>
									<input class="info-input" v-model="form.meterReadingName" placeholder="请输入抄表人"
										:disabled="true" />
								</view>
								<view class="info-item">
									<text class="info-label">本期抄表时间</text>
									<uni-datetime-picker type="datetime" v-model="form.currentMeterReadingTime"
										returnType="timestamp" :disabled="isView">
										<view class="info-value">
											{{
                        form.currentMeterReadingTime
                          ? dayjs(form.currentMeterReadingTime).format('YYYY-MM-DD HH:mm:ss')
                          : '请选择'
                      }}
										</view>
									</uni-datetime-picker>
								</view>
								<view class="info-item">
									<text class="info-label">本期抄表数</text>
									<input class="info-input" v-model="form.currentMeterReadingNum" type="number"
										placeholder="请输入本期抄表数" :disabled="isView" />
								</view>
							</view>
						</view>
					</view>
				</view>
			</scroll-view>

			<view class="popup-footer">
				<u-button type="default" @click="handleCancel">
					{{ isView ? '关闭' : '取消' }}
				</u-button>
				<u-button type="primary" @click="handleSubmit" v-if="!isView" :loading="loading">确定</u-button>
			</view>
		</view>
		<u-toast ref="uToast"></u-toast>
		<materialDialog ref="materialAddRef" @affirm="handleChooseEquipment"></materialDialog>
	</u-popup>
</template>

<script>
	import {
		save,
		update,
		getById
	} from '@/api/centralizedMeterReading/index.js';
	import dayjs from 'dayjs';
	import {
		energyConsumingUnitList
	} from '@/enum/dict.js';
	import materialDialog from '@/components/MaterialSelector/materialDialog.vue';

	const defForm = {
		id: '',
		substanceId: '',
		substanceName: '',
		substanceCode: '',
		meterEquipmentNumber: '',
		energyClassificationName: '',
		energyTypeName: '',
		unit: '',
		meterReadingName: '',
		meterReadingId: '',
		currentMeterReadingTime: '',
		currentMeterReadingNum: '',
		meterReadingMethod: 1,
	};

	export default {
		name: 'MeterReadingDialog',
		data() {
			return {
				visible: false,
				loading: false,
				title: '新增',
				type: 'add',
				form: {
					...defForm
				},
				dayjs,
			};
		},
		computed: {
			isView() {
				return this.type === 'view';
			},
		},
		components: {
			materialDialog
		},
		methods: {
			// 打开弹窗
			async open(row, type = 'add') {
				this.type = type;
				if (type === 'add') {
					this.title = '新增';
					this.resetForm();
					const currentUser = uni.getStorageSync("userInfo");
					this.form.meterReadingName = currentUser?.name || '';
					this.form.meterReadingId = currentUser?.userId || '';
					this.form.currentMeterReadingTime = dayjs().format('YYYY-MM-DD HH:mm:ss');
				} else {
					this.title = type === 'edit' ? '编辑' : '详情';
					try {
						const res = await getById(row.id);
						this.form = {
							...defForm,
							...res
						};
					} catch (e) {
						console.error('获取详情失败', e);
					}
				}
				this.visible = true;
			},
			// 关闭弹窗
			handleCancel() {
				this.visible = false;
				this.resetForm();
			},
			// 重置表单
			resetForm() {
				this.form = {
					...defForm
				};
			},
			// 打开设备选择（uni-app 中可替换为 navigateTo 或 picker）
			openMaterialAdd() {
				if (this.isView) return;
				// TODO: 接入设备选择页面
				this.$refs.materialAddRef.open()
			},
			// 选择设备回调
			handleChooseEquipment(data) {
				let row = data[0] || {}
				this.form.substanceId = row.id;
				this.form.substanceName = row?.category?.name;
				this.form.substanceCode = row.code;
				this.form.meterEquipmentNumber = row.codeNumber;
				this.form.energyClassificationName = row.energyClassificationName;
				this.form.energyClassificationCode = row.energyClassificationCode;
				this.form.energyTypeName = row.energyTypeName || '';
				this.form.energyTypeId = row.energyTypeId || '';
				this.form.energyTypeCode = row.energyTypeCode || '';

				this.form.unit = energyConsumingUnitList
					.find((item) => item.value == row.energyClassificationCode)
					?.unit.find((item) => item.value == row.energyUnit)?.label;
			},
			// 提交
			async handleSubmit() {
				// 必填校验
				if (!this.form.substanceId) {
					this.$refs.uToast.show({
						type: 'error',
						icon: false,
						message: '请选择表计设备'
					});
					return;
				}
				if (!this.form.meterReadingName) {
					this.$refs.uToast.show({
						type: 'error',
						icon: false,
						message: '请输入抄表人'
					});
					return;
				}
				if (!this.form.currentMeterReadingTime) {
					this.$refs.uToast.show({
						type: 'error',
						icon: false,
						message: '请选择本期抄表时间'
					});
					return;
				}
				if (this.form.currentMeterReadingNum === '' || this.form.currentMeterReadingNum == null) {
					this.$refs.uToast.show({
						type: 'error',
						icon: false,
						message: '请输入本期抄表数'
					});
					return;
				}

				// 时间格式补齐
				const formatTime = (timeStr) => {
					if (!timeStr) return timeStr;
					if (/^\d{4}-\d{2}-\d{2}$/.test(timeStr)) {
						return timeStr + ' 00:00:00';
					}
					return timeStr;
				};
				this.form.currentMeterReadingTime = formatTime(this.form.currentMeterReadingTime);

				const api = this.type === 'edit' ? update : save;
				this.loading = true;
				try {
					await api(this.form);
					this.$refs.uToast.show({
						type: 'success',
						message: this.type === 'edit' ? '编辑成功' : '新增成功',
					});
					this.visible = false;
					this.$emit('refresh');
					this.resetForm();
				} catch (error) {
					console.error(error);
				} finally {
					this.loading = false;
				}
			},
		},
	};
</script>

<style scoped lang="scss">
	.popup-content {
		width: 100vw;
		height: calc(100vh - 100px);
		background: #fff;
		border-radius: 0;
		display: flex;
		flex-direction: column;
		background-color: #eff2f7;
	}

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

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

		.close-btn {
			width: 60rpx;
			height: 60rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 60rpx;
			color: #999;
			line-height: 1;
		}
	}

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

	.page {
		font-family: system-ui, -apple-system, 'Segoe UI', Roboto, Helvetica, sans-serif;
	}

	.card-a {
		background: #ffffff;
		border-radius: 48rpx;
		box-shadow: 0 12rpx 40rpx rgba(0, 0, 0, 0.05);
		overflow: hidden;
	}

	.a-header {
		background: linear-gradient(135deg, #e8f5e9 0%, #f1f8e9 100%);
		padding: 40rpx 32rpx 24rpx;
		text-align: center;
	}

	.a-main-title {
		font-size: 36rpx;
		font-weight: 800;
		color: #2e7d32;
	}

	.a-sub {
		font-size: 24rpx;
		color: #558b2f;
		margin-top: 12rpx;
	}

	.card-section {
		padding: 30rpx 32rpx;
		border-bottom: 2rpx solid #f0f2f5;

		&:last-child {
			border-bottom: none;
		}
	}

	.section-title {
		font-size: 30rpx;
		font-weight: 700;
		color: #1f2a44;
		margin-bottom: 24rpx;
		padding-left: 16rpx;
		border-left: 6rpx solid #4caf50;
	}

	.info-grid {
		display: grid;
		grid-template-columns: 1fr 1fr;
		gap: 28rpx 20rpx;
	}

	.info-item {
		display: flex;
		flex-direction: column;
		gap: 8rpx;
	}

	.info-label {
		font-size: 26rpx;
		font-weight: 600;
		color: #6c7a91;
	}

	.info-value {
		font-size: 28rpx;
		font-weight: 500;
		color: #1e2a3a;
		padding: 16rpx 20rpx;
		border-radius: 24rpx;
		border: 2rpx solid #e9edf2;
		background: #fff;

		&.disabled {
			color: #999;
			background: #f5f5f5;
		}
	}

	.info-input {
		font-size: 28rpx;
		color: #1e2a3a;
		padding: 16rpx 20rpx;
		border-radius: 24rpx;
		border: 2rpx solid #e9edf2;
		background: #fff;
		height: 76rpx;

		&:disabled {
			color: #999;
			background: #f5f5f5;
		}
	}

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

		/deep/ .u-button {
			flex: 1;
		}
	}
</style>