<template>
  <div class="home">
    <van-nav-bar title="设备管理" fixed left-arrow @click-left="onClickLeft" />

    <van-cell-group>
      <van-cell title="当前站点" :value="equipmentInfo.sbwz" />
    </van-cell-group>

    <div class="content">
      <van-cell-group>
        <van-cell
          title="设备信息"
          style="font-size: 18px; font-weight: bold; line-height: inherit"
        >
          <template #value>
            <span
              :class="[
                'status-tag',
                `status-` +
                  (equipmentDetailInfo.sbzt === '完好'
                    ? 'good'
                    : equipmentDetailInfo.sbzt === '损坏'
                    ? 'warning'
                    : 'danger'),
              ]"
              >{{ equipmentDetailInfo.sbzt }}</span
            >
          </template>
        </van-cell>
        <van-cell :title="'设备名称： ' + equipmentDetailInfo.sbmc">
          <template #right-icon>
            <van-image
              :src="photos[0]?.photoUrl"
              fit="cover"
              width="100px"
              @click="showImage(photos)"
            ></van-image>
          </template>
        </van-cell>
        <van-cell :title="'设备大类： ' + equipmentDetailInfo.sbdl"> </van-cell>
        <van-cell :title="'设备类型:  ' + equipmentDetailInfo.sblx"> </van-cell>
        <van-cell :title="'设备编号： ' + equipmentDetailInfo.sbbh"> </van-cell>
        <van-cell :title="'设备型号： ' + equipmentDetailInfo.sbxh"> </van-cell>
        <van-cell :title="'设备位置： ' + equipmentDetailInfo.sbwz"> </van-cell>
        <van-cell :title="'设备经纬度： '">
          <template #label>
            <span
              >设备经度: {{ equipmentDetailInfo.jd }}<br />设备纬度:
              {{ equipmentDetailInfo.wd }}</span
            >
          </template>
        </van-cell>
        <van-cell :title="'设备管理人员：  ' + equipmentDetailInfo.glry">
        </van-cell>
        <van-cell :title="'操作员：       ' + equipmentDetailInfo.czy">
        </van-cell>
        <van-cell :title="'购置日期：     ' + equipmentDetailInfo.gzrq">
        </van-cell>
        <van-cell :title="'购买费用（万元）： ' + equipmentDetailInfo.gmfy">
        </van-cell>
        <van-cell :title="'应急设备： ' + equipmentDetailInfo.sfyjsb">
        </van-cell>
        <van-cell :title="'纳入市级补助范围： ' + equipmentDetailInfo.sfnrsjbz">
        </van-cell>
        <van-cell :title="'辐射范围： ' + equipmentDetailInfo.fsfw"> </van-cell>
        <van-cell :title="'所属服务站： ' + equipmentDetailInfo.yhzmc">
        </van-cell>
        <van-cell
          v-if="equipmentDetailInfo.sbzt !== '完好'"
          :title="equipmentDetailInfo.sbzt + '原因：' + latestStatusDesc"
        />
        <van-cell :title="'备注： ' + equipmentDetailInfo.remark"> </van-cell>
      </van-cell-group>
    </div>

    <van-tabbar>
      <van-tabbar-item>
        <van-popover
          placement="top-start"
          :show="showPopover"
          :actions="actions"
          @select="onSelect"
        >
          <template #reference>
            <van-button type="primary" style="width: 80px; border-radius: 10px">
              更多
            </van-button>
          </template>
        </van-popover>
      </van-tabbar-item>
      <van-tabbar-item
        ><template #default>
          <van-button
            type="warning"
            style="width: 80px; border-radius: 10px"
            @click="onBrokenPopupOpen"
          >
            损坏
          </van-button>
        </template></van-tabbar-item
      >
      <van-tabbar-item
        ><template #default>
          <van-button
            type="primary"
            style="width: 80px; border-radius: 10px"
            @click="onEditPopupOpen"
          >
            编辑
          </van-button>
        </template></van-tabbar-item
      >
      <van-tabbar-item
        ><template #default>
          <van-button
            type="primary"
            style="width: 80px; border-radius: 10px"
            @click="onRemarkPopupOpen"
          >
            备注
          </van-button>
        </template></van-tabbar-item
      >
    </van-tabbar>

    <van-popup
      :show="showRemarkPopup"
      position="bottom"
      closeable
      close-on-click-overlay
      :style="{ height: '30%' }"
      @close="onRemarkPopupClose"
    >
      <div
        style="
          height: 100%;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          padding: 0 16px;
        "
      >
        <h1
          style="
            margin: 0 0 12px 0;
            font-size: 18px;
            color: #333;
            text-align: center;
          "
        >
          备注信息
        </h1>
        <van-field
          v-model="equipmentDetailInfo.remark"
          placeholder="请输入备注"
          style="
            width: 100%;
            margin-bottom: 16px;
            border-radius: 8px;
            background: #f7f8fa;
          "
        />
        <div style="display: flex; gap: 20px; width: 100%">
          <van-button
            type="default"
            style="flex: 1; border-radius: 8px"
            @click="onRemarkPopupClose"
          >
            取消
          </van-button>
          <van-button
            type="primary"
            style="flex: 1; border-radius: 8px"
            @click="onRemarkConfirm"
          >
            确认
          </van-button>
        </div>
      </div>
    </van-popup>
    <van-popup
      :show="showDeletePopup"
      position="bottom"
      closeable
      close-on-click-overlay
      :style="{ height: '20%' }"
      @close="onDeletePopupClose"
    >
      <div
        style="
          height: 100%;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          padding: 0 16px;
        "
      >
        <h1
          style="
            margin: 0 0 20px 0;
            font-size: 18px;
            color: #333;
            text-align: center;
          "
        >
          确认删除？
        </h1>

        <div style="display: flex; gap: 20px; width: 100%">
          <van-button
            type="default"
            style="flex: 1; border-radius: 8px"
            @click="onDeletePopupClose"
          >
            取消
          </van-button>
          <van-button
            type="primary"
            style="flex: 1; border-radius: 8px"
            @click="onDeleteConfirm"
          >
            确认
          </van-button>
        </div>
      </div>
    </van-popup>

    <van-popup
      :show="showBrokenPopup"
      position="bottom"
      closeable
      close-on-click-overlay
      :style="{ height: '30%' }"
      @close="onBrokenPopupClose"
    >
      <div
        style="
          height: 100%;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          padding: 0 16px;
        "
      >
        <h1
          style="
            margin: 0 0 12px 0;
            font-size: 18px;
            color: #333;
            text-align: center;
          "
        >
          损坏上报
        </h1>
        <van-field
          v-model="brokenReason"
          placeholder="请填写损坏原因"
          style="
            width: 100%;
            margin-bottom: 16px;
            border-radius: 8px;
            background: #f7f8fa;
          "
        />
        <div style="display: flex; gap: 20px; width: 100%">
          <van-button
            type="default"
            style="flex: 1; border-radius: 8px"
            @click="onBrokenPopupClose"
          >
            取消
          </van-button>
          <van-button
            type="primary"
            style="flex: 1; border-radius: 8px"
            @click="onBrokenConfirm"
          >
            确认
          </van-button>
        </div>
      </div>
    </van-popup>
    <van-popup
      :show="showScrapPopup"
      position="bottom"
      closeable
      close-on-click-overlay
      :style="{ height: '30%' }"
      @close="onScrapPopupClose"
    >
      <div
        style="
          height: 100%;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          padding: 0 16px;
        "
      >
        <h1
          style="
            margin: 0 0 12px 0;
            font-size: 18px;
            color: #333;
            text-align: center;
          "
        >
          报废
        </h1>

        <van-field
          v-model="scrapReason"
          placeholder="请填写原因"
          style="
            width: 100%;
            margin-bottom: 16px;
            border-radius: 8px;
            background: #f7f8fa;
          "
        />

        <div style="display: flex; gap: 20px; width: 100%">
          <van-button
            type="default"
            style="flex: 1; border-radius: 8px"
            @click="onScrapPopupClose"
          >
            取消
          </van-button>
          <van-button
            type="primary"
            style="flex: 1; border-radius: 8px"
            @click="onScrapConfirm"
          >
            确认
          </van-button>
        </div>
      </div>
    </van-popup>

    <van-popup
      :show="showEditPopup"
      position="bottom"
      closeable
      close-on-click-overlay
      :style="{ height: '80%' }"
      @close="onEditPopupClose"
    >
      <van-form class="device-form" label-align="left" colon>
        <h3>编辑设备信息</h3>
        <!-- 设备名称 -->
        <van-field
          v-model="editForm.equipment.sbmc"
          label="设备名称"
          placeholder="请输入设备名称"
          :rules="[{ required: true, message: '请填写设备名称' }]"
          maxlength="20"
          show-word-limit
        >
        </van-field>
        <!-- 设备大类 -->
        <van-field
          v-model="editForm.equipment.sbdl"
          is-link
          arrow-direction="down"
          label="设备大类"
          placeholder="请选择设备大类"
          @click="showCategoryPicker = true"
          ref="categoryField"
        />
        <!-- 设备类型 -->
        <van-field
          v-model="editForm.equipment.sblx"
          is-link
          arrow-direction="down"
          label="设备类型"
          placeholder="请选择设备类型"
          @click="showTypePicker = true"
          ref="typeField"
        />
        <!-- 设备编号 -->
        <van-field
          v-model="editForm.equipment.sbbh"
          label="设备编号"
          placeholder="请输入设备编号"
          :rules="[{ required: true, message: '请填写设备编号' }]"
        />
        <!-- 设备型号 -->
        <van-field
          v-model="editForm.equipment.sbxh"
          label="设备型号"
          placeholder="请输入设备型号"
          :rules="[{ required: true, message: '请填写设备型号' }]"
        />
        <!-- 经纬度 -->
        <van-field
          v-model="editForm.equipment.jd"
          label="设备经度"
          placeholder="请输入经度"
          type="number"
        />
        <van-field
          v-model="editForm.equipment.wd"
          label="设备纬度"
          placeholder="请输入纬度"
          type="number"
        />
        <!-- 管理人员 -->
        <van-field
          v-model="editForm.equipment.glry"
          is-link
          arrow-direction="down"
          readonly
          label="管理人员"
          placeholder="请选择设备管理人员"
          @click="showAdminPicker = true"
        />
        <!-- 操作员 -->
        <van-field
          v-model="editForm.equipment.czy"
          is-link
          arrow-direction="down"
          readonly
          label="操作员"
          placeholder="请选择操作员"
          @click="showOperatorPicker = true"
        />
        <!-- 购买费用 -->
        <van-field
          v-model="editForm.equipment.gmfy"
          type="number"
          label="购买费用(万元)"
          placeholder="请输入购买费用"
        />
        <!-- 购置日期 -->
        <van-field
          v-model="editForm.equipment.gzrq"
          is-link
          arrow-direction="down"
          readonly
          label="购置日期"
          placeholder="请选择日期"
          @click="showTimePicker = true"
        />

        <!-- 生产厂家 -->
        <van-field
          v-model="editForm.equipment.sccj"
          label="生产厂家"
          placeholder="请输入生产厂家"
        />

        <!-- 是否应急设备 -->
        <van-field
          v-model="editForm.equipment.sfyjsb"
          is-link
          arrow-direction="down"
          readonly
          label="是否应急设备"
          placeholder="请选择"
          @click="showEmergencyPicker = true"
        />

        <!-- 是否纳入市级补助范围 -->
        <van-field
          v-model="editForm.equipment.sfnrsjbz"
          is-link
          arrow-direction="down"
          readonly
          label="是否纳入市级补助范围"
          placeholder="请选择"
          @click="showSubsidyPicker = true"
        />

        <!-- 辐射范围 -->
        <van-field
          v-model="editForm.equipment.fsfw"
          label="辐射范围"
          placeholder="请输入辐射范围"
        />

        <van-field label="设备照片" center>
          <template #input>
            <van-uploader
              v-model="fileList"
              @delete="handleDelete"
              name="photos"
              :file-list="fileList"
              :file-type="['image/jpeg', 'image/png']"
              :after-read="afterRead"
              multiple
              :max-count="6"
            />
          </template>
        </van-field>

        <!-- 选择器弹窗 -->
        <!-- 设备大类弹窗 -->
        <van-popup
          :show="showCategoryPicker"
          round
          position="bottom"
          close-on-click-overlay
          @close="showCategoryPicker = false"
        >
          <van-picker
            title="选择设备大类"
            :columns="categoryOptions"
            @confirm="onCategoryConfirm"
            @cancel="showCategoryPicker = false"
          />
        </van-popup>

        <!-- 设备类型弹窗 -->
        <van-popup
          :show="showTypePicker"
          round
          position="bottom"
          close-on-click-overlay
          @close="showTypePicker = false"
        >
          <van-picker
            title="选择设备类型"
            :columns="typeOptions"
            @confirm="onTypeConfirm"
            @cancel="showTypePicker = false"
          />
        </van-popup>

        <!-- 设备管理员弹窗 -->
        <van-popup
          :show="showAdminPicker"
          round
          position="bottom"
          close-on-click-overlay
          @close="showAdminPicker = false"
        >
          <van-picker
            title="选择设备管理员"
            :columns="adminOptions"
            @confirm="onAdminConfirm"
            @cancel="showAdminPicker = false"
          />
        </van-popup>

        <!-- 操作员弹窗 -->
        <van-popup
          :show="showOperatorPicker"
          round
          position="bottom"
          close-on-click-overlay
          @close="showOperatorPicker = false"
        >
          <van-picker
            title="选择操作员"
            :columns="operatorOptions"
            @confirm="operatorConfirm"
            @cancel="showOperatorPicker = false"
          />
        </van-popup>

        <!-- 购置日期弹窗 -->
        <van-popup
          :show="showTimePicker"
          round
          position="bottom"
          close-on-click-overlay
          @close="showTimePicker = false"
        >
          <van-date-picker
            v-model="currentDate"
            title="选择购置日期"
            @confirm="onDateConfirm"
            @cancel="showTimePicker = false"
          />
        </van-popup>

        <!-- 是否应急设备弹窗 -->
        <van-popup
          :show="showEmergencyPicker"
          round
          position="bottom"
          close-on-click-overlay
          @close="showEmergencyPicker = false"
        >
          <van-picker
            title="是否应急设备"
            :columns="emergencyOptions"
            @confirm="onEmergencyConfirm"
            @cancel="showEmergencyPicker = false"
          />
        </van-popup>
        <!-- 是否纳入市级补助范围弹窗 -->
        <van-popup
          :show="showSubsidyPicker"
          round
          position="bottom"
          close-on-click-overlay
          @close="showSubsidyPicker = false"
        >
          <van-picker
            title="是否纳入市级补助"
            :columns="subsidyOptions"
            @confirm="onSubsidyConfirm"
            @cancel="showSubsidyPicker = false"
          />
        </van-popup>
      </van-form>
      <div
        style="
          position: fixed;
          bottom: 0;
          left: 0;
          right: 0;
          padding: 16px;
          background: white;
          box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
          z-index: 100;
        "
      >
        <van-button
          round
          block
          type="primary"
          native-type="submit"
          @click="onEditSubmit"
        >
          保存
        </van-button>
      </div>
    </van-popup>
  </div>
</template>
  
  <script setup>
import "vant/es/toast/style";
import "vant/es/popup/style";
import { ref, onMounted, toRaw, reactive, computed } from "vue";
import { useRouter, useRoute } from "vue-router";
import { showToast, showLoadingToast, showImagePreview } from "vant";
import { request } from "../../../../shared/utils/request";

const router = useRouter();
const route = useRoute();

const showPopover = ref(false);
const actions = [{ text: "删除" }, { text: "报废" }];
const onSelect = (action) => {
  if (action.text === "删除") {
    showDeletePopup.value = true;
  }
  if (action.text === "报废") {
    showScrapPopup.value = true;
  }
};
const equipmentInfo = ref({});
const yhzInfo = ref({});
const equipmentDetailInfo = ref({});
const photos = ref([]);
const statusList = ref([]);

// 获取设备详情
const getEquipmentDetailInfo = async () => {
  try {
    const res = await request({
      url: `/snow-ops-platform/yjsb/getById?rid=${equipmentInfo.value.rid}`,
      method: "GET",
    });
    if (res.code && res.code === "00000") {
      equipmentDetailInfo.value = res.data.equipment;
      photos.value = res.data.photos;
      statusList.value = res.data.statusList;
      console.log("设备详情", toRaw(equipmentDetailInfo.value));
    } else {
      throw new Error(res.data.message);
    }
  } catch (error) {
    showToast({ type: "error", message: error.message });
  }
};

onMounted(() => {
  const data = JSON.parse(decodeURIComponent(route.params.data));
  equipmentInfo.value = data.equipmentInfo;

  yhzInfo.value = data.yhzInfo;
  getEquipmentDetailInfo();
});

const onClickLeft = () => {
  router.push({
    name: "EquipManage",
    params: { data: encodeURIComponent(JSON.stringify(yhzInfo.value)) },
  });
};

const showScrapPopup = ref(false);
const scrapReason = ref(""); // 报废原因
const onScrapPopupClose = () => {
  showScrapPopup.value = false;
  scrapReason.value = "";
};
const onScrapConfirm = async () => {
  try {
    console.log("equipmentDetailInfo", toRaw(equipmentDetailInfo.value));
    const res = await request({
      url: `/snow-ops-platform/yjsb/updateEquipmentStatus`,
      method: "POST",
      data: {
        equipmentId: equipmentDetailInfo.value.rid,
        equipmentStatus: "报废",
        statusDesc: scrapReason.value,
      },
    });
    if (res.code && res.code === "00000") {
      showToast({ type: "success", message: "操作成功" });
      router.push({
        name: "EquipManage",
        params: {
          data: encodeURIComponent(JSON.stringify(yhzInfo.value)),
        },
      });
    } else {
      throw new Error(res.data.message);
    }
  } catch (error) {
    showToast({ type: "error", message: "操作失败" });
    console.log("error", error);
  }
  showScrapPopup.value = false;
  scrapReason.value = "";
};

const showBrokenPopup = ref(false);
const onBrokenPopupOpen = () => {
  showBrokenPopup.value = true;
};
// 损坏相关状态
const brokenReason = ref(""); // 损坏原因
const onBrokenConfirm = async () => {
  try {
    const res = await request({
      url: `/snow-ops-platform/yjsb/updateEquipmentStatus`,
      method: "POST",
      data: {
        equipmentId: equipmentDetailInfo.value.rid,
        equipmentStatus: "损坏",
        statusDesc: brokenReason.value,
      },
    });
    if (res.code && res.code === "00000") {
      showToast({ type: "success", message: "损坏上报成功" });
      router.push({
        name: "EquipManage",
        params: {
          data: encodeURIComponent(JSON.stringify(yhzInfo.value)),
        },
      });
    } else {
      throw new Error(res.data.message);
    }
  } catch (error) {
    showToast({ type: "error", message: "操作失败" });
    console.log("error", error);
  }
  showBrokenPopup.value = false;
  brokenReason.value = "";
};
const onBrokenPopupClose = () => {
  showBrokenPopup.value = false;
  brokenReason.value = "";
};

const showDeletePopup = ref(false);
const onDeletePopupClose = () => {
  showDeletePopup.value = false;
};
const onDeleteConfirm = async () => {
  try {
    showLoadingToast({
      message: "删除中...",
      forbidClick: true,
      loadingType: "spinner",
    });
    const res = await request({
      url: `/snow-ops-platform/yjsb/delete`,
      method: "POST",
      data: {
        rid: equipmentDetailInfo.value.rid,
      },
    });
    if (res.code && res.code === "00000") {
      showToast({ type: "success", message: "删除成功" });
      router.push({
        name: "EquipManage",
        params: {
          data: encodeURIComponent(JSON.stringify(yhzInfo.value)),
        },
      });
    } else {
      throw new Error(res.data.message);
    }
  } catch (error) {
    showToast({ type: "error", message: "删除失败" });
    console.log("error", error);
  }
  showDeletePopup.value = false;
};

const showRemarkPopup = ref(false);
const onRemarkPopupOpen = () => {
  showRemarkPopup.value = true;
};
const onRemarkConfirm = async () => {
  try {
    showLoadingToast({
      message: "提交中...",
      forbidClick: true,
      loadingType: "spinner",
    });

    const res = await request({
      url: "/snow-ops-platform/yjsb/update",
      method: "POST",
      data: {
        equipment: {
          ...equipmentDetailInfo.value,
        },
        photos: photos.value,
      },
    });
    if (res.code && res.code === "00000") {
      showToast({ type: "success", message: "备注更新成功" });
      getEquipmentDetailInfo();
      showRemarkPopup.value = false;
    } else {
      throw new Error(res.data.message);
    }
  } catch (error) {
    showToast({ type: "error", message: error.message || "备注更新失败" });
  } finally {
    showRemarkPopup.value = false;
  }
};
const onRemarkPopupClose = () => {
  getEquipmentDetailInfo();
  showRemarkPopup.value = false;
};

const showEditPopup = ref(false);
// 编辑表单
const editForm = reactive({});

// 获取养护站人员列表
const getPersonList = async () => {
  try {
    const data = {
      pageNum: 1,
      pageSize: 9999,
      yhzid: yhzInfo.value.id,
    };
    const res = await request({
      url: "/snow-ops-platform/yhzry/list",
      method: "get",
      params: data,
    });
    if (res.code === "00000") {
      adminOptions.value = res.data.records.map((item) => ({
        text: item.xm,
        value: item.userId,
      }));
      operatorOptions.value = res.data.records.map((item) => ({
        text: item.xm,
        value: item.userId,
      }));
    } else {
      throw new Error("人员信息获取失败");
    }
  } catch (error) {
    console.log(error);
    showToast({
      type: "fail",
      message: error.message,
    });
  }
};
// 打开编辑弹窗
const onEditPopupOpen = async () => {
  await getPersonList();
  Object.assign(editForm, {
    equipment: equipmentDetailInfo.value,
    photos: photos.value,
  });
  fileList.value = photos.value.map((photo) => ({
    url: photo.photoUrl, // 显示用的URL
    status: "done", // 上传状态为已完成
    message: "上传成功", // 提示信息
    serverUrl: photo.photoUrl, // 保留服务器返回的原始URL
  }));
  showEditPopup.value = true;
};
// 关闭编辑弹窗
const onEditPopupClose = () => {
  showEditPopup.value = false;
};

const showCategoryPicker = ref(false);
const showTypePicker = ref(false);

const categoryField = ref(null);
const typeField = ref(null);

const categoryOptions = [
  { text: "自定义", value: "自定义" },
  { text: "大中修工程设备", value: "大中修工程设备" },
  { text: "小修保养设备", value: "小修保养设备" },
  { text: "交通工具", value: "交通工具" },
];
const typeOptions = [
  { text: "自定义", value: "自定义" },
  { text: "装载机", value: "装载机" },
  { text: "路面修补设备", value: "路面修补设备" },
  { text: "清扫车", value: "清扫车" },
  { text: "压路机", value: "压路机" },
  { text: "洒水车", value: "洒水车" },
  { text: "挖掘机", value: "挖掘机" },
  { text: "运输货车", value: "运输货车" },
  { text: "灌缝设备", value: "灌缝设备" },
  { text: "应急抢险车", value: "应急抢险车" },
  { text: "应急巡查车", value: "应急巡查车" },
  { text: "高空作业车", value: "高空作业车" },
  { text: "除雪设备", value: "除雪设备" },
  { text: "照明设备", value: "照明设备" },
  { text: "护栏维修设备", value: "护栏维修设备" },
  { text: "标线设备", value: "标线设备" },
  { text: "绿化修剪设备", value: "绿化修剪设备" },
  { text: "桥梁维护设备", value: "桥梁维护设备" },
  { text: "发电机", value: "发电机" },
  { text: "沥青洒布车", value: "沥青洒布车" },
  { text: "拖车", value: "拖车" },
  { text: "摊铺机", value: "摊铺机" },
  { text: "抽水设备", value: "抽水设备" },
  { text: "沥青拌和站", value: "沥青拌和站" },
  { text: "水泥拌和机", value: "水泥拌和机" },
  { text: "平地机", value: "平地机" },
  { text: "除雾设备", value: "除雾设备" },
  { text: "无人机", value: "无人机" },
  { text: "推土机", value: "推土机" },
  { text: "稀浆封层设备", value: "稀浆封层设备" },
];

const onCategoryConfirm = (value) => {
  if (value.selectedValues[0] === "自定义") {
    showCategoryPicker.value = false;
    categoryField.value.focus();
  } else {
    editForm.equipment.sbdl = value.selectedValues[0];
    showCategoryPicker.value = false;
  }
};
const onTypeConfirm = (value) => {
  if (value.selectedValues[0] === "自定义") {
    showTypePicker.value = false;
    typeField.value.focus();
  } else {
    editForm.equipment.sblx = value.selectedValues[0];
    showTypePicker.value = false;
  }
};

// 设备管理员
const showAdminPicker = ref(false);
const adminOptions = ref([]);
const onAdminConfirm = (value) => {
  const selectedOption = adminOptions.value.find(
    (opt) => opt.value === value.selectedValues[0]
  );
  if (selectedOption) {
    editForm.equipment.glry = selectedOption.text;
    editForm.equipment.glryid = selectedOption.value;
  }
  showAdminPicker.value = false;
};

// 操作员
const showOperatorPicker = ref(false);
const operatorOptions = ref([]);
const operatorConfirm = (value) => {
  const selectedOption = operatorOptions.value.find(
    (opt) => opt.value === value.selectedValues[0]
  );
  if (selectedOption) {
    editForm.equipment.czy = selectedOption.text;
    editForm.equipment.czyid = selectedOption.value;
  }
  showOperatorPicker.value = false;
};

// 购置日期
const showTimePicker = ref(false);
const currentDate = ref([
  new Date().getFullYear(),
  new Date().getMonth() + 1,
  new Date().getDate(),
]);
const onDateConfirm = ({ selectedValues }) => {
  editForm.gzrq = selectedValues.join("-");
  showTimePicker.value = false;
};

// 设备状态相关
const latestStatusDesc = computed(() => {
  if (
    !equipmentDetailInfo.value.sbzt ||
    equipmentDetailInfo.value.sbzt === "完好"
  )
    return "";

  const records = statusList.value
    .filter((item) => item.equipmentStatus === equipmentDetailInfo.value.sbzt)
    .sort((a, b) => new Date(b.reportTime) - new Date(a.reportTime));

  return records.length > 0 ? `${records[0].statusDesc}` : "暂无相关记录";
});

// 是否应急设备相关
const showEmergencyPicker = ref(false);
const emergencyOptions = [
  { text: "是", value: "是" },
  { text: "否", value: "否" },
];
const onEmergencyConfirm = (value) => {
  editForm.sfyjsb = value.selectedValues[0];
  showEmergencyPicker.value = false;
};

// 是否纳入市级补助相关
const showSubsidyPicker = ref(false);
const subsidyOptions = [
  { text: "是", value: "是" },
  { text: "否", value: "否" },
];
const onSubsidyConfirm = (value) => {
  editForm.sfnrsjbz = value.selectedValues[0];
  showSubsidyPicker.value = false;
};

// 上传附件相关
const fileList = ref([]);
// 文件删除
const handleDelete = (file) => {
  if (file.serverUrl) {
    const index = editForm.photos.findIndex(
      (p) => p.photoUrl === file.serverUrl
    );
    if (index !== -1) {
      editForm.photos.splice(index, 1);
    }
  }
};

// 文件上传
const afterRead = async (file) => {
  try {
    const toast = showLoadingToast({
      message: "上传中...",
      forbidClick: true,
      duration: 0, // 设置为0表示不会自动关闭
    });
    const formData = new FormData();
    formData.append("file", file.file);
    const res = await request({
      url: "/snow-ops-platform/file/upload",
      method: "post",
      data: formData,
    });
    toast.close();
    if (res.code === "00000") {
      editForm.photos.push({ photoUrl: res.data });
      const index = fileList.value.findIndex((f) => f.file === file.file);
      if (index !== -1) {
        fileList.value[index].serverUrl = res.data;
      }

      console.log("editForm.photos", toRaw(editForm.photos));
      console.log("fileList.value", fileList.value);
    } else {
      throw new Error(res.message);
    }
  } catch (error) {
    toast.close();
    showToast({
      type: "fail",
      message: error.message,
    });
  }
};

// 提交修改
const onEditSubmit = async () => {
  try {
    showLoadingToast({ message: "提交中...", forbidClick: true });
    console.log('editForm',toRaw(editForm))

    const res = await request({
      url: "/snow-ops-platform/yjsb/update",
      method: "POST",
      data: editForm,
    });
    if (res.code && res.code === "00000") {
      showToast({ type: "success", message: "修改成功" });
      getEquipmentDetailInfo(); // 刷新详情数据
      showEditPopup.value = false;
    } else {
      throw new Error(res.message);
    }
  } catch (error) {
    showToast({ type: "fail", message: error.message || "修改失败" });
    console.log("error", error);
  }
};

const showImage = (photos) => {
  const photosArr = photos.map((item) => item.photoUrl);
  showImagePreview({
    images: photosArr,
    closeable: true,
  });
};
</script>
  
  <style scoped>
.home {
  padding-top: var(--van-nav-bar-height); /* 自动匹配导航栏高度 */
}

.content {
  padding: 16px 16px 80px 16px;
}

.grid {
  margin-top: 16px;
}

.btn {
  margin-top: 24px;
}

.status-tag {
  display: inline-block;
  padding: 3px 8px;
  border-radius: 4px;
  color: white;
  font-size: 12px;
}
.status-good {
  background-color: #07c160;
}
.status-warning {
  background-color: #ff976a;
}
.status-danger {
  background-color: #ee0a24;
}
.device-form {
  padding: 16px 16px 80px 16px;
}
</style>
  