<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>

						<!-- 设备信息 -->
						<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>
							<u--form labelPosition="left" labelWidth="190rpx" :model="form" :rules="rules"
								ref="formRef">
								<!-- 抄表人 -->
								<u-form-item label="抄表人" prop="meterReadingName" borderBottom>
									<u--input v-model="form.meterReadingName" placeholder="自动带出" disabled
										disabledColor="#f5f5f5" border="none" inputAlign="right" />
								</u-form-item>

								<!-- 本期抄表时间 -->
								<u-form-item label="本期抄表时间" prop="currentMeterReadingTime" borderBottom required>
									<view class="picker-value" @click="!isView && showDateTimePicker()">
										{{
                      form.currentMeterReadingTime
                        ? dayjs(form.currentMeterReadingTime).format('YYYY-MM-DD HH:mm:ss')
                        : '请选择'
                    }}
									</view>
									<u-icon slot="right" name="arrow-right" />
								</u-form-item>
								<!-- 上次抄表数 -->
								<u-form-item label="上次抄表数" prop="lastMeterReadingNum" borderBottom>
									<u--input v-model="form.lastMeterReadingNum" type="number" placeholder="自动获取"
										disabled disabledColor="#f5f5f5" border="none" inputAlign="right" />
								</u-form-item>
								<!-- 本期抄表数 -->
								<u-form-item label="本期抄表数" prop="currentMeterReadingNum" borderBottom required>
									<u--input v-model="form.currentMeterReadingNum" type="number" placeholder="请输入本期抄表数"
										:disabled="isView" border="none" inputAlign="right" @blur="setQuantity" />
								</u-form-item>



								<!-- 本期用量 -->
								<u-form-item label="本期用量" prop="quantity" borderBottom required>
									<u--input v-model="form.quantity" type="number" placeholder="请输入本期用量"
										:disabled="isView" border="none" inputAlign="right" />
								</u-form-item>
							</u--form>
						</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>

		<!-- 日期时间选择器 -->
		<u-datetime-picker :show="showDateTimePopup" v-model="datetimeValue" mode="datetime"
			@confirm="onDateTimeConfirm" @cancel="showDateTimePopup = false" />

		<materialDialog ref="materialAddRef" @affirm="handleChooseEquipment"></materialDialog>
	</u-popup>
</template>

<script>
	import {
		save,
		update,
		getById,
		queryBySubstanceId,
	} 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: '',
		lastMeterReadingNum: '',
		quantity: '',
		meterReadingMethod: 1,
	};

	export default {
		name: 'MeterReadingDialog',
		components: {
			materialDialog,
		},
		data() {
			return {
				visible: false,
				loading: false,
				title: '新增',
				type: 'add',
				form: {
					...defForm
				},
				dayjs,
				// 日期时间选择器
				showDateTimePopup: false,
				datetimeValue: 0,
				// 标记是否手动输入了用量（防止自动计算覆盖用户输入）
				isManualQuantity: false,
				// uView Form 校验规则
				rules: {
					currentMeterReadingTime: {
						required: true,
						message: '请选择本期抄表时间',
						trigger: ['change'],
					},
					currentMeterReadingNum: {
						required: true,
						message: '请输入本期抄表数',
						trigger: ['blur', 'change'],
					},
					quantity: {
						required: true,
						message: '请输入本期用量',
						trigger: ['blur', 'change'],
					},
				},
			};
		},
		computed: {
			isView() {
				return this.type === 'view';
			},
		},
		methods: {
			// ===== 打开弹窗 =====
			async open(row, type = 'add') {
				this.type = type;
				this.isManualQuantity = false;
				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;
				this.$nextTick(() => {
					if (this.$refs.formRef) {
						this.$refs.formRef.setRules(this.rules);
					}
				});
			},

			// ===== 关闭弹窗 =====
			handleCancel() {
				this.visible = false;
				this.resetForm();
				this.showDateTimePopup = false;
				this.isManualQuantity = false;
			},

			// ===== 重置表单 =====
			resetForm() {
				this.form = {
					...defForm
				};
			},

			// ===== 设备选择 =====
			openMaterialAdd() {
				if (this.isView) return;
				this.$refs.materialAddRef.open();
			},

			// ===== 选择设备回调 =====
			async handleChooseEquipment(data) {
				const 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;

				// 设备变更后获取上次抄表数（排除当前记录）
				if (row.id) {
					await this.fetchLastMeterReading();
				}
			},

			// ===== 获取上次抄表数 =====
			async fetchLastMeterReading() {
				if (!this.form.substanceId) return;
				try {
					const data = await queryBySubstanceId(
						this.form.substanceId,
						this.form.id || undefined,
					);
					if (data && data.currentMeterReadingNum !== undefined) {
						this.form.lastMeterReadingNum = data.currentMeterReadingNum;
					} else {
						this.form.lastMeterReadingNum = '';
					}
					// 获取上次抄表数后重新计算本期用量
					this.setQuantity();
				} catch (e) {
					console.error('获取上次抄表数失败', e);
					this.form.lastMeterReadingNum = '';
				}
			},

			// ===== 计算本期用量 =====
			setQuantity() {
				// // 如果用户手动输入了用量，不自动覆盖
				// if (this.isManualQuantity) return;

				const currentNum = parseFloat(this.form.currentMeterReadingNum);
				const lastNum = parseFloat(this.form.lastMeterReadingNum);

				if (!isNaN(currentNum) && !isNaN(lastNum)) {
					const diff = currentNum - lastNum;
					this.form.quantity = diff >= 0 ? diff : 0;
				} else if (!isNaN(currentNum) && isNaN(lastNum)) {
					// 只有本期数，没有上次数，用量 = 本期数
					this.form.quantity = currentNum;
				} else {
					this.form.quantity = '';
				}
			},


			// ===== 日期时间选择器 =====
			showDateTimePicker() {
				if (this.isView || this.loading) return;
				const val = this.form.currentMeterReadingTime;
				this.datetimeValue = val ? new Date(val).getTime() : Date.now();
				this.showDateTimePopup = true;
			},

			onDateTimeConfirm(e) {
				this.showDateTimePopup = false;
				const value = this.$u.timeFormat(e.value, 'yyyy-mm-dd hh:MM:ss');
				this.form.currentMeterReadingTime = value;
				if (this.$refs.formRef) {
					this.$refs.formRef.validateField('currentMeterReadingTime');
				}
			},

			// ===== 提交 =====
			async handleSubmit() {
				try {
					// if (this.$refs.formRef) {
					// 	await this.$refs.formRef.validate();
					// }

					if (!this.form.substanceId) {
						this.$refs.uToast.show({
							type: 'error',
							icon: false,
							message: '请选择表计设备',
						});
						return;
					}
					if (!this.form.currentMeterReadingNum) {
						this.$refs.uToast.show({
							type: 'error',
							icon: false,
							message: '请输入本期抄表数',
						});
						return;
					}
					if (!this.form.quantity) {
						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;
					await api(this.form);
					this.$refs.uToast.show({
						type: 'success',
						message: this.type === 'edit' ? '编辑成功' : '新增成功',
					});
					this.visible = false;
					this.$emit('refresh');
					this.resetForm();
					this.isManualQuantity = false;
				} catch (e) {
					if (e && e.message) {
						this.$refs.uToast.show({
							type: 'error',
							message: e.message
						});
					}
				} 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;
	}

	.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;
		}
	}

	// ===== u--form 样式 =====
	/deep/ .u-form-item {
		padding: 12rpx 0;

		.u-form-item__body__left__label {
			font-size: 26rpx !important;
			color: #6c7a91 !important;
		}

		.u-form-item__body__right__content {
			.u-input__content__field-wrapper__field {
				font-size: 26rpx !important;
				text-align: right;
			}
		}
	}

	.picker-value {
		font-size: 26rpx;
		color: #1e2a3a;
		padding: 8rpx 0;
		text-align: right;
		flex: 1;
		min-height: 44rpx;
	}

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

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