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

      <!-- Tab 切换 -->
      <view class="tab-bar">
        <view
          class="tab-item"
          :class="{ active: activeTab === 'report' }"
          @click="activeTab = 'report'"
          >上报信息</view
        >
        <view
          class="tab-item"
          :class="{ active: activeTab === 'fix', disabled: isAdd }"
          @click="activeTab = 'fix'"
          >整改信息</view
        >
        <view
          class="tab-item"
          :class="{
            active: activeTab === 'verify',
            disabled: isAdd || isFixing,
          }"
          @click="activeTab = 'verify'"
          >验收信息</view
        >
      </view>

      <scroll-view class="popup-body" scroll-y>
        <view class="page">
          <view class="card-a">
            <!-- ============ 上报信息 ============ -->
            <view v-show="activeTab === 'report'">
              <view class="card-section">
                <view class="section-title">📋 基本信息</view>
                <u--form
                  labelPosition="left"
                  labelWidth="160rpx"
                  :model="formData"
                  :rules="reportRules"
                  ref="reportForm"
                >
                  <!-- 隐患编号（只读） -->
                  <u-form-item label="隐患编号" prop="code" borderBottom>
                    <u--input
                      v-model="formData.code"
                      disabled
                      disabledColor="#f5f5f5"
                      border="none"
                      inputAlign="right"
                    />
                  </u-form-item>

                  <!-- 隐患名称 -->
                  <u-form-item
                    label="隐患名称"
                    prop="title"
                    borderBottom
                    required
                  >
                    <u--input
                      v-model="formData.title"
                      placeholder="请输入隐患名称"
                      :disabled="!canEditReport"
                      border="none"
                      inputAlign="right"
                    />
                  </u-form-item>

                  <!-- 隐患等级 -->
                  <u-form-item
                    label="隐患等级"
                    prop="level"
                    borderBottom
                    required
                  >
                    <view
                      class="picker-value"
                      @click="!canEditReport || showPicker('level')"
                    >
                      {{ getLabel(levelOptions, levelIndex) }}
                    </view>
                    <u-icon slot="right" name="arrow-right" />
                  </u-form-item>

                  <!-- 隐患类别 -->
                  <u-form-item
                    label="隐患类别"
                    prop="category"
                    borderBottom
                    required
                  >
                    <view
                      class="picker-value"
                      @click="!canEditReport || showPicker('category')"
                    >
                      {{ getLabel(categoryOptions, categoryIndex) }}
                    </view>
                    <u-icon slot="right" name="arrow-right" />
                  </u-form-item>

                  <!-- 来源类型 -->
                  <u-form-item label="来源类型" prop="sourceType" borderBottom>
                    <view
                      class="picker-value"
                      @click="!canEditReport || showPicker('sourceType')"
                    >
                      {{ getLabel(chkTypeList, sourceTypeIndex) }}
                    </view>
                    <u-icon slot="right" name="arrow-right" />
                  </u-form-item>

                  <!-- 来源单据名称 -->
                  <u-form-item
                    label="来源单据"
                    prop="sourceName"
                    borderBottom
                    @click="addSource"
                  >
                    <u--input
                      v-model="formData.sourceName"
                      placeholder="请选择"
                      :disabled="!canEditReport"
                      border="none"
                      inputAlign="right"
                    />
                  </u-form-item>

                  <!-- 发现人 -->
                  <u-form-item
                    label="发现人"
                    prop="foundUserName"
                    borderBottom
                    required
                    @click="userOpen('found')"
                  >
                    <u--input
                      v-model="formData.foundUserName"
                      placeholder="请选择"
                      :disabled="!canEditReport"
                      border="none"
                      inputAlign="right"
                    />
                  </u-form-item>

                  <!-- 发现时间 -->
                  <u-form-item
                    label="发现时间"
                    prop="foundTime"
                    borderBottom
                    required
                  >
                    <view
                      class="picker-value"
                      @click="!canEditReport || showDateTimePicker('foundTime')"
                    >
                      {{ formData.foundTime || "请选择" }}
                    </view>
                    <u-icon slot="right" name="arrow-right" />
                  </u-form-item>

                  <!-- 区域（category == 2） -->
                  <u-form-item
                    v-if="formData.category == 2"
                    label="区域"
                    prop="areaName"
                    borderBottom
                  >
                    <u--input
                      v-model="formData.areaName"
                      placeholder="请选择区域"
                      :disabled="!canEditReport"
                      readonly
                      border="none"
                      inputAlign="right"
                      @click="selectArea"
                    />
                  </u-form-item>

                  <!-- 设备信息（category == 1） -->
                  <template v-if="formData.category == 1">
                    <u-form-item
                      label="设备名称"
                      prop="deviceName"
                      borderBottom
                    >
                      <u--input
                        v-model="formData.deviceName"
                        placeholder="请选择设备"
                        :disabled="!canEditReport || [1,2,3,5].includes(formData.sourceCode)"
                        readonly
                        border="none"
                        inputAlign="right"
                        @click="selectDevice"
                      />
                    </u-form-item>
                    <u-form-item
                      label="设备编号"
                      prop="deviceCode"
                      borderBottom
                    >
                      <u--input
                        v-model="formData.deviceCode"
                        disabled
                        disabledColor="#f5f5f5"
                        placeholder="自动带出"
                        border="none"
                        inputAlign="right"
                      />
                    </u-form-item>
                    <u-form-item
                      label="设备位置"
                      prop="deviceLocation"
                      borderBottom
                    >
                      <u--input
                        v-model="formData.deviceLocation"
                        placeholder="请输入设备位置"
                        :disabled="!canEditReport"
                        border="none"
                        inputAlign="right"
                      />
                    </u-form-item>
                  </template>

                  <!-- 整改责任人 -->
                  <u-form-item
                    label="整改责任人"
                    prop="fixUserName"
                    borderBottom
                    required
                    @click="userOpen('fix')"
                  >
                    <u--input
                      v-model="formData.fixUserName"
                      placeholder="请选择"
                      :disabled="!canEditReport"
                      border="none"
                      inputAlign="right"
                    />
                  </u-form-item>

                  <!-- 计划整改时限 -->
                  <u-form-item
                    label="计划整改时限"
                    prop="fixDeadline"
                    borderBottom
                    required
                    labelWidth="190rpx"
                  >
                    <view
                      class="picker-value"
                      @click="
                        !canEditReport || showDateTimePicker('fixDeadline')
                      "
                    >
                      {{ formData.fixDeadline || "请选择" }}
                    </view>
                    <u-icon slot="right" name="arrow-right" />
                  </u-form-item>

                  <!-- 隐患描述 -->
                  <u-form-item
                    label="隐患描述"
                    prop="description"
                    borderBottom
                    required
                  >
                    <u--textarea
                      v-model="formData.description"
                      placeholder="请输入隐患详细描述"
                      :disabled="!canEditReport"
                      height="120rpx"
                    />
                  </u-form-item>

                  <!-- 可能导致后果 -->
                  <u-form-item
                    label="可能导致后果"
                    prop="consequence"
                    borderBottom
                    labelWidth="190rpx"
                  >
                    <u--textarea
                      v-model="formData.consequence"
                      placeholder="请输入可能导致的事故后果"
                      :disabled="!canEditReport"
                      height="100rpx"
                    />
                  </u-form-item>

                  <!-- 上报附件 -->
                  <u-form-item label="上报附件" borderBottom>
                    <fileMain
                      v-model="formData.reportAttachments"
                      :type="canEditReport ? '' : 'view'"
                    />
                  </u-form-item>
                </u--form>
              </view>
            </view>

            <!-- ============ 整改信息 ============ -->
            <view v-show="activeTab === 'fix'">
              <view class="card-section">
                <view class="section-title">🔧 整改详情</view>
                <u--form
                  labelPosition="left"
                  labelWidth="160rpx"
                  :model="formData"
                  :rules="fixRules"
                  ref="fixForm"
                >
                  <u-form-item
                    label="整改资金(元)"
                    prop="fixBudget"
                    borderBottom
                    labelWidth="180rpx"
                  >
                    <u--input
                      v-model="formData.fixBudget"
                      type="number"
                      placeholder="请输入"
                      :disabled="!canEditFix"
                      border="none"
                      inputAlign="right"
                    />
                  </u-form-item>

                  <u-form-item
                    label="实际整改开始"
                    prop="fixStart"
                    borderBottom
                    labelWidth="190rpx"
                  >
                    <view
                      class="picker-value"
                      @click="!canEditFix || showDateTimePicker('fixStart')"
                    >
                      {{ formData.fixStart || "请选择" }}
                    </view>
                    <u-icon slot="right" name="arrow-right" />
                  </u-form-item>

                  <u-form-item
                    label="实际整改完成"
                    prop="fixEnd"
                    borderBottom
                    labelWidth="190rpx"
                  >
                    <view
                      class="picker-value"
                      @click="!canEditFix || showDateTimePicker('fixEnd')"
                    >
                      {{ formData.fixEnd || "请选择" }}
                    </view>
                    <u-icon slot="right" name="arrow-right" />
                  </u-form-item>

                  <u-form-item
                    label="整改措施"
                    prop="fixMeasures"
                    borderBottom
                    required
                  >
                    <u--textarea
                      v-model="formData.fixMeasures"
                      placeholder="请输入具体整改措施"
                      :disabled="!canEditFix"
                      height="120rpx"
                    />
                  </u-form-item>

                  <u-form-item
                    label="根因类型"
                    prop="rootCauseType"
                    borderBottom
                  >
                    <DictSelection
                      dictName="根因类型"
                      clearable
                      :disabled="!canEditFix"
                      v-model="formData.rootCauseType"
                    />
                  </u-form-item>

                  <u-form-item
                    label="根因分析"
                    prop="rootCauseAnalysis"
                    borderBottom
                  >
                    <u--textarea
                      v-model="formData.rootCauseAnalysis"
                      placeholder="请输入隐患根因分析"
                      :disabled="!canEditFix"
                      height="120rpx"
                    />
                  </u-form-item>

                  <u-form-item label="整改附件" borderBottom>
                    <fileMain
                      v-model="formData.fixPhotos"
                      :type="canEditFix ? '' : 'view'"
                    />
                  </u-form-item>
                </u--form>
              </view>
            </view>

            <!-- ============ 验收信息 ============ -->
            <view v-show="activeTab === 'verify'">
              <view class="card-section">
                <view class="section-title">✅ 验收信息</view>
                <u--form
                  labelPosition="left"
                  labelWidth="160rpx"
                  :model="formData"
                  :rules="verifyRules"
                  ref="verifyForm"
                >
                  <u-form-item
                    label="验收人"
                    prop="verifyUserName"
                    borderBottom
                    required
                  >
                    <u--input
                      v-model="formData.verifyUserName"
                      placeholder="请输入验收人姓名"
                      disabled
                      disabledColor="#f5f5f5"
                      border="none"
                      inputAlign="right"
                    />
                  </u-form-item>

                  <u-form-item
                    label="验收时间"
                    prop="verifyTime"
                    borderBottom
                    required
                  >
                    <view
                      class="picker-value"
                      @click="
                        !canEditVerify || showDateTimePicker('verifyTime')
                      "
                    >
                      {{ formData.verifyTime || "请选择" }}
                    </view>
                    <u-icon slot="right" name="arrow-right" />
                  </u-form-item>

                  <u-form-item
                    label="验收结果"
                    prop="verifyResult"
                    borderBottom
                    required
                  >
                    <view
                      class="picker-value"
                      @click="!canEditVerify || showPicker('verifyResult')"
                    >
                      {{ getLabel(verifyResultOptions, verifyResultIndex) }}
                    </view>
                    <u-icon slot="right" name="arrow-right" />
                  </u-form-item>

                  <u-form-item
                    label="验收意见"
                    prop="verifyComment"
                    borderBottom
                  >
                    <u--textarea
                      v-model="formData.verifyComment"
                      placeholder="请输入验收人员意见说明"
                      :disabled="!canEditVerify"
                      border="none"
                      height="120rpx"
                    />
                  </u-form-item>

                  <u-form-item label="验收附件" borderBottom>
                    <fileMain
                      v-model="formData.verifyPhotos"
                      :type="canEditVerify ? '' : 'view'"
                    />
                  </u-form-item>
                </u--form>
              </view>
            </view>
          </view>
        </view>
      </scroll-view>

      <!-- 底部按钮 -->
      <view class="popup-footer">
        <u-button type="default" @click="handleCancel">关闭</u-button>
        <u-button
          v-if="canEditReport || dialogType === 'fix'"
          type="primary"
          @click="handleSubmit"
          :loading="loading"
          >保存</u-button
        >
        <u-button
          v-if="dialogType === 'fix'"
          type="success"
          @click="handleSubmitFix"
          :loading="loading"
          >提交整改</u-button
        >
        <u-button
          v-if="dialogType === 'verify'"
          type="success"
          @click="handleSubmitVerify"
          :loading="loading"
          >提交验收</u-button
        >
      </view>
    </view>

    <!-- 选择器 Popup -->
    <u-action-sheet
      :show="showPickerPopup"
      :actions="pickerActions"
      title="请选择"
      @close="showPickerPopup = false"
      @select="onPickerSelect"
    />

    <!-- 日期时间选择器 -->
    <u-datetime-picker
      :show="showDateTimePopup"
      v-model="datetimeValue"
      mode="datetime"
      @confirm="onDateTimeConfirm"
      @cancel="showDateTimePopup = false"
    />
    <selectUserDialog
      ref="userSelectRef"
      @confirm="changePersonel"
    ></selectUserDialog>
    <PatrolSelectDialog
      ref="patrolSelectRef"
      @confirm="onPatrolConfirm"
    ></PatrolSelectDialog>
    <snapshotSelectDialog
      ref="snapshotSelectRef"
      @confirm="onSnapshotConfirm"
    ></snapshotSelectDialog>
    <u-toast ref="uToast" />
  </u-popup>
</template>

<script>
import fileMain from "@/pages/doc/index.vue";
import selectUserDialog from "@/components/selectUserDialog.vue";
import snapshotSelectDialog from "@/pages/ehs/snapshot/components/snapshotSelectDialog.vue";
import PatrolSelectDialog from "./components/PatrolSelectDialog.vue";
import DictSelection from "@/components/Dict/DictSelection.vue";
import {
  save,
  getById,
  accept,
  rectify,
} from "@/api/hazardManagement/index.js";
  import {handle } from '@/api/snapshot/index.js';

export default {
  components: {
    selectUserDialog,
    PatrolSelectDialog,
    fileMain,
    snapshotSelectDialog,
    DictSelection,
  },
  data() {
    return {
      visible: false,
      userKey: "",
      dialogType: "add", // add | edit | view | fix | verify
      activeTab: "report",
      loading: false,
      formData: this.getDefaultForm(),

      // 选择器相关
      showPickerPopup: false,
      showDateTimePopup: false,
      pickerType: "",
      datetimeValue: 0,
      pickerActions: [],

      // 下拉选项
      levelOptions: [
        { value: 4, label: "轻微" },
        { value: 3, label: "一般" },
        { value: 2, label: "较大" },
        { value: 1, label: "重大" },
      ],
      chkTypeList: [
        { value: 1, label: "巡点检" },
        { value: 2, label: "设备保养" },
        { value: 3, label: "设备维修" },
        { value: 4, label: "随手拍" },
        { value: 5, label: "量具送检" },
      ],
      categoryOptions: [
        { value: 1, label: "设备设施" },
        { value: 2, label: "作业环境" },
        { value: 3, label: "人员行为" },
        { value: 4, label: "管理缺陷" },
        { value: 5, label: "其他" },
      ],
      verifyResultOptions: [
        { value: 1, label: "合格" },
        { value: 2, label: "不合格" },
        { value: 3, label: "部分合格" },
      ],

      // 索引
      levelIndex: -1,
      categoryIndex: -1,
      sourceTypeIndex: -1,
      verifyResultIndex: -1,

      // uView Form 校验规则
      reportRules: {
        title: {
          type: "string",
          required: true,
          message: "请输入隐患名称",
          trigger: ["blur", "change"],
        },
        level: {
          type: "number",
          required: true,
          message: "请选择隐患等级",
          trigger: ["change"],
        },
        category: {
          type: "number",
          required: true,
          message: "请选择隐患类别",
          trigger: ["change"],
        },
        foundUserName: {
          type: "string",
          required: true,
          message: "请选择发现人",
          trigger: ["change"],
        },
        foundTime: {
          type: "string",
          required: true,
          message: "请选择发现时间",
          trigger: ["change"],
        },
        description: {
          type: "string",
          required: true,
          message: "请输入隐患描述",
          trigger: ["blur", "change"],
        },
        fixUserName: {
          type: "string",
          required: true,
          message: "请选择整改责任人",
          trigger: ["change"],
        },
        fixDeadline: {
          type: "string",
          required: true,
          message: "请选择计划整改时限",
          trigger: ["change"],
        },
      },
      fixRules: {
        fixMeasures: {
          type: "string",
          required: true,
          message: "请输入整改措施",
          trigger: ["blur", "change"],
        },
      },
      verifyRules: {
        verifyUserName: {
          type: "string",
          required: true,
          message: "请输入验收人",
          trigger: ["blur", "change"],
        },
        verifyTime: {
          type: "string",
          required: true,
          message: "请选择验收时间",
          trigger: ["change"],
        },
        verifyResult: {
          type: "number",
          required: true,
          message: "请选择验收结果",
          trigger: ["change"],
        },
      },
    };
  },
  computed: {
    dialogTitle() {
      const map = {
        add: "新增隐患",
        edit: "编辑隐患",
        view: "查看隐患",
        fix: "隐患整改",
        verify: "隐患验收",
      };
      return map[this.dialogType] || "隐患详情";
    },
    isAdd() {
      return this.dialogType === "add";
    },
    isFixing() {
      return this.dialogType === "fix";
    },
    canEditReport() {
      return ["add", "edit"].includes(this.dialogType);
    },
    canEditFix() {
      return this.dialogType === "fix";
    },
    canEditVerify() {
      return this.dialogType === "verify";
    },
  },
  methods: {
    // 辅助方法：安全获取选项标签（兼容无可选链）
    getLabel(list, index) {
      if (index >= 0 && index < list.length) {
        return list[index].label;
      }
      return "请选择";
    },

    getDefaultForm() {
      const userInfo = uni.getStorageSync("userInfo") || {};
      return {
        id: "",
        code: "",
        title: "",
        level: null,
        category: null,
        foundTime: "",
        foundUserId: userInfo.userId || "",
        foundUserName: userInfo.name || "",
        fixUserId: "",
        fixUserName: "",
        fixDeadline: "",
        description: "",
        consequence: "",
        reportAttachments: [],
        fixBudget: "",
        fixStart: "",
        fixEnd: "",
        fixMeasures: "",
        rootCauseType: "",
        rootCauseAnalysis: "",
        fixPhotos: [],
        verifyUserId: "",
        verifyUserName: "",
        verifyTime: "",
        verifyResult: null,
        verifyComment: "",
        verifyPhotos: [],
        areaId: null,
        areaName: "",
        deviceId: "",
        deviceName: "",
        deviceCode: "",
        deviceLocation: "",
        sourceType: null,
        sourceName: "",
        sourceId: "",
        sourceCode: "",
      };
    },

    // 打开弹窗
    async open(type, row = null, activeTab = "report", sourceDate = null) {
      this.dialogType = type;
      this.activeTab = activeTab || "report";
      this.loading = false;
      if (row && row.id) {
        try {
          const data = await getById(row.id);
          this.formData = { ...data };
          if (type === "verify") {
            const userInfo = uni.getStorageSync("userInfo") || {};
            this.formData.verifyUserName = userInfo.name || "";
            this.formData.verifyUserId = userInfo.userId || "";
          }
          this.syncPickerIndex();
        } catch (e) {
          console.error(e);
        }
      } else {
        this.formData = { ...this.getDefaultForm(), ...sourceDate };
        this.syncPickerIndex();
      }
      this.visible = true;
      this.$nextTick(() => {
        // 安全设置校验规则
        if (this.$refs.reportForm) {
          this.$refs.reportForm.setRules(this.reportRules);
        }
        if (this.$refs.fixForm) {
          this.$refs.fixForm.setRules(this.fixRules);
        }
        if (this.$refs.verifyForm) {
          this.$refs.verifyForm.setRules(this.verifyRules);
        }
      });
    },

    syncPickerIndex() {
      this.levelIndex = this.levelOptions.findIndex(
        (i) => i.value == this.formData.level,
      );
      this.categoryIndex = this.categoryOptions.findIndex(
        (i) => i.value == this.formData.category,
      );
      this.sourceTypeIndex = this.chkTypeList.findIndex(
        (i) => i.value == this.formData.sourceType,
      );
      this.verifyResultIndex = this.verifyResultOptions.findIndex(
        (i) => i.value == this.formData.verifyResult,
      );
    },

    // ============ 选择器相关 ============
    showPicker(type) {
      if (this.loading) return;
      this.pickerType = type;
      let actions = [];
      switch (type) {
        case "level":
          actions = this.levelOptions.map((i) => ({
            name: i.label,
            value: i.value,
          }));
          break;
        case "category":
          actions = this.categoryOptions.map((i) => ({
            name: i.label,
            value: i.value,
          }));
          break;
        case "sourceType":
          actions = this.chkTypeList.map((i) => ({
            name: i.label,
            value: i.value,
          }));
          break;
        case "verifyResult":
          actions = this.verifyResultOptions.map((i) => ({
            name: i.label,
            value: i.value,
          }));
          break;
        default:
          return;
      }
      this.pickerActions = actions;
      this.showPickerPopup = true;
    },

    onPickerSelect(e) {
      this.showPickerPopup = false;
      const value = e.value;
      switch (this.pickerType) {
        case "level":
          this.levelIndex = this.levelOptions.findIndex(
            (i) => i.value === value,
          );
          this.formData.level = value;
          if (this.$refs.reportForm) {
            this.$refs.reportForm.validateField("level");
          }
          break;
        case "category":
          this.categoryIndex = this.categoryOptions.findIndex(
            (i) => i.value === value,
          );
          this.formData.category = value;
          // 清空设备/区域
          this.formData.deviceId = "";
          this.formData.deviceName = "";
          this.formData.deviceCode = "";
          this.formData.deviceLocation = "";
          this.formData.areaId = null;
          this.formData.areaName = "";
          if (this.$refs.reportForm) {
            this.$refs.reportForm.validateField("category");
          }
          break;
        case "sourceType":
          this.sourceTypeIndex = this.chkTypeList.findIndex(
            (i) => i.value === value,
          );
          this.formData.sourceType = value;
          this.formData.sourceName = "";
          this.formData.sourceId = "";
          this.formData.sourceCode = "";
          break;
        case "verifyResult":
          this.verifyResultIndex = this.verifyResultOptions.findIndex(
            (i) => i.value === value,
          );
          this.formData.verifyResult = value;
          if (this.$refs.verifyForm) {
            this.$refs.verifyForm.validateField("verifyResult");
          }
          break;
      }
    },

    showDateTimePicker(field) {
      if (this.loading) return;
      this.pickerType = field;
      const val = this.formData[field];
      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.formData[this.pickerType] = value;
      // 触发对应表单校验
      if (
        this.pickerType === "foundTime" ||
        this.pickerType === "fixDeadline"
      ) {
        if (this.$refs.reportForm) {
          this.$refs.reportForm.validateField(this.pickerType);
        }
      } else if (this.pickerType === "verifyTime") {
        if (this.$refs.verifyForm) {
          this.$refs.verifyForm.validateField(this.pickerType);
        }
      }
    },

    // ============ 人员选择 ============
    userOpen(key) {
      if (this.loading) return;
      this.userKey = key;
      this.$refs.userSelectRef.open(2);
    },
    changePersonel(data) {
      this.formData[this.userKey + "UserName"] = data[0].name;
      this.formData[this.userKey + "UserId"] = data[0].id;
      if (
        (this.userKey === "found" || this.userKey === "fix") &&
        this.$refs.reportForm
      ) {
        this.$refs.reportForm.validateField(this.userKey + "UserName");
      }
    },

    // ============ 设备选择 ============
    selectDevice() {
    
      this.$refs.MaterialAddRef.open();
    },
    chooseEquipment(data) {
      this.formData.deviceId = data.id;
      this.formData.deviceLocation = data.pathName;
      this.formData.deviceName = data.category.name;
      this.formData.deviceCode = data.codeNumber;
    },

    // ============ 区域选择 ============
    selectArea() {
      if (!this.canEditReport || this.loading) return;
      uni.showModal({
        title: "选择区域",
        editable: true,
        placeholderText: "请输入区域名称",
        success: (res) => {
          if (res.confirm && res.content) {
            this.formData.areaName = res.content;
            this.formData.areaId = res.content;
          }
        },
      });
    },

    // ============ 来源单据 ============
    addSource() {
      if (this.loading) return;
      if (!this.formData.sourceType) {
        this.$refs.uToast.show({ type: "error", message: "请先选择来源类型" });
        return;
      }
      if (this.formData.sourceType == 4) {
        this.$refs.snapshotSelectRef.open();
      } else {
        this.$refs.patrolSelectRef.open(this.formData.sourceType);
      }
    },
    onPatrolConfirm(data) {
      this.formData.category = 1;
      this.formData.sourceCode = data.sourceCode;
      this.formData.sourceId = data.sourceId;
      this.formData.sourceName = data.sourceName;
      const device = data.deviceList;
      if (device && device.substance) {
        this.formData.deviceId = device.substance.id || "";
        this.formData.deviceName = device.substance.name || "";
        this.formData.deviceCode = device.substance.codeNumber || "";
        this.formData.deviceLocation = device.substance.positionNames || "";
      }
      this.syncPickerIndex();
    },
    onSnapshotConfirm(data) {
      Object.assign(this.formData, data);
      this.formData.sourceName = "随手拍";
      this.syncPickerIndex();
    },

    // ============ 提交逻辑 ============
    async handleSubmit() {
      try {
        // 安全校验
        if (this.$refs.reportForm) {
          await this.$refs.reportForm.validate();
        }
        if (this.dialogType === "fix" && this.$refs.fixForm) {
          await this.$refs.fixForm.validate();
          this.formData.status = 2;
        }
        this.loading = true;
        const res = await save(this.formData);
        this.$refs.uToast.show({ type: "success", message: "保存成功" });
        this.visible = false;
        //随手拍需要改变状态
        if (this.formData.sourceType == 4) {
          await handle({
            id: this.formData.sourceId,
            handleOpinion: "下发整改",
            invHazardId: res,
          });
        }

        this.$emit("reload");
      } catch (e) {
        if (e && e.message) {
          this.$refs.uToast.show({ type: "error", message: e.message });
        }
      } finally {
        this.loading = false;
      }
    },

    async handleSubmitFix() {
      try {
        if (this.$refs.fixForm) {
          await this.$refs.fixForm.validate();
        }

        this.loading = true;
        await rectify(this.formData);
        this.$refs.uToast.show({ type: "success", message: "整改成功" });
        this.visible = false;
        this.$emit("reload");
      } catch (e) {
        if (e && e.message) {
          this.$refs.uToast.show({ type: "error", message: e.message });
        }
      } finally {
        this.loading = false;
      }
    },

    async handleSubmitVerify() {
      try {
        if (this.$refs.verifyForm) {
          await this.$refs.verifyForm.validate();
        }

        this.loading = true;
        await accept(this.formData);
        this.$refs.uToast.show({ type: "success", message: "验收成功" });
        this.visible = false;
        this.$emit("reload");
      } catch (e) {
        if (e && e.message) {
          this.$refs.uToast.show({ type: "error", message: e.message });
        }
      } finally {
        this.loading = false;
      }
    },

    handleCancel() {
      this.visible = false;
      this.formData = this.getDefaultForm();
      this.activeTab = "report";
      this.showPickerPopup = false;
      this.showDateTimePopup = false;
    },
  },
};
</script>

<style lang="scss" scoped>
.hazard-popup {
  .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;
    }
  }

  .tab-bar {
    display: flex;
    background: #fff;
    border-bottom: 1rpx solid #e5e5e5;
    .tab-item {
      flex: 1;
      text-align: center;
      padding: 20rpx 0;
      font-size: 28rpx;
      color: #666;
      &.active {
        color: $theme-color;
        font-weight: bold;
        border-bottom: 4rpx solid $theme-color;
      }
      &.disabled {
        color: #ccc;
        pointer-events: none;
      }
    }
  }

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

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

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

  .card-section {
    padding: 30rpx 32rpx;
    &:not(:last-child) {
      border-bottom: 2rpx solid #f0f2f5;
    }
  }

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



  .picker-value {
    font-size: 28rpx;
    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;
      border-radius: 48rpx;
    }
  }
}
</style>
