<template>
  <view class="page-content dfReport">
    <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" :scroll-top="scrollTop">
      <view
        class="section-card"
        v-for="(item, index) in form"
        :key="item.id"
        style="margin-bottom: 24rpx"
      >
        <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.electricMeterNumber"
            type="digit"
            placeholder="请输入电表号"
            border="none"
            :disabled="!!item.electricMeterNumber"
            :custom-style="
              item.electricMeterNumber ? 'background:#fff;color:#bbb;' : ''
            "
          />
        </view>
        <!-- :disabled="!!item.lastMeterReading" -->

        <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="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: "",
      deptNames: [],
      deptOptions: [],
      blockForm: {},
      buildingOptions: [],
      unitOptions: [],
      houseOptions: [],
      currentHouse: {},
      multiArray: [[], [], []],
      multiIndex: [0, 0, 0],
      form: [
        {
          meterNumber: "",
          meterType: 1, // 1:电表 2:水表
          houseId: "", // 初始化时可为空，选择房屋后赋值
          roomId: "",
          lastMeterReading: "",
          thisMeterReading: "",
          fileList: [],
          remark: "",
          electricMeterNumber: "",
        },
        // 可以有多个水表对象
      ],
      energyMeterConfig: "",
      waterMeterConfig: "",
    };
  },
  watch: {
    "blockForm.apartmentId": {
      handler(newVal, oldVal) {
        if (newVal !== oldVal) {
          this.blockForm.buildingId = null;
          this.blockForm.unitId = null;
          this.blockForm.houseId = null;
          this.buildingOptions = [];
          this.unitOptions = [];
          this.houseOptions = [];
        }
      },
      deep: true,
      immediate: true,
      apartmentList: [],
    },
  },
  onLoad() {
    this.getTree();
  },
  methods: {
    //图片超过大小时取消上传
    oversize(e) {
      this.$u.toast("请传10MB以内大小的图片/视频！");
      return false;
    },
    getTree() {
      getdeptList().then(async (res) => {
        this.deptOptions = this.handleTree(
          res.data,
          "deptId",
          "parentId",
          "children",
          2
        );
        // const deptInfo = this.deptOptions[0].children.filter(
        //   (item) => item.deptName == "城阳区"
        // )[0];
        const newArr = this.deptOptions.map((item) => ({
          name: item.deptName,
        }));
        // this.deptOptions = newArr
        // this.deptOptions = await this.getListByParentId("1", deptInfo.deptId);
        // const array = JSON.parse(JSON.stringify(this.deptOptions));
        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 == "乐业社区") {
        const apartmentInfo = this.deptOptions[e.detail.value];
        this.blockForm.apartmentName = apartmentInfo.deptName;
        this.blockForm.apartmentId = apartmentInfo.deptId;
        // 楼
        const buildingArray = await this.getListByParentId(
          "2",
          apartmentInfo.deptId
        );
        this.buildingOptions = buildingArray;
        const buildingNames = buildingArray.map((item) => item.name);

        this.blockForm.buildingId = buildingArray[0].id;
        // 单元
        const unitArray = await this.getListByParentId(
          "3",
          buildingArray[0].id
        );
        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);
        this.houseOptions = houseArray;
        const houseNames = houseArray.map((item) => item.name);
        this.blockForm.houseId = houseArray[0].id;
        this.energyMeterConfig = houseArray[0].energyMeterConfig;
        this.waterMeterConfig = houseArray[0].waterMeterConfig;
        let house = houseArray[0];
        this.blockForm.roomId = houseArray[0].roomId;

        // for (let index = 0; index < house.type; index++) {
        //   this.form.waterMeters.push({
        //     waterMeter: "",
        //     imageList: [],
        //     fileList: [],
        //   });
        // }
        this.multiArray = [buildingNames, unitNames, houseNames];
        if (this.energyMeterConfig == 1) {
          this.getHouseInfoBy(this.blockForm.houseId);
        } else if (this.energyMeterConfig == 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
            );
            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
            );
            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;
          } //拖动第1列
          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
            );
            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;
          } //拖动第2列
          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;
          this.energyMeterConfig =
            this.houseOptions[e.detail.value].energyMeterConfig;
        }
      }
      if (this.energyMeterConfig == 1) {
        this.getHouseInfoBy(this.blockForm.houseId);
      } else if (this.energyMeterConfig == 2) {
        this.getRoomByHouseId(this.blockForm.houseId);
      }
      this.$forceUpdate();
    },
    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);
      }
    },
    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,
                format: filePath.split(".").pop() || "",
                status: "success",
              });
            }
          } 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 (this.energyMeterConfig == 1) {
          this.getRoomByHouseId(id);

          this.form = [
            {
              electricMeterNumber: res.data.electricMeterNumber,
            },
          ];
        } else if (this.energyMeterConfig == 2) {
          this.form = this.form.map((item) => ({
            ...item,
            electricMeterNumber: res.data.electricMeterNumber,
          }));
        }
        this.getLastMeter(res.data.electricMeterNumber);
      }
    },
    // 获取上次抄表
    async getLastMeter(item) {
      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: 1,
        meterNumber: item,
      };
      const res = await queryLastMeterReading(params);
      if (this.energyMeterConfig == 1) {
        this.form = this.form.map((item) => ({
          ...item,
          lastMeterReading: res.data[0].thisMeterReading,
          electricMeterNumber: res.data[0].meterNumber,
        }));
      } else if (this.energyMeterConfig == 2) {
        this.form = this.form.map((item) => {
          // 找到 getLastMeter 返回的对应项
          const meter = res.data.find(
            (m) => String(m.roomId) === String(item.id)
          );

          if (meter) {
            return {
              ...item,
              lastMeterReading: meter.thisMeterReading,
              electricMeterNumber: meter.meterNumber,
            };
          }
          return item;
        });
      }
    },
    async getRoomByHouseId(id) {
      const res = await getRoomByHouseId({ houseId: id });
      if (res.code == 200) {
        if (this.energyMeterConfig == 1) {
          this.form = this.form.map((item) => ({
            ...item,
            id: res.data[0].id,
          }));
        } else if (this.energyMeterConfig == 2) {
          this.form = res.data;
          this.getLastMeter();
        }
      }
    },
    onSubmit() {
      let { buildingId, unitId, houseId } = this.blockForm;
      // 检查是否选择了社区
      if (!this.blockForm.apartmentName) {
        uni.showToast({ title: "请选择乐业社区", icon: "none" });
        return;
      }
      // 检查是否选择了房屋
      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.energyMeterConfig == 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.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.fileList || item.fileList.length === 0) {
            uni.showToast({
              title: `请上传图片/视频`,
              icon: "none",
            });
            return;
          }
        }
      }
      this.submitAdd();
    },
    async submitAdd() {
      let params = this.form.map((item) => ({
        meterNumber: item.electricMeterNumber,
        meterType: 1,
        houseId: this.blockForm.houseId,
        roomId: item.id || "",
        lastMeterReading: isNaN(parseFloat(item.lastMeterReading)) ? '' : parseFloat(item.lastMeterReading).toFixed(4),
        thisMeterReading: parseFloat(item.thisMeterReading).toFixed(4),
        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 || "",
      }));
      console.log(params, "params");
      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",
        });
      }
    },
  },
};
</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;
}
.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>
.dfReport .u-input__content__field-wrapper__field {
  text-align: right !important;
}
</style>
