<template>
  <!-- 井道巡检操作 -->
  <view class="container">
    <uni-nav-bar
      :fixed="true"
      background-color="rgba(214, 240, 255, 0.0)"
      status-bar
      rightWidth="300"
    >
      <block slot="left">
        <view class="" @click="back">
          <text class="iconfont icon-fanhui"></text>
        </view>
      </block>
    </uni-nav-bar>
    <!-- Tab 操作区域 -->
    <view class="module">
      <view class="location">{{ location }}</view>

      <scroll-view
        scroll-x
        class="tab-scroll"
        show-scrollbar="false"
        :scroll-left="scrollLeft"
      >
        <view class="tab-buttons">
          <view
            v-for="(tab, index) in tabs"
            :key="index"
            :class="['tab-item', { active: activeTab === index }]"
            @click="switchTab(index)"
            ><text
              v-if="tab.status == 0"
              class="iconfont icon-weixunjian"
            ></text>
            <text v-if="tab.status == 1" class="iconfont icon-wancheng"></text>
            <text v-if="tab.status == 2" class="iconfont icon-shibai1"></text>
            <text class="tab-text">{{ tab.label }}</text>
            <view v-if="activeTab === index" class="underline"></view>
          </view>
        </view>
      </scroll-view>
      <view class="module-box">
        <view class="tip">
          <text class="iconfont icon-tixing"></text
          ><view class="text">
            <view
              class="itemText"
              v-for="(item, index) in tabs[activeTab].text"
              :key="index"
              >{{ item }}</view
            >
          </view>
        </view>
        <view class="tab-content">
          <view class="jfImg">
            <image class="weitu" :src="imgSrc" mode=""></image
          ></view>
          <view class="kong"></view>
          <!-- 操作区域 -->
          <!-- 物理环境 -->
          <wlhj
            v-show="checkValueInArray(tabs, 'wlhj', activeTab)"
            ref="wlhj"
            inspectionItem="物理环境"
            :defaultData="list.wlhj"
          ></wlhj>
          <!-- 安防系统 -->
          <afxt
            v-show="checkValueInArray(tabs, 'afxt', activeTab)"
            ref="afxt"
            inspectionItem="安防系统"
            :defaultData="list.afxt || {}"
          ></afxt>
          <!-- 设备告警 -->
          <sbgj
            v-show="checkValueInArray(tabs, 'sbgj', activeTab)"
            ref="sbgj"
            inspectionItem="设备告警"
            :defaultData="list.sbgj || {}"
          ></sbgj>
          <!-- 电池状态 -->
          <dczt
            v-show="checkValueInArray(tabs, 'dczt', activeTab)"
            ref="dczt"
            inspectionItem="电池状态"
            :defaultData="list.dczt || {}"
            :jfType="jfType"
          ></dczt>
          <!-- 机房温湿度 -->
          <jfwsd
            v-show="checkValueInArray(tabs, 'jfwsd', activeTab)"
            ref="jfwsd"
            inspectionItem="机房温湿度"
            :defaultData="list.jfwsd || {}"
          ></jfwsd>
          <!-- 电力系统 -->
          <dlxt
            v-show="checkValueInArray(tabs, 'dlxt', activeTab)"
            ref="dlxt"
            inspectionItem="电力系统"
            :defaultData="list.dlxt || {}"
          ></dlxt>
          <!-- 消防系统 -->
          <xfxt
            v-show="checkValueInArray(tabs, 'xfxt', activeTab)"
            ref="xfxt"
            inspectionItem="消防系统"
            :defaultData="list.xfxt || {}"
          ></xfxt>
          <!-- 线路情况 -->
          <xlqk
            v-show="checkValueInArray(tabs, 'xlqk', activeTab)"
            ref="xlqk"
            inspectionItem="线路情况"
            :defaultData="list.xlqk || {}"
          ></xlqk>
          <!-- 其它 -->
          <qt
            v-show="checkValueInArray(tabs, 'qt', activeTab)"
            ref="qt"
            inspectionItem="其它"
            :defaultData="list.qt || {}"
          ></qt>
          <!-- 空调系统 -->
          <ktxt
            v-show="checkValueInArray(tabs, 'ktxt', activeTab)"
            ref="ktxt"
            inspectionItem="空调系统"
            :defaultData="list.ktxt"
          ></ktxt>
          <!-- UPS系统 -->
          <upsxt
            v-show="checkValueInArray(tabs, 'upsxt', activeTab)"
            ref="upsxt"
            inspectionItem="UPS系统"
            :defaultData="list.upsxt"
          ></upsxt>
          <!-- 冷通道系统 -->
          <ltdxt
            v-show="checkValueInArray(tabs, 'ltdxt', activeTab)"
            ref="ltdxt"
            inspectionItem="冷通道系统"
            :defaultData="list.ltdxt || {}"
          ></ltdxt>
          <!-- 屏蔽系统 -->
          <pbxt
            v-show="checkValueInArray(tabs, 'pbxt', activeTab)"
            ref="pbxt"
            inspectionItem="屏蔽系统"
            :defaultData="list.pbxt || {}"
          ></pbxt>
          <!-- 除湿机 -->
          <csj
            v-show="checkValueInArray(tabs, 'csj', activeTab)"
            ref="csj"
            inspectionItem="除湿机"
            :defaultData="list.csj || {}"
          ></csj>
          <!-- 内网监管在线平台 -->
          <nwjgzx
            v-show="checkValueInArray(tabs, 'nwjgzx', activeTab)"
            ref="nwjgzx"
            inspectionItem="内网监管在线平台"
            :defaultData="list.nwjgzx || {}"
          ></nwjgzx>
          <!-- 专网监管在线平台 -->
          <zwjgzx
            v-show="checkValueInArray(tabs, 'zwjgzx', activeTab)"
            ref="zwjgzx"
            inspectionItem="专网监管在线平台"
            :defaultData="list.zwjgzx || {}"
          ></zwjgzx>
          <!-- LED屏 -->
          <ledp
            v-show="checkValueInArray(tabs, 'ledp', activeTab)"
            ref="ledp"
            inspectionItem="LED屏"
            :defaultData="list.ledp || {}"
          ></ledp>
        </view>
      </view>
    </view>
    <view class="submit-module">
      <view class="action-btn" @click="submit(0)">暂存</view>
      <view
        v-if="tabs[activeTab].value !== 'qt' || activeTab != tabs.length - 1"
        class="action-btn complete-btn"
        @click="nextTab"
      >
        下一项
      </view>
      <!-- v-if="value > 2" -->
			<view class="action-btn complete-btn" @click="submit(1)"> 完成巡检 </view>
      <!-- <view class="action-btn" @click="normal"> 一键正常 </view> -->
    </view>
    <startDialog
      ref="startDialog"
      :startDialogData="startDialogData"
      @confirm="handleStartDialog"
      @backList="back"
    ></startDialog>
  </view>
</template>

<script>
import assRoomApi from "@/api/assRoom.js";
import inspectApi from "@/api/inspect.js";
import { dataToSql, sqlToData, getHistoryData } from "./shared";

import {
  pad_all_inspection_position,
  tabsInfo1,
  tabsInfo2,
} from "@/utils/dict.js"; //巡检位置，A座到F座 楼层2楼4楼到26楼
import {
  addLog,
  getLogContent,
  LOG_TYPE_ENUM,
  writeInspectionData,
} from "@/utils/IoReadingAndWriting.js";

import { getInspectionDetails } from "@/request/index.js";
import moment from "moment";
import _ from "lodash";
import wlhj from "./components/wlhj.vue"; //物理环境
import afxt from "./components/afxt.vue"; //安防系统
import sbgj from "./components/sbgj.vue"; //设备告警
import dczt from "./components/dczt.vue"; //电池状态
import jfwsd from "./components/jfwsd.vue"; //机房温湿度
import dlxt from "./components/dlxt.vue"; //电力系统
import xfxt from "./components/xfxt.vue"; //消防系统
import xlqk from "./components/xlqk.vue"; //线路情况
import qt from "./components/qt.vue"; //其它
import ktxt from "./components/ktxt.vue"; //空调系统
import upsxt from "./components/upsxt.vue"; //UPS系统
import ltdxt from "./components/ltdxt.vue"; //冷通道系统
import pbxt from "./components/pbxt.vue"; //屏蔽系统
import csj from "./components/csj.vue"; //除湿机
import nwjgzx from "./components/nwjgzx.vue"; //内网监管在线平台
import zwjgzx from "./components/zwjgzx.vue"; //专网监管在线平台
import ledp from "./components/ledp.vue"; //LED屏
import startDialog from "./components/dialog.vue";

export default {
  components: {
    wlhj,
    afxt,
    sbgj,
    dczt,
    jfwsd,
    dlxt,
    xfxt,
    xlqk,
    qt,
    ktxt,
    upsxt,
    ltdxt,
    pbxt,
    csj,
    nwjgzx,
    zwjgzx,
    ledp,
    startDialog,
  },
  data() {
    return {
      location: "",
      value: "",
      dictValue: "",
      inspectionCode: "",
      isSubmitEnabled: false, // 提交按钮是否可点击
      uid: "",
      jfType: "2",
      randomDescription: "这是一段随机说明文字。", // 随机说明文字
      tabs: [],
      activeTab: 0, // 当前选中的 Tab
      inspectionResult: "", // Switch 值（0: 正常, 1: 异常）
      conclusion: "", // 情况摘要
      photos: [], // 现场照片
      historyData: null, // 历史数据
      firstSubmitTime: null, // 首次提交时间
      detailsInfo: {}, // 详情
      baseInfo: {}, // 基础信息
      list: [], //巡检信息
      itemDetail: {},
      backValue: "", //路由来源
      startDialogData: {
        text: [],
        isList: false,
        isLast: false,
      }, //弹窗文案
      listData: [],
      name: "",
      jfType: "2",
      value: "1",
      paramsObjFirst: {},
      all_data: [],
      imgSrc: "",
      // 我新增的
      jfList: [],
      did: "",
      scrollLeft: 0, // 横向滚动位置
      inspectionType: "1",
    };
  },
  computed: {
    userInfo() {
      return this.$store.state.now_user || {};
    },
    canSubmit() {
      const ret = this.allValid(this.getAllChildFormData());
      return !ret;
    },
    // isOperationPermissions() {
    // 	// 是否有操作权限
    // 	const {
    // 		uid,
    // 		createByName
    // 	} = this.detailsInfo;
    // 	return !uid || (uid && createByName == this.userInfo.user);
    // },
  },
  onLoad(options) {
    console.log("option detail", options);
    this.isDisable = options.isDisable == 1 ? true : false;
    this.uid = options.uid;
    this.jfType = options.jfType;
    this.location = options.location;
    this.value = options.value;
    this.dictValue = options.dictValue;
    this.inspectionCode = options.inspectionCode;
    this.backValue = options.backValue || "";
    this.imgSrc = `../../static/img/jf_new/jf${this.value}.png`;

    this.tabs =
      this.jfType === "2" || this.jfType === "3"
        ? this.deepClone(tabsInfo2)
        : this.deepClone(tabsInfo1);
    console.log("机房查看options", options);
    this.all_data = this.$store.state.all_data || [];

    if (options.uid) {
      this.getDetails(options.uid);
    } else if (options.did) {
      this.did = options.did;
      this.init();
      this.paramsObjFirst = this.getAllChildFormData();
      // 临时id
      getHistoryData(this.inspectionType).then((detailsInfo) => {
        console.log("history", detailsInfo);

        if (detailsInfo) {
          delete detailsInfo.id;
					delete detailsInfo.inspectionCode

          // 处理历史数据（选项、文案、照片；异常项-不调出文案及照片）
          this.list = detailsInfo.originData[this.value - 1].details;

          this.inspectionNumber = detailsInfo.inspectionNumber;
          this.inspectionCode = `JFXJ${moment().format("yyyyMMDDHHmmss")}${
            Math.floor(Math.random() * 900) + 100
          }`;

          this.tabs.forEach((item) => {
            if (
              this.list[item.value] &&
              this.list[item.value].status !== undefined
            ) {
              item.status = this.list[item.value].status;
            }
          });
          this.detailsInfo = detailsInfo;

          uni.hideLoading();
        } else {
          this.init();
          this.paramsObjFirst = this.getAllChildFormData();
        }
      });
    } else {
      this.init();
      this.paramsObjFirst = this.getAllChildFormData();
    }
  },
  watch: {},
  mounted() {
    this.itemDetail = this.getAllChildFormData();
    this.getRoomList();
  },
  methods: {
    getRoomList() {
      return assRoomApi.selectRoomList(1).then((res) => {
        console.log("机房列表Content", res);
        this.jfList = res;
        return res;
      });
    },
    // 初始化
    init() {
      console.log("查看tabs", this.tabs);
      return new Promise((resolve, reject) => {
        // 判断是否有回显数据
        // 基础数据
        this.baseInfo = {
          inspectionType: "1",
          inspectionCode: this.inspectionCode,
          recordName: `${moment().format("yyyyMMDD")}-机房日常巡检`,
          inspectionTime: moment().format("yyyy-MM-DD HH:mm"),
          inspectionBy: this.$store.state.now_user.user,
          inspectionById: this.$store.state.now_user.userId,
          createByName: this.$store.state.now_user.user,
          isException: "", // 是否有异常,大于0存在异常
          inspectionNumber: 0, //巡检数量
          floor: this.floor, // 楼层
          isSubmit: "", // 0 是草稿态；  1 是正式提交
          isSign: false, // 是否签字
          signImg: "", // 签字图片地址
          conclusion: "", //摘要
          creatTime: `${new Date().getTime()}`,
          items: [],
        };
        resolve();
      });
    },
    // 回显数据
    getDetails(uid) {
      console.log("getDetails", uid);
      uni.showLoading();
      inspectApi
        .info(uid)
        .then((res) => {
          const detailsInfo = sqlToData(res);

          this.list = detailsInfo.originData[this.value - 1].details;
          this.tabs.forEach((item) => {
            if (
              this.list[item.value] &&
              this.list[item.value].status !== undefined
            ) {
              item.status = this.list[item.value].status;
            }
          });
          console.log("查看tabs2", this.tabs);
          this.detailsInfo = detailsInfo;
          console.log("detailsInfo", detailsInfo);

          this.isDisable = this.isDisable || detailsInfo.synchronization == 1; // 是否禁用 1:已同步数据 0: 未同步数据
          uni.hideLoading();
        })
        .catch((error) => {
          uni.showToast({
            title: error.msg,
            icon: "none",
            duration: 1000,
          });
          uni.hideLoading();
        });
    },
    // 根据数据来判断组件
    checkValueInArray(arr, str, num) {
      for (let i = 0; i < arr.length; i++) {
        if (arr[i].value === str && i === num) {
          return true;
        }
      }
      return false;
    },
    // 处理提交数据
    getParams(isSubmit) {
      console.log("this.getParams", this.uid, this.value);
      console.log("originData", this.detailsInfo.originData);
      if (this.uid || this.did) {
        let posItem = this.detailsInfo.originData[this.value - 1];
        let paramsObj = this.getAllChildFormData(); //获取所有数据
        console.log("获取数据", paramsObj);
        posItem.details = paramsObj;
        posItem.isSubmit = isSubmit;
        if (!this.checkInspectionResult(paramsObj)) {
          posItem.status = 1; //1表示已经巡检过没有异常
          posItem.statusLable = "已巡检";
        } else {
          posItem.status = 2; //1表示已经巡检过有异常
          posItem.statusLable = "巡检异常";
        }
        // 使用 filter 方法筛选出 status 为 1 或 2 的对象
        const inspectedItems = this.detailsInfo.originData.filter(
          (item) => item.status === 1 || item.status === 2
        );

        const isException = this.detailsInfo.originData.some(
          (item) => item.status == 2
        );

        console.log("isException", isException);

        // 获取已经巡检过的数量
        this.detailsInfo.inspectionNumber = inspectedItems.length;

        this.detailsInfo.isException = isException ? 1 : 0;
        this.detailsInfo.submitTime = moment().format("yyyy-MM-DD"); // 记录提交时间
        this.detailsInfo.submitMonth = moment().format("yyyy-MM"); // 记录提交月份
        this.listData = this.detailsInfo.originData;

        let allIsSubmitOne = this.detailsInfo.originData.every(
          (item) => item.isSubmit === 1
        );

        if (!allIsSubmitOne) {
          // 如果有机房没有巡检完,记录是编辑状态
          this.detailsInfo.synchronization = 2;
        } else {
          this.detailsInfo.synchronization = 0;
        }

        return this.detailsInfo;
      } else {
        let baseInfo = this.baseInfo;
        let paramsObj = this.getAllChildFormData(); //获取所有数据
        const roomFeatureMap = {
          1: "1",
          2: "0",
          3: "2",
        };
        let dataObj = this.jfList.map((item, index) => {
          const jfType = roomFeatureMap[item.roomFeature];
          return {
            id: item.id,
            name: item.roomName,
            value: item.dictValue,
            /** 只是为了映射jfType，为了兼容之前的逻辑
             * 前端用的：jfType 机房类型 0屏蔽  1汇聚  2电池间（1） 3电池间（2）
             * roomFeature 机房类型枚举：1.汇聚机房，2.屏蔽机房，3.UPS机房，4.数据机房
             */
            // jfType: item.dictValue == "11" ? "3" : jfType,
						jfType,
            isVaild: false, // 校验通过
            details: this.paramsObjFirst,
            status: item.status,
            refName: `TabContentItem_${index}`,
            statusLable: item.statusLable,
          };
        });
        let tabList = this.deepClone(dataObj);
        let posItem = tabList[this.value - 1];
        posItem.details = paramsObj;
        posItem.isSubmit = isSubmit;
        if (!this.checkInspectionResult(paramsObj)) {
          posItem.status = 1; //1表示已经巡检过没有异常
          posItem.statusLable = "已巡检";
        } else {
          posItem.status = 2; //1表示已经巡检过有异常
          posItem.statusLable = "巡检异常";
        }
        const data = {
          ...baseInfo,
          isSubmit: isSubmit, //0暂存(编辑中) 1提交（待同步，已同步）
          inspectionNumber: 1,
          isException: posItem.status == 2 ? 1 : 0,
          items: [],
          synchronization: 0, // 是否同步过
          submitTime: moment().format("yyyy-MM-DD"), // 记录提交时间
          submitMonth: moment().format("yyyy-MM"), // 记录提交月份
          originData: tabList, //所有大楼和楼层的数据
        };
        /**记录的isSubmit0暂存(编辑中) 1提交（待同步，已同步）
         * 得检测每个机房是否巡检完
         */
        let allIsSubmitOne = data.originData.every(
          (item) => item.isSubmit === 1
        );
        if (!allIsSubmitOne) {
          // 如果有机房没有巡检完,记录是编辑状态
          data.synchronization = 2;
        } else {
          this.detailsInfo.synchronization = 0;
        }
        console.log("getParams", data);
        this.listData = data.originData;
        return data;
      }
    },
    deepClone(target) {
      if (typeof target !== "object" || target === null) {
        return target;
      }

      let clone;
      if (Array.isArray(target)) {
        clone = [];
        for (let i = 0; i < target.length; i++) {
          clone[i] = this.deepClone(target[i]);
        }
      } else {
        clone = {};
        for (const key in target) {
          if (target.hasOwnProperty(key)) {
            clone[key] = this.deepClone(target[key]);
          }
        }
      }

      return clone;
    },
    count(originData) {
      return originData.reduce(
        (acc, curr) => {
          curr.position.forEach((item) => {
            if (item.status !== 0) {
              acc.notZeroCount++; // 统计 status 不为 0 的数量
            }
            if (item.status === 2) {
              acc.equalTwoCount++; // 统计 status 等于 2 的数量
            }
          });
          return acc;
        },
        {
          notZeroCount: 0,
          equalTwoCount: 0,
        } // 初始化统计结果
      );
    },
    typeSubmit(originData) {
      return originData.reduce((acc, curr) => {
        return (
          acc +
          curr.position.reduce((innerAcc, innerCurr) => {
            return innerCurr.status === 0 ? innerAcc + 1 : innerAcc;
          }, 0)
        );
      }, 0);
    },
    // 判断数据是否有异常
    checkInspectionResult(data) {
      // 遍历每个检查项类别（如 wlhj, afxt 等）
      for (const category in data) {
        const categoryData = data[category];

        // 如果发现任意一个 inspectionResult 为 1，立即返回 true（异常）
        if (categoryData.status === 2) {
          return true;
        }
      }

      // 所有 inspectionResult 都为 0，返回 false（正常）
      return false;
    },
    realSave(data) {
      const send = dataToSql(data);
      const api = this.uid ? inspectApi.update : inspectApi.save;
      return api(this.uid ? { id: this.uid, ...send } : send).then((res) => {
        if (!this.uid) {
          this.uid = res.lastInsertId;
          setTimeout(() => {
            this.getDetails(res.lastInsertId);
          }, 300);
        }
        console.log("保存成功", res);
      });
    },
    // 提交
    submit(isSubmit = 1) {
      console.log("提交时查看一下数据", this.getAllChildFormData());
      let allValid = this.allValid(this.getAllChildFormData());
      // 校验是否通过
      if (isSubmit && !allValid) {
        uni.showToast({
          title: "请填写完整必填项",
          icon: "none",
        });
        return false;
      }
      const params = this.getParams(isSubmit); //数据获取
      console.log("提交时获取一次", params);
      this.all_data = this.$store.state.all_data || [];
			
			params.inspectionCode = this.inspectionCode || `JFXJ${moment().format("yyyyMMDDHHmmss")}${
				Math.floor(Math.random() * 900) + 100
			}`
      params.inspectionType = this.inspectionType;

      this.realSave(params).then(() => {
        let logContent = "";
        console.log("all_data", this.all_data);
        if (this.uid) {
          const index = this.all_data.findIndex(
            (element) => element.uid == this.uid
          );
          params.uid = this.uid;

          this.all_data[index] = params;
          logContent = getLogContent(
            LOG_TYPE_ENUM.edit,
            `巡检编号(${params.inspectionCode})`,
            "巡检模块"
          );
        } else {
          this.all_data.push(params);
          logContent = getLogContent(
            LOG_TYPE_ENUM.add,
            `巡检编号(${params.inspectionCode})`,
            "巡检模块"
          );
        }
        // 更新巡检list
        const userInfo = this.userInfo;
        console.log("all_data存储", this.all_data);
        this.$store.commit("SET_ALL_DATA", this.all_data);
        const inspectList = this.all_data.filter(
          (item) => item.createByName == userInfo.user
        );

        console.log("inspectList", inspectList);
        writeInspectionData(inspectList, userInfo.user);

        // 更新日志
        const log_list = this.$store.state.log_list;
        logContent.inspectionType = params.inspectionType;
				this.$logApi.addlog(logContent)
        console.log("logContent", logContent);
        log_list.push(logContent);

        this.$store.commit("SET_LOG_LIST", log_list);

        addLog(log_list).then((res) => {
          console.log("日志文件写入成功");
        });

        if (isSubmit) {
          this.startDialog();
        } else {
          uni.showToast({
            title: "暂存成功",
            icon: "none",
          });
        }
      });
    },
    startDialog() {
      let allIsSubmitOne = this.listData.every((item) => item.isSubmit === 1);
      this.allIsSubmitOne = allIsSubmitOne;
      console.log("是否全部完成", allIsSubmitOne);
      console.log("this.listData", this.listData);

      // let item = this.findTargetObject(this.listData);

      const item = this.listData.find(
        (item) => !item.status || item.isSubmit == 0
      );
      console.log("即将操作的机房", item);

      this.name = item && item.name ? item.name : "";
      this.jfType = item && item.name ? item.jfType : "";
      this.value = item && item.name ? item.value : "";
      if (!allIsSubmitOne) {
        this.startDialogData.text = [
          `当前机房已巡检完毕，`,
          `请到“${this.name}”`,
        ];
      } else {
        this.startDialogData.text = [
          `本次巡检任务已全部完成，`,
          "请“返回巡检列表”进行签名及数据同步",
        ];
        this.startDialogData.isLast = true;
      }
      this.$refs.startDialog.open();
    },
    // 处理弹窗确认
    handleStartDialog() {
      console.log("跳转前", this.uid);
      uni.navigateTo({
        url: `/pages/inspectionContent/inspectionContentNew?value=${this.value}&inspectionCode=${this.inspectionCode}&jfType=${this.jfType}&location=${this.name}&uid=${this.uid}&backValue=${this.backValue}`,
      });
    },
    findTargetObject(rows) {
      if (!rows || rows.length === 0) return null;

      let lastNonZeroIndex = -1;

      // 首先检查所有对象，记录最后一个 status 不为 0 的索引
      for (let i = 0; i < rows.length; i++) {
        if (rows[i].status !== 0) {
          lastNonZeroIndex = i;
        }
      }

      // 如果没有找到任何 status 不为 0 的对象，返回 null
      if (lastNonZeroIndex === -1) return null;

      // 计算目标对象的索引
      let targetIndex = lastNonZeroIndex + 1;

      // 如果最后一个非零对象是数组的最后一个元素，则从第一个对象开始检查
      if (lastNonZeroIndex === rows.length - 1) {
        for (let i = 0; i < rows.length; i++) {
          if (rows[i].status !== 0) {
            targetIndex = i + 1;
            break; // 找到第一个就停止
          }
        }

        // 如果 targetIndex 超出数组范围，则返回 null
        return targetIndex < rows.length ? rows[targetIndex] : null;
      }

      // 正常情况：返回最后一个非零对象的下一个对象
      return rows[targetIndex];
    },
    // 获取子组件数据
    getAllChildFormData() {
      // 获取所有子组件实例
      const allData = {};

      // 遍历 ref 名称数组
      this.tabs.forEach((item) => {
        console.log("item.value", item.value);
        let refName = item.value;
        // 通过 this.$refs[refName] 获取子组件实例
        const childComponent = this.$refs[refName];
        if (childComponent && childComponent.getFromData) {
          // 调用子组件的 getFromData 方法，获取数据
          allData[refName] = childComponent.getFromData();
        }
      });
      // console.log("wlhj",this.$refs["wlhj"].getFromData())
      // console.log("afxt",this.$refs["afxt"].getFromData())
      // console.log("dlxt",this.$refs["dlxt"].getFromData())
      // console.log("所有子组件的数据:", allData);
      return allData;
    },
    // 判断所有的数据是否通过校验
    allValid(parentObj) {
      // 遍历对象的所有属性
      for (let key in parentObj) {
        // 确保属性是对象自身的（而非继承的）
        if (parentObj.hasOwnProperty(key)) {
          // 检查 isValid 属性是否为 false
          if (parentObj[key].isValid === false) {
            return false; // 如果有一个为 false，直接返回 false
          }
        }
      }
      return true; // 如果全部为 true，返回 true
    },
    // 检查所有Tab 的必填项是否填写完整
    isAllTabValid() {
      const data = this.list;
      // 校验函数
      const validateData = (data) => {
        return data.every(
          (item) =>
            item.inspectionResult !== null && item.conclusion.trim() !== ""
        );
      };
      // 调用校验函数
      const isValid = validateData(data);
      return isValid;
    },
    normal() {
      this.tabs.forEach((item) => {
        console.log("item.value", item.value);
        let refName = item.value;
        // 通过 this.$refs[refName] 获取子组件实例
        const childComponent = this.$refs[refName];
        if (childComponent && childComponent.setNormal) {
          childComponent.setNormal();
        }
      });

      this.tabs.forEach((tab, index) => {
        if (index !== this.tabs.length - 1) {
          tab.status = 1;
        }
      });
    },
    // 下一项
    nextTab() {
      // if (!this.isCurrentTabValid()) {
      //   uni.showToast({
      //     title: "请填写完整必填项",
      //     icon: "none",
      //   });
      //   return false;
      // }
      let data = this.getAllChildFormData();
      this.tabs[this.activeTab].status =
        data[this.tabs[this.activeTab].value].status;
      if (this.activeTab === this.tabs.length - 1) {
        this.isSubmitEnabled = true;
      } else {
        this.switchTab(this.activeTab + 1);
      }
    },
    // 切换 Tab
    switchTab(index) {
      let data = this.getAllChildFormData();
      this.tabs[this.activeTab].status =
        data[this.tabs[this.activeTab].value].status || 0;
      this.activeTab = index;
      if (this.activeTab !== this.tabs.length - 1) {
        this.isSubmitEnabled = false;
      }

      // 滚动到目标 tab 位置
      this.$nextTick(() => {
        this.scrollToTab(index);
      });
    }, // 设置巡检结论
    setInspectionResult(value) {
      console.log("设置巡检结论", value);
      this.inspectionResult = value;
      this.list[this.activeTab].inspectionResult = value; // 更新当前 Tab 的数据
    },
    // 滚动到目标 tab
    scrollToTab(index) {
      uni
        .createSelectorQuery()
        .in(this)
        .select(`.tab-item:nth-child(${index + 1})`)
        .boundingClientRect((data) => {
          if (!data) return;

          uni
            .createSelectorQuery()
            .in(this)
            .select(".tab-scroll")
            .boundingClientRect((scrollData) => {
              if (!scrollData) return;

              // 获取当前滚动位置
              uni
                .createSelectorQuery()
                .in(this)
                .select(".tab-scroll")
                .scrollOffset((res) => {
                  const scrollLeft = res.scrollLeft || 0;

                  // 计算目标 tab 在滚动容器中的位置
                  const targetLeft = data.left;
                  const itemWidth = data.width;
                  const scrollWidth = scrollData.width;

                  let newScrollLeft = scrollLeft;

                  // 判断是否需要滚动
                  if (targetLeft < 10) {
                    // 目标在左侧，向左滚动
                    newScrollLeft = Math.max(0, scrollLeft + targetLeft - 10);
                  } else if (targetLeft + itemWidth > scrollWidth - 10) {
                    // 目标在右侧，向右滚动
                    newScrollLeft =
                      scrollLeft + (targetLeft + itemWidth - scrollWidth + 10);
                  }

                  // 执行滚动
                  if (newScrollLeft !== scrollLeft) {
                    uni.pageScrollTo({
                      scrollTop: 0,
                      duration: 0,
                    });

                    // 使用 scroll-view 的 scroll-left 属性
                    this.scrollLeft = newScrollLeft;
                  }
                })
                .exec();
            })
            .exec();
        })
        .exec();
    },
    // 返回
    back() {
      uni.navigateTo({
        url: `/pages/inspectionContent/inspectionContentList?uid=${this.uid}&backValue=${this.backValue}&value=${this.value}`,
      });
    },
    // 关闭弹窗
    closePopup() {
      this.switchTab((this.activeTab + 1) % this.tabs.length);
    },
  },
};
</script>
<style scoped lang="less">
.uni-nav-bar-text {
  height: 28.8px;
  width: 28.8px;
  background: #ffffff;
  border: 0.32px solid rgba(224, 224, 224, 1);
  border-radius: 14.4px;
  color: #333;
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;

  .iconfont {
    font-size: 16px;
    line-height: 28.8px;
  }
}

.container {
  padding: 19.2px;
  height: calc(100vh - 160px);
}
.module {
  background: #ffffff;
  border-radius: 9.6px;
  padding: 12.8px 20px;
  overflow: hidden;
  position: relative;
  .location {
    font-size: 14.4px;
    color: #000000;
    line-height: 20.8px;
    font-weight: 500;
    margin-bottom: 14.4px;
  }
  .action-btn {
    width: 118px;
    height: 38.4px;
    line-height: 38.4px;
    background: #ffffff;
    border: 0.8px solid rgba(224, 224, 224, 1);
    box-shadow: 0px 8px 19.2px 0px rgba(185, 185, 185, 0.24);
    border-radius: 21.6px 19.2px 19.2px 21.6px;
    font-size: 16px;
    color: #000000;
    text-align: center;
    font-weight: 400;
    position: absolute;
    right: 20px;
    top: 15px;
    &.complete-btn {
      background-image: linear-gradient(180deg, #3773f6 0%, #2c57f6 99%);
      color: #ffffff;
    }
    &.disable-btn {
      background: #f2f2f2;
      color: #999999;
    }
  }
}
.module-box {
  height: calc(100vh - 212px); /* 根据实际情况调整高度 */
  overflow-y: auto; /* 垂直方向滚动 */
  overflow-x: hidden; /* 防止水平方向滚动 */
}
.tab-content {
  margin-top: 12.8px;
}
.title-bar {
  display: flex;
  align-items: center;
  margin-bottom: 8px;

  .blue-line {
    width: 3.2px;
    height: 12.8px;
    background-color: #007aff;
    margin-right: 6.4px;
  }

  .title {
    font-size: 12.8px;
    font-weight: bold;
  }

  .location {
    margin-left: 6.4px;
    color: #666;
  }

  .submit-btn {
    position: absolute;
    right: 19.2px;
    width: 20%;
    background-color: #ccc;
    color: #fff;
    border-radius: 3.2px;
    padding: 3.2px 6.4px;
    font-size: 9.6px;

    &.active {
      background-color: #007aff;
    }
  }
}

.description {
  font-size: 11.2px;
  color: #666;
}

.tab-scroll {
  width: 100%;
  white-space: nowrap;
}

.tab-buttons {
  display: inline-flex;
  justify-content: flex-start;
  align-items: center;
  margin-bottom: 8px;
  gap: 16px;
  min-width: 100%;
}

.tip {
  width: 100%;
  background: rgba(55, 116, 246, 0.05);
  border: 0.8px solid rgba(55, 116, 246, 0.3);
  border-radius: 8px;
  font-size: 11.2px;
  color: #4a4a4a;
  letter-spacing: 0;
  font-weight: 400;
  padding: 4.8px 9.6px;
  display: flex;

  .icon-tixing {
    color: #3774f6;
    font-size: 9.6px;
    margin-right: 6.4px;
  }
  .text {
    line-height: 17.6px;
    color: #4a4a4a;
    letter-spacing: 0;
    font-weight: 400;
  }
}
.jfImg {
  width: 100%;
  margin-bottom: 15px;
  .weitu {
    width: 100%;
    height: 320px;
  }
}
.kong {
  width: 100%;
  height: 10px;
}
.tab-item {
  display: flex;
  align-items: flex-start;
  position: relative;
  padding: 6.4px 0;
  cursor: pointer;
  white-space: nowrap;
  .iconfont {
    font-size: 12px;
    margin-right: 4px;
    &.icon-weixunjian {
      color: #959595;
    }
    &.icon-shibai1 {
      color: #ff4a34;
    }
    &.icon-wancheng {
      color: #3774f6;
    }
  }

  .tab-icon {
    width: 8.4px;
    height: 8.4px;
    margin-bottom: 3.2px;
    margin-right: 2.4px;
  }

  .tab-text {
    font-size: 11.2px;
    color: #333;
    white-space: nowrap;
  }

  &.active {
    .tab-text {
      color: #3774f6;
    }

    .underline {
      position: absolute;
      bottom: 0;
      left: 50%;
      transform: translateX(-50%);
      width: 100%;
      height: 1.6px;
      background-color: #3774f6;
    }
  }
}

.form-item {
  display: flex;
  align-items: center;
  padding: 9.6px 0;
  line-height: 28.8px;
  border-bottom: 0.8px solid #f2f3f5;

  .form-label {
    font-size: 11.2px;
    margin-right: 25.6px;
    width: 58.4px;
    text-align: right;
    color: #7c7c7c;

    .required {
      color: red;
      margin-right: 3.2px;
    }
  }
  .label {
    font-size: 11.2px;
  }

  .switch-container {
    display: flex;
    gap: 9.6px;

    .status-btn {
      flex: 1;
      padding: 5.6px 19.2px;
      font-size: 12.8px;
      color: #000000;
      background: #f2f2f2;
      text-align: center;
      font-weight: 400;
      line-height: 17.6px;
      border-radius: 14.4px;

      &.active {
        color: #ffffff;
        background: #3774f6;
        border: 0.32px solid rgba(224, 224, 224, 1);
      }
    }
  }

  .input-box {
    flex: 1;
    border-radius: 3.2px;
    font-size: 12.8px;
    line-height: 19.2px;
  }

  .photo-limit {
    font-size: 12.8px;
    color: #959595;
    line-height: 19.2px;
    font-weight: 400;
  }

  .photo-container {
    display: flex;
    flex-wrap: wrap;
    margin-bottom: 6.4px;

    .photo-item {
      position: relative;
      margin-right: 6.4px;
      margin-bottom: 6.4px;

      .photo {
        width: 57.6px;
        height: 57.6px;
        border-radius: 3.2px;
        margin-left: 9.6px;
      }

      .delete-photo {
        position: absolute;
        top: -6.4px;
        right: -6.4px;
        background-color: #ff4d4f;
        color: #fff;
        width: 12.8px;
        height: 12.8px;
        border-radius: 50%;
        text-align: center;
        line-height: 12.8px;
        font-size: 9.6px;
      }
    }
  }

  .photo-btn {
    background: #ffffff;
    border: 0.272px solid rgba(221, 221, 221, 1);
    border-radius: 1.64px;
    width: 57.6px;
    height: 57.6px;
    font-size: 57.6px;
    color: #cccccc;
    text-align: center;
    line-height: 51.2px;
  }
}

.submit-module {
  display: flex;
  justify-content: center;
  position: fixed;
  gap: 16px;
  left: 55%;
  transform: translateX(-50%);
  bottom: 20px;

  .action-btn {
    width: 118px;
    height: 38.4px;
    line-height: 38.4px;
    background: #ffffff;
    border: 0.8px solid rgba(224, 224, 224, 1);
    box-shadow: 0px 8px 19.2px 0px rgba(185, 185, 185, 0.24);
    border-radius: 21.6px 19.2px 19.2px 21.6px;
    font-size: 16px;
    color: #000000;
    text-align: center;
    font-weight: 400;

    &.complete-btn {
      background-image: linear-gradient(180deg, #3773f6 0%, #2c57f6 99%);
      color: #ffffff;
    }
  }
}

.popup-content {
  background-color: white;
  padding: 32px;
  border-radius: 8px;
  text-align: center;
  position: relative;
  width: 240px;

  .close-icon {
    position: absolute;
    top: 8px;
    right: 8px;
    font-size: 16px;
    cursor: pointer;
  }

  .icon-success {
    font-size: 32px;
    color: green;
    margin-bottom: 16px;
  }

  .success-text {
    font-size: 14.4px;
    margin-bottom: 16px;
  }

  .next-button {
    background-color: blue;
    color: white;
    padding: 8px 16px;
    border-radius: 4px;
    cursor: pointer;
    font-size: 12.8px;

    &:hover {
      opacity: 0.9;
    }
  }
}
</style>
