<template>
  <view class="page repair">
    <scroll-view scroll-y="true" class="detail">
      <view class="form-content">
        <uni-forms
          ref="repairFormRef"
          labelWidth="140px"
          :modelValue="maintain"
        >
          <!-- 设备 -->
          <uni-forms-item
            class="form-item"
            :label="$t('maintenanceWorkOrder.equipment')"
            name="deviceName"
            :required="false"
          >
            <uni-easyinput
              style="text-align: right"
              :inputBorder="false"
              :clearable="false"
              :disabled="true"
              :styles="{ disableColor: '#fff' }"
              :placeholder="' '"
              v-model="maintain.deviceName"
            />
          </uni-forms-item>
          <!-- 维修类型 -->
          <uni-forms-item
            class="form-item"
            :label="$t('equipmentMaintenance.maintenanceType')"
            name="type"
            :required="false"
          >
            <uni-data-select
              :clear="false"
              :disabled="true"
              v-model="maintain.type"
              :localdata="typeRange"
            >
            </uni-data-select>
          </uni-forms-item>

          <!-- 维修方式 -->
          <uni-forms-item
            v-if="maintain.maintainMethod"
            class="form-item"
            label="维修方式"
            name="maintainMethod"
            :required="false"
          >
            <uni-data-select
              :clear="false"
              :disabled="true"
              v-model="maintain.maintainMethod"
              :localdata="typeRange2"
            >
            </uni-data-select>
          </uni-forms-item>
          <!-- 是否停机 -->
          <uni-forms-item
            class="form-item"
            :label="$t('equipmentMaintenance.isStop')"
            name="ifStop"
            :required="false"
          >
            <uni-data-select
              :clear="false"
              :disabled="true"
              v-model="maintain.ifStop"
              :localdata="ifStopRange"
            >
            </uni-data-select>
          </uni-forms-item>

          <!-- 维修开始时间 维修类型是委外时不必填-->
          <uni-forms-item
            class="form-item"
            :label="$t('equipmentMaintenance.maintenanceStartTime')"
            name="maintainStartTime"
            :required="false"
          >
            <!-- :end="dateMax" -->
            <uni-datetime-picker
              type="datetime"
              :border="false"
              :disabled="true"
              returnType="timestamp"
              :placeholder="' '"
              :style="{
                color: maintain.maintainStartTime ? '#333' : '#999',
                'font-size': maintain.maintainStartTime
                  ? '14px !important'
                  : 'inherit !important',
              }"
              v-model="maintain.maintainStartTime"
            >
            </uni-datetime-picker>
          </uni-forms-item>
          <!-- return-type="timestamp" -->
          <!-- 维修结束时间 维修类型是委外时不必填-->
          <uni-forms-item
            class="form-item"
            :label="$t('equipmentMaintenance.maintenanceEndTime')"
            name="maintainEndTime"
            :required="false"
          >
            <!-- :end="dateMax" -->
            <uni-datetime-picker
              type="datetime"
              :border="false"
              :disabled="true"
              returnType="timestamp"
              :placeholder="' '"
              :style="{
                color: maintain.maintainEndTime ? '#333' : '#999',
                'font-size': maintain.maintainEndTime
                  ? '14px !important'
                  : 'inherit !important',
              }"
              v-model="maintain.maintainEndTime"
            >
            </uni-datetime-picker>
          </uni-forms-item>
          <!-- 负责人 -->
          <uni-forms-item
            class="form-item"
            :label="$t('workOrder.responsiblePerson')"
            name="failureInfluence"
            :required="false"
          >
            <uni-easyinput
              style="text-align: right"
              :inputBorder="false"
              :clearable="false"
              :disabled="true"
              :styles="{ disableColor: '#fff' }"
              v-model="responsiblePerson"
              :placeholder="' '"
            />
          </uni-forms-item>
          <!-- 故障时间 维修类型是委外时必填-->
          <uni-forms-item
            class="form-item"
            :label="$t('fault.faultTime')"
            name="failureTime"
            :required="false"
          >
            <!-- :end="dateMax" -->
            <uni-datetime-picker
              type="datetime"
              :border="false"
              returnType="timestamp"
              :disabled="true"
              :placeholder="' '"
              :style="{
                color: maintain.failureTime ? '#333' : '#999',
                'font-size': maintain.failureTime
                  ? '14px !important'
                  : 'inherit !important',
              }"
              v-model="maintain.failureTime"
            >
            </uni-datetime-picker>
          </uni-forms-item>
          <!-- 故障影响 -->
          <uni-forms-item
            class="form-item"
            :label="$t('fault.faultImpact')"
            name="failureInfluence"
            :required="false"
          >
            <uni-easyinput
              style="text-align: right"
              :inputBorder="false"
              :clearable="false"
              :disabled="true"
              :styles="{ disableColor: '#fff' }"
              v-model="maintain.failureInfluence"
              :placeholder="' '"
            />
          </uni-forms-item>
          <!-- 故障系统 -->
          <uni-forms-item
            class="form-item"
            :label="$t('fault.faultSystem')"
            name="failureSystem"
            :required="false"
          >
            <uni-easyinput
              style="text-align: right"
              :inputBorder="false"
              :clearable="false"
              :disabled="true"
              :styles="{ disableColor: '#fff' }"
              v-model="maintain.failureSystem"
              :placeholder="' '"
            />
          </uni-forms-item>
          <!-- 维修费用 维修类型是委外时可填 -->
          <uni-forms-item
            class="form-item"
            :label="$t('equipmentMaintenance.cost')"
            name="maintainFee"
            :required="false"
            v-if="maintain.type == 'in'"
          >
            <uni-easyinput
              style="text-align: right"
              :inputBorder="false"
              :clearable="false"
              :disabled="true"
              :styles="{ disableColor: '#fff' }"
              v-model="maintain.maintainFee"
            />
          </uni-forms-item>
          <!-- 图片 -->
          <uni-forms-item
            class="form-item"
            :label="$t('general.picture')"
            name="picList"
            :required="false"
          >
            <uni-file-picker
              file-mediatype="image"
              mode="grid"
              :auto-upload="false"
              :limit="9"
              :readonly="true"
              :imageStyles="{ border: false }"
              v-model="maintain.picList"
            >
            </uni-file-picker>
          </uni-forms-item>
          <!-- 类型是out(OA委外)时，触发oa流程  -->
          <template v-if="maintain.type == 'out'">
            <!-- 申请人 -->
            <uni-forms-item
              class="form-item"
              :label="$t('equipmentMaintenance.applicant')"
              :required="false"
              name="applyPersonId"
            >
              <uni-data-select
                :clear="false"
                :disabled="true"
                v-model="maintain.applyPersonId"
                :localdata="applyPersonRange"
                :placeholder="' '"
              >
              </uni-data-select>
            </uni-forms-item>
            <!-- 维修类别 -->
            <uni-forms-item
              class="form-item"
              :label="$t('equipmentMaintenance.classify')"
              :required="false"
              name="maintainClassify"
            >
              <uni-data-select
                :clear="false"
                :disabled="true"
                v-model="maintain.maintainClassify"
                :localdata="maintainClassifyRange"
                :placeholder="' '"
              >
              </uni-data-select>
            </uni-forms-item>
            <!-- 运行公里/小时 -->
            <uni-forms-item
              class="form-item"
              :label="$t('equipmentMaintenance.runningKilometersPerHour')"
              :required="false"
              name="kmHour"
            >
              <uni-easyinput
                style="text-align: right"
                :inputBorder="false"
                :clearable="false"
                :disabled="true"
                :styles="{ disableColor: '#fff' }"
                v-model="maintain.kmHour"
                :placeholder="' '"
              />
            </uni-forms-item>
            <!-- 规格型号 -->
            <uni-forms-item
              class="form-item"
              :label="$t('equipmentMaintenance.specificationModel')"
              :required="false"
              name="specificationModel"
            >
              <uni-easyinput
                style="text-align: right"
                :inputBorder="false"
                :clearable="false"
                :disabled="true"
                :styles="{ disableColor: '#fff' }"
                v-model="maintain.model"
                :placeholder="' '"
              />
            </uni-forms-item>
            <!-- 启用日期 -->
            <uni-forms-item
              class="form-item"
              :label="$t('equipmentMaintenance.enableDate')"
              :required="false"
              name="enableDate"
            >
              <uni-datetime-picker
                type="date"
                :border="false"
                :disabled="true"
                :placeholder="' '"
                returnType="string"
                :style="{
                  color: maintain.enableDate ? '#333' : '#999',
                  'font-size': maintain.enableDate
                    ? '14px !important'
                    : 'inherit !important',
                }"
                v-model="maintain.enableDate"
              >
              </uni-datetime-picker>
            </uni-forms-item>
            <!-- 供应商 -->
            <uni-forms-item
              class="form-item"
              :label="$t('equipmentMaintenance.supplier')"
              :required="false"
              name="supplier"
            >
              <uni-easyinput
                style="text-align: right"
                :inputBorder="false"
                :clearable="false"
                :disabled="true"
                :styles="{ disableColor: '#fff' }"
                v-model="maintain.supplier"
                :placeholder="' '"
              >
              </uni-easyinput>
            </uni-forms-item>
            <!-- 维修费用 -->
            <uni-forms-item
              class="form-item"
              :label="$t('equipmentMaintenance.cost')"
              :required="false"
              name="maintainFee"
            >
              <uni-easyinput
                style="text-align: right"
                :inputBorder="false"
                :clearable="false"
                :disabled="true"
                :styles="{ disableColor: '#fff' }"
                v-model="maintain.maintainFee"
                :placeholder="' '"
              />
            </uni-forms-item>
            <!-- 项目经理 -->
            <uni-forms-item
              class="form-item"
              :label="$t('equipmentMaintenance.projectManager')"
              :required="false"
              name="projectManager"
            >
              <uni-data-select
                :clear="false"
                :disabled="true"
                v-model="maintain.projectManager"
                :localdata="projectManagerRange"
                :placeholder="' '"
              >
              </uni-data-select>
            </uni-forms-item>
            <!-- 维修地点 -->
            <uni-forms-item
              class="form-item"
              :label="$t('equipmentMaintenance.maintenanceLocation')"
              :required="false"
              name="address"
            >
              <uni-easyinput
                style="text-align: right"
                :inputBorder="false"
                :clearable="false"
                :disabled="true"
                :styles="{ disableColor: '#fff' }"
                v-model="maintain.address"
                :placeholder="' '"
              />
            </uni-forms-item>
            <!-- 委外相关附件 -->
            <uni-forms-item
              class="form-item"
              :label="$t('equipmentMaintenance.outsourceRelatedAttachments')"
              :required="false"
              name="outFilesList"
            >
              <view class="file-list">
                <view
                  class="file-item flex-row justify-between"
                  v-for="(file, index) in maintain.outFilesList"
                  :key="index"
                >
                  <view class="file-name">{{ file.name }}</view>
                  <view class="file-btn" @click="downloadFile(file)">
                    {{ $t("operation.download") }}
                  </view>
                </view>
              </view>
              <!-- <uni-file-picker
                :clear="false"
                :limit="9"
                readonly
                file-mediatype="all"
                :value="maintain.outFilesList"
              >
              </uni-file-picker> -->
            </uni-forms-item>
            <!-- 维修项目 -->
            <uni-forms-item
              class="form-item"
              :label="$t('equipmentMaintenance.maintenanceItem')"
              :required="false"
              name="maintainItem"
            >
              <uni-easyinput
                style="text-align: right"
                :inputBorder="false"
                :clearable="false"
                :disabled="true"
                :styles="{ disableColor: '#fff' }"
                v-model="maintain.maintainItems"
                :placeholder="' '"
              />
            </uni-forms-item>
          </template>
          <!-- ----------------------------------- OA委外 end ------------------------  -->
          <!-- 故障描述 -->
          <uni-forms-item
            class="form-item"
            :label="$t('fault.description')"
            :required="false"
            name="description"
          >
            <uni-easyinput
              style="text-align: right"
              type="textarea"
              :autoHeight="true"
              :inputBorder="false"
              :disabled="true"
              :clearable="false"
              :styles="{ disableColor: '#fff' }"
              v-model="maintain.description"
              :placeholder="' '"
            />
          </uni-forms-item>
          <!-- 维修描述 维修类型是委外时不必填-->
          <uni-forms-item
            class="form-item"
            :label="$t('equipmentMaintenance.description')"
            :required="false"
            name="maintainDescription"
          >
            <uni-easyinput
              style="text-align: right"
              type="textarea"
              :autoHeight="true"
              :inputBorder="false"
              :disabled="true"
              :clearable="false"
              :styles="{ disableColor: '#fff' }"
              v-model="maintain.maintainDescription"
              :placeholder="' '"
            />
          </uni-forms-item>
          <!-- 解决办法 -->
          <uni-forms-item
            class="form-item"
            :label="$t('fault.solution')"
            :required="false"
            name="solution"
          >
            <uni-easyinput
              style="text-align: right"
              type="textarea"
              :autoHeight="true"
              :inputBorder="false"
              :disabled="true"
              :clearable="false"
              :styles="{ disableColor: '#fff' }"
              v-model="maintain.solution"
              :placeholder="' '"
            />
          </uni-forms-item>
          <!-- 备注 -->
          <uni-forms-item
            class="form-item"
            :label="$t('operation.remark')"
            :required="false"
            name="remark"
          >
            <uni-easyinput
              style="text-align: right"
              type="textarea"
              :autoHeight="true"
              :inputBorder="false"
              :disabled="true"
              :clearable="false"
              :styles="{ disableColor: '#fff' }"
              v-model="maintain.remark"
              :placeholder="' '"
            />
          </uni-forms-item>
        </uni-forms>

        <view class="device-section" v-for="bom in maintainBom">
          <!-- 设备编码 -->
          <view class="item-module">
            <view class="item-content flex-row align-center justify-between">
              <view class="item-title">
                <span class="item-title-width"
                  >{{ $t("device.deviceCode") }}:</span
                >
              </view>
              <view class="item-title">
                <span>{{ bom.deviceCode }}</span>
              </view>
            </view>
            <view class="module-border"> </view>
          </view>
          <!-- 设备名称 -->
          <view class="item-content flex-row align-center justify-between">
            <view class="item-title">
              <span class="item-title-width"
                >{{ $t("device.deviceName") }}:</span
              >
            </view>
            <view class="item-title">
              <span>{{ bom.deviceName }}</span>
            </view>
          </view>
          <!-- 维修项 -->
          <view class="item-content flex-row align-center justify-between">
            <view class="item-title">
              <span class="item-title-width"
                >{{ $t("equipmentMaintenance.maintenanceItems") }}:</span
              >
            </view>
            <view class="item-title">
              <span>{{ bom.name }}</span>
            </view>
          </view>
          <!-- 是否消耗物料 -->
          <view
            class="item-content flex-row align-center justify-between"
            v-if="bom.rule"
          >
            <view class="item-title">
              <span class="item-title-width">
                {{ $t("workOrder.isConsumptionMaterial") }}:
              </span>
            </view>

            <switch
              :checked="bom.rule == 0 ? true : false"
              :disabled="true"
              @change="bomRuleChange(bom)"
            />
          </view>
          <!-- 不消耗物料原因 -->
          <view
            class="item-content flex-row align-center justify-between"
            v-if="bom.rule == 1"
          >
            <view class="item-title">
              <span class="item-title-width">
                {{ $t("equipmentMaintenance.noConsumeMaterialReason") }}:
              </span>
            </view>
            <uni-easyinput
              style="text-align: right"
              :styles="{ disableColor: '#fff' }"
              :inputBorder="false"
              :autoHeight="true"
              type="textarea"
              :placeholder="$t('operation.PleaseFillIn')"
              v-model="bom.remark"
            />
          </view>
          <!-- 物料数量 -->
          <!-- 					<view class="item-content flex-row align-center justify-between">
						<view class="item-title">
							<span class="item-title-width">{{$t('workOrder.materialCount')}}:</span>
						</view>
						<view class="item-title">
							<span>{{bom.materialCount}}</span>
						</view>
					</view> -->
          <!-- 操作按钮 -->
          <view class="item-opera flex-row justify-end">
            <button type="primary" :plain="false" @click="onMaterialView(bom)">
              {{ $t("workOrder.materialDetails") }}
            </button>
          </view>
        </view>
      </view>
    </scroll-view>
  </view>
  <!-- -->
  <materials-view ref="materialsViewRef" />
</template>

<script setup>
import { onLoad, onReady, onBackPress } from "@dcloudio/uni-app";
import {
  reactive,
  ref,
  watch,
  computed,
  watchEffect,
  onMounted,
  onBeforeUnmount,
  nextTick,
  getCurrentInstance,
} from "vue";
import {
  getRepairDetail,
  getRepairApplicantList,
  getRepairProjectManagerList,
} from "@/api/repair.js";
import { getRandomNumber } from "@/utils/methods";
import dayjs from "dayjs";
import { uploadFile, getUserInfo } from "@/api";

import deviceSingle from "@/components/device/single.vue";
import repairMultiple from "@/components/repair/multiple.vue";
import repairAdd from "@/components/repair/add.vue";
import materialsChoose from "@/components/materials/choose.vue";
import materialsView from "@/components/materials/view.vue";

import { useDataDictStore } from "@/store/modules/dataDict";
import { template } from "lodash";
const { getDataDictList } = useDataDictStore();

// 引用全局变量$t
const { appContext } = getCurrentInstance();
const t = appContext.config.globalProperties.$t;
// 获取维修类型
const typeDict = getDataDictList("pms_main_type");

// 获取维修方式
const typeDict2 = getDataDictList("maintain_method");
// 遍历typeDict，新增text字段 值为label
typeDict.forEach((item) => {
  item.text = item.label;
});

typeDict2.forEach((item) => {
  item.text = item.label;
});

// 维修类型
const typeRange = ref(typeDict);
const typeRange2 = ref(typeDict2);
// 是否停机
const ifStopRange = ref([
  {
    value: 1,
    text: t("operation.yes"),
  },
  {
    value: 0,
    text: t("operation.no"),
  },
]);
// 申请人
const applyPersonRange = ref([]);
// 获取申请人列表
const getApplicantList = async (id) => {
  // id参数创建的时候传undefined，详情的时候需要传入工单的创建人creator
  const res = await getRepairApplicantList({
    id,
  });
  if (res.code == 0) {
    applyPersonRange.value = res.data.map((item) => {
      return {
        value: item.oaId,
        text: item.lastname,
      };
    });
    // console.log(
    //   "🚀 ~ getApplicantList ~ applyPersonRange.value:",
    //   applyPersonRange.value
    // );
  }
};
// 维修类别列表
const maintainClassifyRange = getDataDictList("pms_maintain_classify").map(
  (item) => {
    return {
      value: item.value,
      text: item.label,
    };
  },
);
console.log("🚀 ~ maintainClassifyRange:", maintainClassifyRange);

// 项目经理
const projectManagerRange = ref([]);
// 获取项目经理列表
const getProjectManagerList = async (id) => {
  // id参数创建的时候传undefined，详情的时候需要传入工单的创建人creator
  const res = await getRepairProjectManagerList({
    id,
  });
  if (res.code !== 0) {
    uni.showToast({
      title: res.msg,
      icon: "error",
    });
    return;
  }
  projectManagerRange.value = res.data.map((item) => {
    return {
      value: item.oaId,
      text: item.lastname,
    };
  });
  // console.log(
  //   "🚀 ~ getProjectManagerList ~ projectManagerRange.value:",
  //   projectManagerRange.value
  // );
};
// 获取当前时间
const now = dayjs().format("YYYY-MM-DD HH:mm:ss");
const dateMax = ref(now);

//维修工单
const maintain = ref({
  deviceId: "",
  deviceName: "",
  type: "in", // 类型(是否委外 in 内部 out 外部)
  picList: [], //用于上传照片 提交时删除
});
// 维修项
const maintainBom = ref([]);
const maintainId = ref("");
const responsiblePerson = ref("");
const getData = () => {
  getRepairDetail({
    id: maintainId.value,
  }).then((res) => {
    console.log("getRepairDetail", res);
    // 将ifStop字段改为0/1
    res.data.ifStop = res.data.ifStop ? 1 : 0;
    maintain.value = res.data;
    // 将图片地址转换为数组
    maintain.value.picList = res.data.pics
      ? res.data.pics.map((item) => {
          return {
            url: item,
          };
        })
      : [];
    // 将附件转换为数组
    maintain.value.outFilesList = res.data.outFiles
      ? res.data.outFiles.map((item) => {
          return {
            url: item,
            name: item.split("/").pop(),
          };
        })
      : [];

    // 维修项赋值
    maintainBom.value = res.data.maintainBomDOS;
    // 遍历维修项,将设备名称和设备编码添加到维修项中
    maintainBom.value.forEach((bom) => {
      bom.deviceName = res.data.deviceName;
      bom.deviceCode = res.data.deviceCode;
    });
    // 获取负责人
    getUserInfo({
      id: res.data.maintainPerson,
    }).then((res) => {
      console.log("getUserInfo", res);
      responsiblePerson.value = res.data?.nickname;
    });
    // 获取申请人列表
    getApplicantList(res.data.creator);
    // 获取项目经理列表
    getProjectManagerList(res.data.creator);
  });
};

// 下载文件
const downloadFile = async (file) => {
  console.log("🚀 ~ downloadFile ~ file:", file);
  const { url: fileUrl, name: fileName } = file;
  if (!fileUrl) {
    uni.showToast({ title: t("operation.fileUrlEmpty"), icon: "none" });
    return;
  }
  // 获取平台
  const platform = uni.getSystemInfoSync().platform;
  console.log("🚀 ~ downloadFile ~ platform:", platform);
  // 判断平台
  if (platform === "android") {
    uni.downloadFile({
      url: fileUrl,
      success: (res) => {
        console.log("🚀 ~ downloadFile ~ res:", res);
        if (res.statusCode === 200) {
          uni.saveFile({
            tempFilePath: res.tempFilePath,
            success: (res) => {
              console.log("🚀 ~ downloadFile saveFile ~ res:", res);
              uni.showToast({
                title: t("operation.downloadSuccess"),
                icon: "none",
              });
            },
            fail: (err) => {
              console.log("🚀 ~ downloadFile saveFile ~ err:", err);
              uni.showToast({
                title: t("operation.downloadFail"),
                icon: "none",
              });
            },
          });
        }
      },
      fail: (err) => {
        console.log("🚀 ~ downloadFile ~ err:", err);
        uni.showToast({
          title: t("operation.downloadFail"),
          icon: "none",
        });
      },
    });
  } else {
    try {
      // 2.1 处理文件名（避免特殊字符乱码，如中文、空格）
      const safeFileName = decodeURIComponent(fileName || "未命名文件"); // 解码URL编码的文件名

      // 2.2 创建隐藏的 <a> 标签（核心：利用 download 属性触发下载）
      const link = document.createElement("a");
      // 关键：设置 download 属性指定文件名（Web 端独有）
      link.download = safeFileName;
      // 设置文件地址（若跨域，需后端配置 CORS + Content-Disposition 响应头）
      link.href = fileUrl;
      // 隐藏 <a> 标签（不影响页面布局）
      link.style.display = "none";
      // 将 <a> 标签添加到文档中（否则部分浏览器无法触发点击）
      document.body.appendChild(link);

      // 2.3 模拟点击 <a> 标签触发下载
      link.click();

      // 2.4 下载后清理资源（避免内存泄漏）
      setTimeout(() => {
        document.body.removeChild(link); // 移除 <a> 标签
        URL.revokeObjectURL(link.href); // 释放 URL 资源（若使用 Blob 时必需）
      }, 100);
    } catch (err) {
      console.error("🚀 ~ Web 端下载失败:", err);
      // 若直接通过 <a> 标签下载失败（如跨域），尝试通过 Blob 流下载（场景2兼容）
      await downloadFileByBlob(fileUrl, fileName);
    }
  }
};
// 兼容场景2：通过 Blob 流下载（解决跨域或后端返回流的情况）
const downloadFileByBlob = async (fileUrl, fileName) => {
  try {
    // 1. 发起请求获取文件流（注意：需设置 responseType: 'blob'）
    const response = await fetch(fileUrl, {
      method: "GET",
      headers: {
        // 若需要登录态，添加 token（根据项目授权方式调整）
        Authorization: `Bearer ${uni.getStorageSync("token")}`,
      },
    });

    if (!response.ok) {
      throw new Error(`请求失败: ${response.status}`);
    }

    // 2. 将响应转换为 Blob 对象（根据文件类型设置 MIME，如 PDF 为 'application/pdf'）
    const blob = await response.blob();
    // 3. 生成 Blob 临时 URL
    const blobUrl = URL.createObjectURL(blob);

    // 4. 用 <a> 标签触发下载（同场景1逻辑）
    const safeFileName = decodeURIComponent(fileName || "未命名文件");
    const link = document.createElement("a");
    link.download = safeFileName;
    link.href = blobUrl;
    link.style.display = "none";
    document.body.appendChild(link);
    link.click();

    // 5. 清理资源
    setTimeout(() => {
      document.body.removeChild(link);
      URL.revokeObjectURL(blobUrl); // 必须释放 Blob URL，避免内存泄漏
      uni.hideLoading();
      // uni.showToast({ title: t("operation.downloadSuccess"), icon: "success" });
    }, 100);
  } catch (err) {
    console.error("🚀 ~ Blob 下载失败:", err);
    uni.hideLoading();
    // uni.showToast({ title: t("operation.downloadFail"), icon: "error" });
  }
};
onLoad((option) => {
  maintainId.value = option.id;
  getData();
});
onReady(() => {});

const onMaterialView = (item) => {
  console.log("onMaterialView", item);

  uni.navigateTo({
    url:
      "/pages/material/repair-view?workOrderId=" +
      maintain.value.id +
      "&bomId=" +
      item.id,
  });
};

const repairFormRef = ref(null);

onMounted(() => {
  // 监听子页面提交的事件
  console.log("onMounted");
  // uni.$on('multiple-devide-submit', (data) => {
  // 	console.log('接收到子页面数据:', data);
  // 	selectedDevices.value = data
  // 	onDeviceBomList()
  // });
});
onBeforeUnmount(() => {
  // 移除监听
  console.log("onBeforeUnmount");
  // uni.$off('multiple-devide-submit');
});
</script>

<style lang="scss" scoped>
@import "@/style/work-order-detail.scss";

.detail {
  height: 100%;
}

:deep(.uni-textarea-textarea:disabled),
:deep(.uni-input-input:disabled) {
  color: #333;
}
.file-list {
  margin: 10px;
  .file-item {
    padding: 10px;
    margin-bottom: 10px;
    border: 1px solid #f5f5f5;
    .file-btn {
      color: #004098;
      min-width: max-content;
    }
  }
}
</style>
