<template>
  <view class="page-content sfReport">
    <view class="bg-box">
      <view class="bg-text">
        <view>填写信息</view>
        <view>请您填写相关问题</view>
      </view>
      <image
        class="bg-img"
        src="/static/img/bsorbxBac.png"
        mode="aspectFill"
      ></image>
    </view>
    <view class="info-card">
      <view class="meter-row">
        <view class="meter-label">
          <view style="color: #f93838; margin-right: 4rpx; font-size: 24rpx"
            >*</view
          >
          <text>乐业社区</text>
        </view>
        <view class="picker-label">
          <picker
            mode="selector"
            :range="deptNames"
            @change="onPickerChange($event, '乐业社区')"
          >
            <view
              :style="{ color: !blockForm.apartmentName ? '#cbcbcb' : '' }"
              >{{ blockForm.apartmentName || pickerPlaceholder }}</view
            >
          </picker>
          <image
            class="arrow-r"
            src="/static/img/arrow-right.png"
            mode="aspectFill"
          ></image>
        </view>
      </view>
      <view class="meter-row">
        <view class="meter-label">
          <view style="color: #f93838; margin-right: 4rpx; font-size: 24rpx"
            >*</view
          >
          <text>房屋</text>
        </view>
        <view class="picker-label">
          <view class="uni-list-cell-db" v-if="multiArray[0].length">
            <picker
              mode="multiSelector"
              @columnchange="bindMultiPickerColumnChange"
              :value="multiIndex"
              :range="multiArray"
            >
              <view class="uni-input">{{
                multiArray[0][multiIndex[0]] +
                multiArray[1][multiIndex[1]] +
                multiArray[2][multiIndex[2]]
              }}</view>
            </picker>
          </view>
          <view v-else @click="handleShowToast" style="color: #cbcbcb"
            >请选择社区</view
          >
          <image
            class="arrow-r"
            src="/static/img/arrow-right.png"
            mode="aspectFill"
          ></image>
        </view>
      </view>
    </view>
    <scroll-view class="house-view" scroll-y="true">
      <view class="section-card" v-for="(item, index) in form" :key="index">
        <view class="section-title">{{ item.roomTypeName }}</view>
        <view class="meter-row">
          <view class="meter-label">
            <view style="color: #f93838; margin-right: 4rpx; font-size: 24rpx"
              >*</view
            >
            <text>水表号</text>
          </view>
          <u-input
            v-model="item.waterMeterNumber"
            type="digit"
            placeholder="请输入水表号"
            border="none"
            :disabled="item.isSystemWaterMeterNumber"
            :custom-style="
              item.isSystemWaterMeterNumber ? 'background:#fff;color:#666;' : ''
            "
          />
        </view>
        <!-- <view class="meter-row">
          <view class="meter-label">
            <view style="color: #f93838; margin-right: 4rpx; font-size: 24rpx"
              >*</view
            >
            <text>上次表数</text>
          </view>
          <u-input
            v-model="form[index].lastMeterReading"
            type="digit"
             :placeholder="`上次表数${item.lastMeterReading || ''}`"
            border="none"
            :custom-style="
              form[index].electricMeterNumber
                ? 'background:#fff;color:#bbb;'
                : ''
            "
          />
        </view> -->
        <view class="meter-row">
          <view class="meter-label">
            <view style="color: #f93838; margin-right: 4rpx; font-size: 24rpx"
              >*</view
            >
            <text>本次表数</text>
          </view>
          <u-input
            v-model="form[index].thisMeterReading"
            type="digit"
            placeholder="请输入本次表数"
            border="none"
          />
        </view>
        <view class="meter-row" @click="showTimePicker(index)">
          <view class="meter-label">
            <view style="color: #f93838; margin-right: 4rpx; font-size: 24rpx"
              >*</view
            >
            <text>抄表时间</text>
          </view>
          <view class="picker-label">
            <u-datetime-picker
              :ref="`datetimePicker${index}`"
              :show="form[index].showTimePicker"
              v-model="form[index].meterReadingTime"
              mode="datetime"
              @cancel="closeTimePicker(index)"
              @confirm="(e) => onTimeConfirm(e, index)"
              :min-date="minDate"
              :max-date="maxDate"
            ></u-datetime-picker>
            <view class="time-display">
              {{
                formatDisplayTime(form[index].meterReadingTime) ||
                "请选择抄表时间"
              }}
            </view>
            <image
              class="arrow-r"
              src="/static/img/arrow-right.png"
              mode="aspectFill"
            ></image>
          </view>
        </view>
        <view class="imeter-row">
          <view class="meter-label">
            <view style="color: #f93838; margin-right: 4rpx; font-size: 24rpx"
              >*</view
            >
            <text>上传图片</text>
          </view>
          <u-upload
            :max-count="10"
            :multiple="true"
            :preview-full-image="true"
            :deletable="true"
            :show-upload-list="true"
            :fileList="form[index].fileList || []"
            :auto-upload="false"
            accept="all"
            :maxSize="10 * 1024 * 1024"
            @oversize="oversize"
            @delete="(e) => onDelete(e, index)"
          >
            <view
              class="custom-upload-btn"
              @click.stop="() => chooseMedia(index)"
            >
              <view class="icon-box">
                <image
                  class="camera-icon"
                  src="/static/img/camera-icon.png"
                  mode="aspectFill"
                ></image>
              </view>
              <view class="upload-tips">点击上传</view>
            </view>
          </u-upload>
        </view>
      </view>
    </scroll-view>
    <!-- 提交按钮 -->
    <view class="btn" @click="onSubmit">提交</view>
  </view>
</template>

<script>
import { queryDeptDropdownList } from "@/common/rec";
import { getdeptList } from "@/common/api";
import {
  uploadImage,
  queryLastMeterReading,
  submitWaterAndElectricity,
  getRoomByHouseId,
  getHouseInfo,
} from "@/pages/api";

export default {
  data() {
    return {
      pickerPlaceholder: "请选择", // 初始显示的文字
      waterMeter: 3245.1,
      electricMeter: 2672.6,
      remark: "",
      fileList: [],
      deptNames: [],
      deptOptions: [],
      blockForm: {},
      buildingOptions: [],
      unitOptions: [],
      houseOptions: [],
      multiArray: [[], [], []],
      multiIndex: [0, 0, 0],
      form: [
        {
          meterNumber: "",
          meterType: 2, // 1:电表 2:水表
          houseId: "", // 初始化时可为空，选择房屋后赋值
          roomId: "",
          lastMeterReading: "",
          thisMeterReading: "",
          fileList: [],
          remark: "",
          waterMeterNumber: "",
          isSystemWaterMeterNumber: false, // 是否为系统预设的水表号
          meterReadingTime: "", // 抄表时间
          showTimePicker: false, // 控制时间选择器显示
        },
      ], //
      waterMeterConfig: "",
      minDate: new Date(new Date().getFullYear() - 5, 0, 1).getTime(), // 最小日期：当前时间之前的5年（时间戳）
      maxDate: new Date().getTime(), // 最大日期：当前时间（时间戳）
    };
  },
  watch: {
    "blockForm.apartmentId": {
      handler(newVal, oldVal) {
        console.log("newVal", newVal);
        this.blockForm.buildingId = null;
        this.blockForm.unitId = null;
        this.blockForm.houseId = null;
        this.buildingOptions = [];
        this.unitOptions = [];
        this.houseOptions = [];
      },
      deep: true,
      immediate: true,
    },
  },
  onLoad() {
    this.getTree();
  },
  methods: {
    getTree() {
      getdeptList().then(async (res) => {
        // 直接使用返回的数据，不使用未定义的handleTree方法
        this.deptOptions = res.data || [];
        
        const newArr = this.deptOptions.map((item) => ({
          name: item.deptName,
        }));
        this.deptNames = newArr.map((item) => item.name);
      });
    },
    // 三级联动通用接口
    async getListByParentId(type, id) {
      return new Promise((resolve, reject) => {
        queryDeptDropdownList({ type, id }).then((res) => {
          resolve(res.data);
        });
      });
    },
    async onPickerChange(e, type) {
      if (type == "乐业社区") {
        console.log("e", e);

        const apartmentInfo = this.deptOptions[e.detail.value];
        console.log("社区信息", apartmentInfo);
        console.log("社区信息11", this.deptOptions);

        // 添加数据验证
        if (!apartmentInfo) {
          console.warn("未获取到社区信息");
          return;
        }

        this.blockForm.apartmentName = apartmentInfo.deptName;
        this.blockForm.apartmentId = apartmentInfo.deptId;
        // 楼
        const buildingArray = await this.getListByParentId(
          "2",
          apartmentInfo.deptId
        );
        
        // 验证楼数据
        if (!buildingArray || buildingArray.length === 0) {
          console.warn("未获取到楼信息");
          return;
        }
        
        this.buildingOptions = buildingArray;
        console.log("楼信息", buildingArray);
        const buildingNames = buildingArray.map((item) => item.name);
        console.log("buildingNames:", buildingNames);

        this.blockForm.buildingId = buildingArray[0].id;
        // 单元
        const unitArray = await this.getListByParentId(
          "3",
          buildingArray[0].id
        );
        
        // 验证单元数据
        if (!unitArray || unitArray.length === 0) {
          console.warn("未获取到单元信息");
          return;
        }
        
        this.unitOptions = unitArray;
        console.log("unitArray:", unitArray);

        const unitNames = unitArray.map((item) => item.name);
        this.blockForm.unitId = unitArray[0].id;
        // 户
        const houseArray = await this.getListByParentId("4", unitArray[0].id);
        
        // 验证户数据
        if (!houseArray || houseArray.length === 0) {
          console.warn("未获取到户信息");
          return;
        }
        
        this.houseOptions = houseArray;
        const houseNames = houseArray.map((item) => item.name);
        this.blockForm.houseId = houseArray[0].id;
        this.waterMeterConfig = houseArray[0].waterMeterConfig;


        this.blockForm.roomId = houseArray[0].roomId;
        let house = houseArray[0];
        // for (let index = 0; index < house.type; index++) {
        //   this.form.waterMeters.push({
        //     meterNumber: "",
        //     lastMeterReading: "",
        //     thisMeterReading: "",
        //     imageList: [],
        //     fileList: [],
        //   });
        // }
        this.multiArray = [buildingNames, unitNames, houseNames];
        if (this.waterMeterConfig == 1) {
          this.getHouseInfoBy(this.blockForm.houseId);
        } else if (this.waterMeterConfig == 2) {
          this.getRoomByHouseId(this.blockForm.houseId);
        }
      }
    },
    handleShowToast() {
      uni.showToast({ title: "请选择乐业社区", icon: "none" });
    },
    async bindMultiPickerColumnChange(e) {
      if (!this.multiArray[0].length) return;
      this.multiIndex[e.detail.column] = e.detail.value;
      switch (e.detail.column) {
        case 0:
          {
            const unitArray = await this.getListByParentId(
              "3",
              this.buildingOptions[e.detail.value].id
            );
            
            // 验证单元数据
            if (!unitArray || unitArray.length === 0) {
              console.warn("未获取到单元信息");
              return;
            }
            
            this.unitOptions = unitArray;
            const unitNames = unitArray.map((item) => item.name);
            this.blockForm.unitId = unitArray[0].id;

            const houseArray = await this.getListByParentId(
              "4",
              unitArray[0].id
            );
            
            // 验证户数据
            if (!houseArray || houseArray.length === 0) {
              console.warn("未获取到户信息");
              return;
            }
            
            this.houseOptions = houseArray;
            const houseNames = houseArray.map((item) => item.name);
            this.blockForm.houseId = houseArray[0].id;
            this.blockForm.roomId = houseArray[0].roomId;
            this.multiArray[1] = unitNames;
            this.multiArray[2] = houseNames;
          }
          this.multiIndex.splice(1, 1, 0);
          this.multiIndex.splice(2, 1, 0);
          break;
        case 1:
          {
            const houseArray = await this.getListByParentId(
              "4",
              this.unitOptions[e.detail.value].id
            );
            
            // 验证户数据
            if (!houseArray || houseArray.length === 0) {
              console.warn("未获取到户信息");
              return;
            }
            
            this.houseOptions = houseArray;
            const houseNames = houseArray.map((item) => item.name);
            this.blockForm.houseId = houseArray[0].id;
            this.blockForm.roomId = houseArray[0].roomId;
            this.multiArray[2] = houseNames;
          }
          this.multiIndex.splice(2, 1, 0);
          break;
        case 2: {
          this.blockForm.houseId = this.houseOptions[e.detail.value].id;
          this.blockForm.roomId = this.houseOptions[e.detail.value].roomId;
          this.waterMeterConfig =
            this.houseOptions[e.detail.value].waterMeterConfig;
        }
      }
      
      // 确保在调用方法之前有有效的配置
      if (this.waterMeterConfig && this.blockForm.houseId) {
        if (this.waterMeterConfig == 1) {
          this.getHouseInfoBy(this.blockForm.houseId);
        } else if (this.waterMeterConfig == 2) {
          this.getRoomByHouseId(this.blockForm.houseId);
        }
      }

      this.$forceUpdate();
    },
    //图片超过大小时取消上传
    oversize(e) {
      this.$u.toast("请传10MB以内大小的图片/视频！");
      return false;
    },
    chooseMedia(index) {
      if (!this.form[index].fileList) {
        this.$set(this.form[index], "fileList", []);
      }
      uni.chooseMedia({
        count: 10 - this.form[index].fileList.length,
        mediaType: ["image", "video"],
        sourceType: ["album", "camera"],
        maxDuration: 60,
        camera: "back",
        success: async (res) => {
          uni.showLoading({ title: "上传中...", mask: true });
          try {
            const files = res.tempFiles;
            for (let i = 0; i < files.length; i++) {
              const file = files[i];
              const filePath = file.tempFilePath;
              const type =
                file.fileType ||
                (filePath.match(/\.(mp4|mov|avi|wmv|flv|mkv)$/i)
                  ? "video"
                  : "image");
              // 上传
              const uploadRes = await uploadImage(filePath);
              this.form[index].fileList.push({
                url: uploadRes.data?.url || uploadRes.url || uploadRes.path,
                name: uploadRes.data?.name || uploadRes.name || "",
                type: type,
                status: "success",
              });
            }
            // 更新 imageList
            this.form[index].imageList = this.form[index].fileList.map(
              (v) => v.url
            );
          } catch (e) {
            uni.showToast({ title: "上传失败", icon: "none" });
          } finally {
            uni.hideLoading();
          }
        },
        fail: () => {
          uni.hideLoading();
        },
      });
    },
    async getHouseInfoBy(id) {
      const res = await getHouseInfo(id);
      if (res.code == 200) {
        // 添加安全检查
        if (!res.data) {
          console.warn("未获取到房屋信息");
          return;
        }
        
        if (this.waterMeterConfig == 1) {
          this.getRoomByHouseId(id);
          this.form = [
            {
              waterMeterNumber: res.data.waterMeterNumber || "",
              isSystemWaterMeterNumber: !!(res.data.waterMeterNumber && res.data.waterMeterNumber.trim() !== ''),
              meterReadingTime: this.formatDateTime(new Date()), // 设置默认抄表时间（格式化字符串）
              showTimePicker: false, // 确保时间选择器关闭
            },
          ];
        } else if (this.waterMeterConfig == 2) {
          this.form = this.form.map((item) => ({
            ...item,
            waterMeterNumber: res.data.waterMeterNumber || "",
            isSystemWaterMeterNumber: !!(res.data.waterMeterNumber && res.data.waterMeterNumber.trim() !== ''),
            meterReadingTime: item.meterReadingTime || this.formatDateTime(new Date()), // 确保有抄表时间（格式化字符串）
            showTimePicker: false, // 确保时间选择器关闭
          }));
        }
        this.getLastMeter(res.data.waterMeterNumber);
      }
    },
    // 获取上次抄表
    async getLastMeter(waterMeterNumber) {
      this.initMeterReadingTime();
      console.log(this.form, "this.formgetHouseInfoBy");
        let roomId = ''
      if (this.waterMeterConfig == 1) {
        roomId = this.form[0].id
      }else {
        roomId = this.blockForm.roomId
      }
      const params = {
        houseId: this.blockForm.houseId,
        roomId: roomId,
        meterType: 2, // 2水表
        meterNumber: waterMeterNumber,
      };
      const res = await queryLastMeterReading(params);
      console.log(res.data, "res.data");
      
      // 添加安全检查，确保res.data存在且不为空
      if (!res.data || !Array.isArray(res.data) || res.data.length === 0) {
        console.warn("未获取到水表读数数据");
        return;
      }
      
      if (this.waterMeterConfig == 1) {
        this.form = this.form.map((item) => ({
          ...item,
          lastMeterReading: res.data[0].thisMeterReading || 0,
          waterMeterNumber: res.data[0].meterNumber || "",
          isSystemWaterMeterNumber: !!(res.data[0].meterNumber && res.data[0].meterNumber.trim() !== ''),
          meterReadingTime: item.meterReadingTime || this.formatDateTime(new Date()), // 确保有抄表时间
        }));
      console.log(this.form, "this.formgetLastMeter");

      } else if (this.waterMeterConfig == 2) {
        this.form = this.form.map((item) => {
          const meter = res.data.find(
            (m) => String(m.roomId) === String(item.id)
          );
          if (meter) {
            return {
              ...item,
              lastMeterReading: meter.thisMeterReading || 0,
              waterMeterNumber: meter.meterNumber || "",
              isSystemWaterMeterNumber: !!(meter.meterNumber && meter.meterNumber.trim() !== ''),
              meterReadingTime: item.meterReadingTime || this.formatDateTime(new Date()), // 确保有抄表时间
            };
          }
          return item;
        });
      }
    },
    // 初始化抄表时间
    initMeterReadingTime() {
      const currentTime = this.formatDateTime(new Date());
      console.log("初始化时间:", currentTime);
      console.log("当前时间Date对象:", new Date());
      
      this.form.forEach((item, index) => {
        item.meterReadingTime = currentTime;
        item.showTimePicker = false; // 确保时间选择器关闭
        console.log(`表单项${index}的时间:`, item.meterReadingTime);
        console.log(`表单项${index}的时间类型:`, typeof item.meterReadingTime);
      });
    },
    async getRoomByHouseId(id) {
      const res = await getRoomByHouseId({ houseId: id });
      if (res.code == 200) {
        // 添加安全检查
        if (!res.data || !Array.isArray(res.data) || res.data.length === 0) {
          console.warn("未获取到房间数据");
          return;
        }
        
        if (this.waterMeterConfig == 1) {
          console.log(this.form,"this.formgetRoomByHouseId11");
          
          console.log(res.data,"res.data[0].id");
          
          this.form = this.form.map((item) => ({
            ...item,
            id: res.data[0].id || "",
            meterReadingTime: item.meterReadingTime || this.formatDateTime(new Date()), // 确保有抄表时间
            showTimePicker: false, // 确保时间选择器关闭
          }));
        } else if (this.waterMeterConfig == 2) {
          this.form = res.data.map(item => ({
            ...item,
            meterReadingTime: this.formatDateTime(new Date()), // 为每个房间设置默认抄表时间
            showTimePicker: false, // 确保时间选择器关闭
          })); 
          this.getLastMeter();
        }
      }
    },
    onDelete(event, index) {
      if (this.form[index] && Array.isArray(this.form[index].fileList)) {
        this.form[index].fileList.splice(event.index, 1);
        // this.form.waterMeters[index].imageList = this.form.waterMeters[
        //   index
        // ].fileList.map((v) => v.url);
      }
    },
    onSubmit() {
      let { buildingId, unitId, houseId } = this.blockForm;
      if (!this.blockForm.apartmentName) {
        uni.showToast({ title: "请选择乐业社区", icon: "none" });
        return;
      } else if (!buildingId && !unitId && !houseId) {
        uni.showToast({ title: "请选择房屋", icon: "none" });
        return;
      }
      // 必填校验：水表号、上次表数、本次表数、图片/视频
      for (let i = 0; i < this.form.length; i++) {
        const item = this.form[i];
        if (this.waterMeterConfig == 2) {
          // if (!item.electricMeterNumber) {
          //   uni.showToast({
          //     title: `第${i + 1}个房间请填写水表号`,
          //     icon: "none",
          //   });
          //   return;
          // }
          // if (!item.lastMeterReading && item.lastMeterReading !== 0) {
          //   uni.showToast({
          //     title: `第${i + 1}个房间请填写上次表数`,
          //     icon: "none",
          //   });
          //   return;
          // }
          if (!item.thisMeterReading && item.thisMeterReading !== 0) {
            uni.showToast({
              title: `第${i + 1}个房间请填写本次表数`,
              icon: "none",
            });
            return;
          }
          if (!item.meterReadingTime) {
            uni.showToast({
              title: `第${i + 1}个房间请选择抄表时间`,
              icon: "none",
            });
            return;
          }
          if (!item.fileList || item.fileList.length === 0) {
            uni.showToast({
              title: `第${i + 1}个房间请上传图片/视频`,
              icon: "none",
            });
            return;
          }
        } else {
          //  if (!item.electricMeterNumber) {
          //   uni.showToast({
          //     title: `请填写水表号`,
          //     icon: "none",
          //   });
          //   return;
          // }
          // if (!item.lastMeterReading && item.lastMeterReading !== 0) {
          //   uni.showToast({
          //     title: `请填写上次表数`,
          //     icon: "none",
          //   });
          //   return;
          // }
          if (!item.thisMeterReading && item.thisMeterReading !== 0) {
            uni.showToast({
              title: `请填写本次表数`,
              icon: "none",
            });
            return;
          }
          if (!item.meterReadingTime) {
            uni.showToast({
              title: `请选择抄表时间`,
              icon: "none",
            });
            return;
          }
          if (!item.fileList || item.fileList.length === 0) {
            uni.showToast({
              title: `请上传图片/视频`,
              icon: "none",
            });
            return;
          }
        }
      }
      this.submitAdd();
    },
    async submitAdd() {
      console.log(this.form,"this.form");
      
      // 验证form数据
      if (!this.form || !Array.isArray(this.form) || this.form.length === 0) {
        uni.showToast({
          title: "表单数据无效",
          icon: "none",
        });
        return;
      }
      
      // 验证blockForm数据
      if (!this.blockForm.houseId) {
        uni.showToast({
          title: "房屋信息无效",
          icon: "none",
        });
        return;
      }
      
      let params = this.form.map((item) => {
        // 验证每个表单项
        if (!item) {
          console.warn("表单项数据无效:", item);
          return null;
        }
        
        return {
          meterNumber: item.waterMeterNumber || "",
          meterType: 2,
          houseId: this.blockForm.houseId,
          roomId: item.id || "",
          // lastMeterReading: isNaN(parseFloat(item.lastMeterReading)) ? '' : parseFloat(item.lastMeterReading).toFixed(4),
          lastMeterReading: item.lastMeterReading ? item.lastMeterReading : item.thisMeterReading,
          thisMeterReading: parseFloat(item.thisMeterReading || 0).toFixed(4),
          inputTime: item.meterReadingTime
            ? new Date(item.meterReadingTime.length === 16 ? item.meterReadingTime + ":00" : item.meterReadingTime).getTime()
            : "", // 改为时间戳
          images: (item.fileList || []).map((f) => ({
            url: f.url || "",
            name: f.name || "",
            type: f.type || "",
            format: f.format || (f.url ? f.url.split(".").pop() : ""),
          })),
          remark: item.remark || "",
        };
      }).filter(item => item !== null); // 过滤掉无效的项
      
      // 验证处理后的参数
      if (params.length === 0) {
        uni.showToast({
          title: "没有有效的表单数据",
          icon: "none",
        });
        return;
      }
      
      try {
        const res = await submitWaterAndElectricity(params);
        if (res.code == 200) {
          uni.showToast({
            icon: "success",
            title: "提交成功!",
            success: () => {
              setTimeout(() => {
                uni.switchTab({
                  url: "/pages/tabBar/work/index",
                  success: () => {
                    this.fileList = [];
                  },
                });
              }, 1500);
            },
          });
        } else {
          uni.showToast({
            title: res.msg || "提交失败",
            icon: "none",
          });
        }
      } catch (error) {
        console.error("提交失败:", error);
        uni.showToast({
          title: "提交失败，请重试",
          icon: "none",
        });
      }
    },
    showTimePicker(index) {
      this.form[index].showTimePicker = true; // 打开时间选择器
      
      // 微信小程序需要用此写法设置格式化器
      this.$nextTick(() => {
        const pickerRef = this.$refs[`datetimePicker${index}`];
        if (pickerRef && pickerRef.setFormatter) {
          pickerRef.setFormatter(this.formatter);
        }
      });
    },
    closeTimePicker(index) {
      console.log("关闭时间选择器", index);
      this.form[index].showTimePicker = false; // 关闭时间选择器
    },
    onTimeConfirm(e, index) {
      console.log("时间选择器返回值:", e);
      
      // 处理时间选择器的返回值
      let selectedDate;
      if (e.value) {
        // 如果返回的是时间戳
        selectedDate = new Date(e.value);
      } else if (e.year && e.month && e.day) {
        // 如果返回的是年月日时分对象
        selectedDate = new Date(
          e.year,
          e.month - 1,
          e.day,
          e.hour || 0,
          e.minute || 0
        );
      } else {
        // 其他情况，使用当前时间
        selectedDate = new Date();
      }
      
      // 格式化并保存时间（存储为格式化的字符串）
      const formattedTime = this.formatDateTime(selectedDate);
      this.form[index].meterReadingTime = formattedTime;
      this.form[index].showTimePicker = false; // 关闭时间选择器
      
      console.log("选择的时间戳:", e.value);
      console.log("转换后的Date对象:", selectedDate);
      console.log("格式化后的时间字符串:", formattedTime);
      console.log("表单中存储的时间:", this.form[index].meterReadingTime);
    },
    // 时间格式化器
    formatter(type, value) {
      if (type === "year") {
        return `${value}年`;
      }
      if (type === "month") {
        return `${value}月`;
      }
      if (type === "day") {
        return `${value}日`;
      }
      if (type === "hour") {
        return `${value}时`;
      }
      if (type === "minute") {
        return `${value}分`;
      }
      return value;
    },
    // 格式化时间为 YYYY-MM-DD hh:mm 格式
    formatDateTime(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      const hours = String(date.getHours()).padStart(2, "0");
      const minutes = String(date.getMinutes()).padStart(2, "0");
      return `${year}-${month}-${day} ${hours}:${minutes}`;
    },
    // 格式化时间显示，用于在模板中显示时间
    formatDisplayTime(time) {
      if (!time) return "";
      const date = new Date(time);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      const hours = String(date.getHours()).padStart(2, "0");
      const minutes = String(date.getMinutes()).padStart(2, "0");
      return `${year}-${month}-${day} ${hours}:${minutes}`;
    },
  },
};
</script>

<style scoped>
.page-content {
  background: #f7f7f7;
  min-height: 100vh;
  padding-bottom: 40rpx;
}
.bg-box {
  width: 100vw;
  height: 280rpx;
  object-fit: cover;
  display: block;
  position: relative;
  display: flex;
}
.bg-img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
.bg-text {
  margin: 50rpx 0 0 28rpx;
  z-index: 1;
  font-size: 44rpx;
  color: #101010;
  font-weight: bold;
}
.bg-text view:nth-child(2) {
  font-size: 28rpx;
  color: #666666;
  margin-top: 10rpx;
  font-weight: 400;
}

.info-card {
  background: #fff;
  border-radius: 20rpx;
  margin: -100rpx 24rpx 16rpx 24rpx;
  padding: 24rpx 24rpx 12rpx 24rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.04);
  position: relative;
  z-index: 2;
}
.house-view {
  height: calc(100vh - 600rpx);
}
.room-title {
  font-weight: bold;
  font-size: 32rpx;
  margin-bottom: 16rpx;
}
.info-row {
  font-size: 28rpx;
  color: #222;
  margin-bottom: 8rpx;
}
.label {
  color: #888;
  margin-right: 24rpx;
}
.section-card {
  background: #fff;
  border-radius: 20rpx;
  margin: 0 24rpx 16rpx 24rpx;
  padding: 24rpx;
  z-index: 2;
}
.section-title {
  font-weight: bold;
  font-size: 28rpx;
  margin-bottom: 18rpx;
}
.device-row {
  display: flex;
  align-items: center;
  padding: 0 24rpx;
  min-height: 64rpx;
  border-bottom: 1px solid #f2f2f2;
}
.device-label {
  width: 160rpx;
  color: #222;
  font-size: 28rpx;
  margin-right: 24rpx;
}
.meter-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12rpx;
  /* padding-bottom: 14rpx; */
  padding: 16rpx 0 26rpx;
  border-bottom: 2rpx solid #bbbbbb43;
}
.meter-label {
  display: flex;
  flex-direction: row;
  align-items: center;
  width: 140rpx;
  color: #68758b;
  font-size: 28rpx;
}
.picker-label {
  display: flex;
  align-items: center;
  font-size: 28rpx;
}
.arrow-r {
  width: 30rpx;
  height: 30rpx;
  margin-left: 8rpx;
}
.u-input .u-input__content uni-input {
  text-align: right !important;
}
.u-radio {
  margin-right: 36rpx;
}
.meter-value {
  color: #222;
  font-size: 28rpx;
}
.custom-upload-btn {
  width: 160rpx;
  height: 160rpx;
  background: #fafafa;
  border: 2rpx solid #f0f0f0;
  border-radius: 16rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin: 20rpx 16rpx 0 0;
}
.icon-box {
  width: 60rpx;
  height: 60rpx;
  background: #ceeced;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}
.camera-icon {
  width: 36rpx;
  height: 36rpx;
}
.upload-tips {
  color: #bbb;
  font-size: 24rpx;
  margin-top: 8rpx;
}
.time-display {
  color: #222;
  font-size: 28rpx;
  min-width: 200rpx;
  text-align: right;
  padding: 8rpx 0;
  border: 1px solid transparent;
  border-radius: 8rpx;
  background: #fff;
  padding: 8rpx 16rpx;
}
.u-upload__wrap {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  margin-top: 20rpx;
}
.u-upload__preview {
  border-radius: 16rpx;
  overflow: hidden;
  margin-right: 16rpx;
  margin-bottom: 16rpx;
}
.submit-btn-wrap {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 40rpx 0 0 0;
}

.btn {
  width: 414rpx;
  height: 70rpx;
  line-height: 70rpx;
  border-radius: 600rpx;
  background: linear-gradient(
    86.25deg,
    rgba(13, 198, 198, 1) 3.03%,
    rgba(19, 194, 194, 1) 3.03%,
    rgba(70, 219, 213, 1) 96.43%
  );
  color: rgba(255, 255, 255, 1);
  font-size: 34rpx;
  text-align: center;
  margin: auto;
  margin-top: 40rpx;
}
</style>

<style>
.sfReport .u-input__content__field-wrapper__field {
  text-align: right !important;
}
</style>
