<template>
  <!-- 设备列表 -->
  <div class="devicePage flex-col">
    <div class="listBox">
      <s-header :name="sys ? sys.title : $t('device.managementCenter')" :noback="true" :isFixed="false"></s-header>
      <van-list v-model:loading="loading" v-model:error="error" :error-text="$t('public.requestFailed')"
        :finished="finished" :finished-text="$t('public.noMore')" offset="100" :immediate-check="false" @load="onLoad">
        <div class="deviceBox1 flex-col">
          <div class="searchRow flex-row justify-between">
            <div class="flex-col">
              <div class="flex-row justify-between bd3">
                <div class="flex-col outer4"></div>
                <span class="flex-col txt2">
                  {{ $t("device.dataOverview") }}</span>
              </div>
            </div>
            <div class="flex-col">
              <div class="main5 flex-row justify-between">
                <van-popover v-model:show="showPopover" placement="left-start" theme="dark" :actions="actions"
                  @select="selectLabel">
                  <template #reference>
                    <van-icon name="bars" class="fixed-icon o-pr-15" style="font-size: 0.55rem;" color="#4d6add" />
                  </template>
                </van-popover>
                <img class="label2" src="../../assets/device/searchIcon.png" @click="searchClick" />
                <!-- <div class="TextGroup2 flex-col">
                  <span class="txt3">{{ $t("device.search") }}</span>
                </div> -->
              </div>
            </div>
          </div>
          <img class="pic1" src="../../assets/device/line.png" />
          <div class="o-plr-15 o-ptb-20">
            <div class="bd1 flex-col">
              <div class="box2 l-f l-flex-c l-flex-j-a">
                <div @click="eqeStatusClk(1)" class="TextGroup3 flex-col">
                  <div class="group1 flex-col justify-between align-center">
                    <span class="word4">{{ equipStatus.machineUseNum }}</span>
                    <span class="info1">{{ $t("device.totalNumberOfRuns") }}</span>
                  </div>
                </div>
                <div @click="eqeStatusClk('')" class="TextGroup3 flex-col">
                  <div class="group1 flex-col justify-between align-center">
                    <span class="word4">{{ equipStatus.machineTotalNum }}</span>
                    <span class="info1">{{ $t("device.totalNumberOfEquipment") }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="deviceBox2 flex-col justify-between">
          <van-tabs v-model:active="active" @click-tab="clickLabel" class="tabs2 o-pb-15">
            <van-tab :title="$t('device.whole')" name="">
            </van-tab>
            <van-tab v-for="item in labelList" :name="item.id" :key="item" :title="item.name">
            </van-tab>
          </van-tabs>
          <div class="section1 flex-col">
            <div class="outer1 flex-col o-plr-15">
              <div v-for="item in list" :key="item" class="o-pb-20">
                <div class="bd1 l-flex-between">
                  <div class="l-flex-RC">
                    <div class="layer1 flex-col"></div>
                    <div class="txtBox">
                      <span class="txt1">{{ item.name == null ? item.clientId.slice(-6) : item.name }}</span>
                    </div>
                  </div>
                  <div v-if="item.hasTodayAlarm" :class="{ 'flash-icon': showAlert }" class="box4 o-mr-5"></div>
                  <div v-if="!item.hasTodayAlarm" class="layer2 o-mr-5"
                    :class="{ deviceOn: item.eqeStatus === 1, layerLeft: item.hasTodayAlarm, }"></div>
                </div>
                <!-- 机器编码 -->
                <span class="txt1 o-mt-10">{{ $t("device.machineUniqueCode") }}：{{ item.clientId }}</span>
                <!-- 锁机状态 -->
                <span v-if="user.type < 1" class="txt1 o-mt-10">
                  {{ $t("device.lockCondition") }}：{{ item.isBlocked ? $t("device.lockState") : $t("device.unLockState") }}
                </span>
                <!-- 温湿度 -->
                <!-- <span v-if="(item.machineType == '0' || item.machineType == null) && item.equimentType != 'P30'"
                  class="txt1 o-mt-10">
                  <van-col class="word5" style="">{{ $t("device.furnaceHeadTemperature") + '：' +
                    item.furnaceTm
                    + $t("device.degree") }}</van-col>
                  <van-col class="word5" style="">{{ '&nbsp;' + $t("device.temperatureInCabinet") + '：' + item.cabinetTm
                    + $t("device.degree") }}</van-col>
                  <van-col class="word5" style="">{{ '&nbsp;' + $t("device.humidityInCabinet") + '：' + item.cabinetHd
                    + $t("device.humidity") }}</van-col>
                </span> -->
                <span v-if="(item.machineType == '0' || item.machineType == null) && item.equimentType != 'P30'"
                  class="txt1 o-mt-10">
                  {{ $t("device.temperatureInCabinet") + '：' + item.cabinetTm
                    + $t("device.degree") }}
                </span>
                <span v-if="(item.machineType == '0' || item.machineType == null) && item.equimentType != 'P30'"
                  class="txt1 o-mt-10">
                  {{ $t("device.humidityInCabinet") + '：' + item.cabinetHd
                    + $t("device.humidity") }}
                </span>
                <span v-if="(item.machineType == '0' || item.machineType == null) && item.equimentType != 'P30'"
                  class="txt1 o-mt-10">
                  {{ $t("device.furnaceHeadTemperature") + '：' +
                    item.furnaceTm
                    + $t("device.degree") }}
                </span>
                <img v-if="item.checkType" class="pic1" referrerpolicy="no-referrer" src="../../assets/home/line.png" />
                <div class="contentBottomCon" v-if="item.checkType">

                  <!-- 所属商家 -->
                  <!-- <span class="txt1 o-mt-10">{{ $t("device.affiliatedMerchants") }}：{{ item.adminUserName }}</span> -->
                  <div class="contentWord kBordBott">{{ $t("device.affiliatedMerchants") }}：{{ item.adminUserName }}
                  </div>
                  <!-- 睡眠状态 -->
                  <div class="contentWord kBordBott">
                    <span class="o-mr-10">{{ $t("device.sleepState") }}：{{ item.isSleep ? $t("device.sleeping") :
                      $t("device.notSleeping") }}</span>
                    <van-switch :model-value="item.isSleep" size="23px" @click="changeSleep(item)" />
                  </div>
                  <!-- 睡眠描述 -->
                  <div v-if="item.isSleep" class="contentWord kBordBott">
                    <span class="">{{ $t("device.sleepDesc") }}：</span>
                    <van-field colon center class="word2" v-model="item.sleepDesc" v-if="!sleepDescBoxShow"
                      :placeholder="$t('device.sleepDescPlace')" label-width="auto">
                      <template #button class="button_1">
                        <van-button type="primary" @click="sleepDescChg(item.sleepDesc, item.id)">
                          {{ $t("device.confirm") }}
                        </van-button>
                        <van-button type="primary" @click="editSleepDesc()">{{ $t("device.cancel") }}</van-button>
                      </template>
                    </van-field>
                    <div class="l-flex-RC" v-else>
                      <span class="o-mr-10">{{ item.sleepDesc == null ? $t("device.SuspendBusiness") : item.sleepDesc
                        }}</span>
                      <van-button type="primary" @click="editSleepDesc()">{{ $t("device.modify") }}</van-button>
                    </div>
                  </div>
                  <span v-if="item.machineType == null || item.machineType == '0'"
                    class="contentWord kBordBott l-flex-RC">
                    <span>{{ $t("device.clickRestart") }}：</span>
                    <van-button @click="restartHead(item.id)" type="primary">{{ $t("device.restartHead") }}</van-button>
                  </span>
                  <!-- 炉头状态 -->
                  <div class="contentWord kBordBott" v-if="item.machineType == null || item.machineType == '0'">
                    <span>
                      {{ (item.machineType == '0' || item.machineType == null) ? $t("device.furnHeadStatus") :
                        $t("device.deviceStatus") }}：
                      {{ item.eqeStatus === 1 ? $t("device.opened") : $t("device.closed") }}
                    </span>
                    <div class="o-ml-10">
                      <van-button @click="openCloseHead(item.id, 1)" type="primary">{{ $t("device.open") }}</van-button>
                      <van-button @click="openCloseHead(item.id, 0)" type="primary">{{ $t("device.close")
                        }}</van-button>
                    </div>
                  </div>
                  <!-- <span class="txt5 o-ptb-10 kBordBott l-flex-RC"><span>远程开门：</span>
                    <van-button type="primary">开门</van-button>
                  </span> -->

                  <!-- 设备地址 -->
                  <!-- <span class="txt1 o-ptb-7">{{ item.fullName }}</span> -->
                  <!-- 定位： -->
                  <!-- <div>
                    <span v-if="item.latitude" class="txt5 o-ptb-7 kBordBott l-flex-RC">
                      <span class="info1">{{
                        $t("device.position") }}：</span>
                      <van-button @click="viewPosiClk(item)" type="primary">{{
                        $t("device.view")
                      }}</van-button>
                    </span>
                  </div> -->

                  <!-- 定位： -->
                  <span v-if="item.latitude" class="contentWord kBordBott l-flex-LC justify-space-between">
                    <span>{{ $t("device.position") }}：</span>
                    <a class="clickable-link" @click="viewPosiClk(item)">{{ item.fullName }}</a>
                  </span>

                  <!-- 机器参数 -->
                  <!-- <van-row class="layer5 kBordBott" justify="space-between"
                    v-if="(item.machineType == '0' || item.machineType == null) && item.equimentType != 'P30'">
                    <van-col class="word5" style="">{{ $t("device.furnaceHeadTemperature") }}：{{
        item.furnaceTm
      }}{{ $t("device.degree") }}</van-col>
                    <van-col class="word5" style="">{{ $t("device.temperatureInCabinet") }}：{{
        item.cabinetTm
      }}{{ $t("device.degree") }}</van-col>
                    <van-col class="word5" style="">{{ $t("device.humidityInCabinet") }}：{{
        item.cabinetHd
      }}{{ $t("device.humidity") }}</van-col>
                  </van-row> -->


                  <van-row class="layer5 kBordBott" justify="space-between" v-if="item.machineType == '1'">
                    <van-col class="word5" style="">{{ $t("device.cornGeneratorTemperature") }}：{{
                      item.cabinetTm
                    }}{{ $t("device.degree") }}</van-col>
                    <van-col class="word5" style="">{{ $t("device.stirringTemperature") }}：{{
                      item.cabinetHd
                    }}{{ $t("device.degree") }}</van-col>
                    <van-col class="word5" style="">{{ $t("device.cupQuantity") }}：{{ item.furnaceTm
                      }}</van-col>
                  </van-row>
                  <template v-if="item.isMaterialUse === '1' && (item.machineType == '0' || item.machineType == null)">
                    <van-row justify="space-between" class="sugarTxt kBordBott">
                      <van-col style="">
                        {{ $t("device.whiteSugar") }}：{{ Format_calcuDecial(item.whiteSugar) }}%
                      </van-col>
                      <van-col>
                        {{ $t("device.redSugar") }}：{{ Format_calcuDecial(item.redSugar) }}%
                      </van-col>
                      <van-col>
                        {{ $t("device.yellowSugar") }}：{{ Format_calcuDecial(item.yellowSugar) }}%
                      </van-col>
                      <van-col style="">
                        {{ $t("device.blueSugar") }}：{{ Format_calcuDecial(item.blueSugar) }}%
                      </van-col>
                    </van-row>
                    <div class="sugarTxt kBordBott">
                      <span>{{ $t("device.stick") }}：{{
                        Format_calcuDecial(item.stick)
                      }}%</span>
                    </div>
                    <van-row gutter="20" class="sugarTxt kBordBott">
                      <van-col>
                        {{ $t("device.water") }}：{{ Format_calcuDecial(item.water) }}%
                      </van-col>
                      <van-col>
                        {{ $t("device.wasteWater") }}：{{ Format_calcuDecial(item.wasteWater) }}%
                      </van-col>
                    </van-row>
                    <!-- 一键补料 -->
                    <span class="contentWord kBordBott">
                      <span class="l-flex-RC">{{ $t("device.oneKeyFeed") }}：
                        <van-button class="replenishment" @click="replenishmentClk(item)" type="primary">{{
                          $t("device.replenishment") }}
                        </van-button>
                      </span>
                      <!-- <a class="replenishment" @click="replenishmentClk(item)">{{ $t("device.replenishment")
                      }}</a> -->
                    </span>
                  </template>
                  <!-- 最近刷新时间 -->
                  <span class="contentWord kBordBott">{{ $t("device.lastRefreshTime") }}：{{
                    showDateTime(item.lastUpdateTime)
                  }}</span>
                  <!-- 音量 -->
                  <span v-if="item.machineType != '2'" class="contentWord kBordBott">{{ $t("device.volume") }}：{{
                    item.volume }}</span>
                  <!-- 报警内容 -->
                  <div class="contentWord kBordBott l-flex-LC justify-space-between">
                    <span>{{ $t("device.alarmContent") }}：</span>
                    <!-- <div class="l-flex-RC"> -->
                    <span class="word3">{{
                      item.alarmList && item.alarmList[0] && item.alarmList[0].alarmContent
                        ? showDateTime(item.alarmList[0].occurrenceTime) + " " + item.alarmList[0].alarmContent
                        : $t("device.alarmContentNoData")
                    }}
                    </span>
                    <van-button v-if="item.alarmList && item.alarmList[0] && item.alarmList[0].alarmContent"
                      style="flex-shrink: 0; margin: 0;" type="primary" color="#07c160"
                      :text="$t('device.eliminateAlarm')" @click="clearAlarm(item.alarmList[0], item)"></van-button>
                    <!-- </div> -->
                  </div>
                  <div class="editDeviceBtnCon l-flex-center o-mt-10">
                    <!-- 详细信息 -->
                    <div class="l-flex-RC" @click="deviceSet(item)">
                      <span class="c-text-14">{{
                        $t("device.editDevice")
                      }}</span>
                      <div class="box2 flex-col"></div>
                    </div>

                    <!-- 远程操作 -->
                    <div class="l-flex-RC" @click="deviceOprShow(item)">
                      <span class="c-text-14">{{
                        $t("device.commonOperations")
                      }}</span>
                      <div class="box2 flex-col"></div>
                    </div>
                  </div>
                  <div style="height: 10px;"></div>
                </div>
                <div class="bd6 l-flex-center o-ptb-7" @click="item.checkType = !item.checkType">
                  <div class="l-flex-RC">
                    <span class="info2 o-mr-2">{{
                      item.checkType ? $t("device.stow") : $t("device.seeMore")
                    }}</span>
                    <div class="group2 flex-col" :class="{ checkType: item.checkType }"></div>
                  </div>
                </div>
              </div>
              <van-back-top @click="backTop" right="5vw" bottom="10vh" />
            </div>
          </div>
        </div>
      </van-list>
    </div>
    <deviceOper ref="oprRef" @operfinish="operFinish"></deviceOper>
    <!-- 搜索弹出框 -->
    <deviceSearch ref="searchRef" @search="search($event)"></deviceSearch>
    <div style="height: 50px;"></div>
    <!-- <nav-bar></nav-bar> -->
  </div>
</template>


<script>
import {
  Api_postMachineNum,
} from "../../service/home";
import { onMounted, reactive, toRefs, ref, onActivated } from "vue";
import { showFailToast, showSuccessToast, showToast, showConfirmDialog } from "vant";
// import navBar from "../../components/NavBar";
import sHeader from "../../components/SimpleHeader";
import { getLoginUser, Format_calcuDecial, styleUrl } from "../../common/js/utils";
import {
  getDeviceList,
  eliminate,
  Api_getReplenishment,
  changeSleepDesc,
  setFurnace,
  sleepEquipment,
} from "../../service/device/index";
import deviceSearch from "./deviceSearch";
import deviceOper from "./deviceOper";
import { onBeforeRouteLeave, useRouter } from "vue-router";
import dateUtil from "../../utils/dateUtil";
import { useI18n } from "vue-i18n";
import { onBeforeUnmount } from "vue";
import { Api_getLabelList } from "../../service/labelMan";


export default {
  name: "device",
  components: { sHeader, deviceSearch, deviceOper },
  setup() {
    const { t } = useI18n();
    const searchRef = ref(null);
    const oprRef = ref(null);
    const list = ref([]);
    const loading = ref(true);
    const error = ref(false);
    const finished = ref(false);
    const router = useRouter();
    const sys = ref(null);
    const user = getLoginUser();
    const verticalScrollPosition = ref(0);
    const labelList = ref([]);

    // 返回顶部
    const backTop = () => {
      window.scrollY = 0;
    }

    onActivated(() => {
      // 当组件被激活时，可能是从 keep-alive 缓存中激活的
      // 这时重新添加滚动事件监听器
      console.log("进入时的位置", verticalScrollPosition.value);
      document.documentElement.scrollTop = verticalScrollPosition.value;
      document.body.scrollTop = verticalScrollPosition.value;
      window.scrollY = verticalScrollPosition.value;
      // window.addEventListener('scroll', handleScroll);
    });


    onBeforeRouteLeave(() => {
      verticalScrollPosition.value = document.documentElement.scrollTop || document.body.scrollTop || window.scrollY;
      console.log("离开时的位置", verticalScrollPosition.value);
    })

    // 在组件卸载前清除定时器
    onBeforeUnmount(() => {
      clearInterval(updateDataInterval);
    });


    const updateDataInterval = () => {
      // 每隔5分钟更新数据
      setInterval(() => {
        init();
        if (oprRef.value) {
          oprRef.value.closeOper();
        }
        // verticalScrollPosition.value = 0;
      }, 5 * 60 * 1000); // 5分钟的毫秒数
    };
    //控制睡眠描述的显示隐藏
    const sleepDescBoxShow = ref(true);
    // 页面列表查询参数
    let searchParams = reactive({
      id: "", // 用户账户id
      // adminName: '', // 用户登录名
      current: 1, // 页数
      size: 10, // 页大小
      todayDate: dateUtil.formateDate(new Date(), "yyyy-MM-dd"), // 当天时间
      labelId: "", // 分组标签
    });
    // 初始化页面获取列表
    const showAlert = ref(false);
    onMounted(() => {
      sleepDescBoxShow.value = true;
      init();
      updateDataInterval();
      // window.addEventListener('scroll', handleScroll);
      // 加载样式
      styleUrl('device');
      setInterval(() => {
        showAlert.value = !showAlert.value;
      }, 500); // 1000毫秒即1秒
    });
    // 初始化
    const init = () => {
      // 获取设备情况
      getMachineNum();
      getLabelList();
      if (localStorage.getItem("loginSys")) {
        const loginSysString = localStorage.getItem("loginSys");
        sys.value = JSON.parse(loginSysString);
      }
      list.value = [];
      searchParams.current = 1;
      if (user) {
        searchParams.id = user.id;
        // if (user.isAdmined) {
        //   searchParams.adminName = user.username;
        // }
        getList();
      }
    };

    // 获取设备标签
    const getLabelList = async () => {
      // console.log("adminId>>>>", user.id);
      Api_getLabelList({
        adminId: user.id,
        type: "1"
      }).then((res) => {
        const { data } = res.data;
        labelList.value = data;
      })
    }

    // 获取设备列表数据
    const getList = async () => {
      finished.value = false;
      const { data } = await getDeviceList(Object.assign({}, searchParams));
      if (data.code === "00000") {
        if (searchParams.current === 0) {
          list.value = [];
        }
        // 列表值叠加
        list.value = list.value.concat(
          data.data.records.map((item) => {
            if (item.sleepDesc == null) {
              item.sleepDesc = t("device.SuspendBusiness");
            }
            return {
              ...item,
              checkType: false,
            };
          })
        );
        if (list.value.length === data.data.total) {
          finished.value = true;
        }
        loading.value = false;
      } else {
        showFailToast(data.message);
      }
    };
    // 滚动加载
    const onLoad = () => {
      if (!finished.value) {
        // console.log("滚动加载")
        searchParams.current = searchParams.current + 1;
        getList();
      }
    };
    // 搜索点击
    const searchClick = () => {
      searchRef.value.showSearch();
    };
    // 搜索条件触发查询
    const search = (e) => {
      list.value = [];
      loading.value = true;
      searchParams.current = 1;
      searchParams = Object.assign(searchParams, e);
      getList();
      getMachineNum();
    };
    // 跳转设备编辑
    const deviceSet = (e) => {
      router.push({ path: "deviceSet", query: { deviceId: e.id } });
    };
    // 常用操作弹窗展示触发
    const deviceOprShow = (e) => {
      oprRef.value.showOper(e);
    };
    // 消除报警
    const clearAlarm = async (e, e1) => {
      const params = {
        id: e.id,
        name: e.name,
        selfName: e.selfName,
        areaId: e.areaId,
        channel: e.channel,
        contactName: e.contactName,
        contactPhone: e.contactPhone,
        flowers: e.flowers,
        operationalName: e.operationalName,
        operationalPhone: e.operationalPhone,
        timeRuleId: e.timeRuleId,
      };
      const { data } = await eliminate(Object.assign({}, params));
      if (data.code) {
        showSuccessToast(t("device.successfullyEliminatedTheAlarm"));
        setTimeout(() => {
          e.alarmContent = "";
          e1.hasTodayAlarm = false;
        }, 1000);
      } else {
        showFailToast(data.message);
      }
    };
    const showDateTime = (date) => {
      if (!date) {
        return "";
      }
      const currentDate = new Date(dateUtil.formateDate(new Date(date), "yyyy/MM/dd hh:mm:ss"));
      return dateUtil.timeZoneDate(currentDate);
    };

    // 点击查看定位
    const viewPosiClk = (row) => {
      console.log("row 是 >>>", row);
      if (row.latitude) {
        router.push({
          path: "viewPosition",
          query: {
            latitude: row.latitude,
            longitude: row.longitude,
            fullName: row.fullName,
          },
        });
      } else {
        showToast(`${t("device.noPosition")}！！！`);
      }
    };

    // 点击补料
    const replenishmentClk = (row) => {
      // console.log("row >>>", row);
      showConfirmDialog({
        title: t('user.tips'),
        message: t('device.isReplenishment'),
      }).then(async () => {
        const { data } = await Api_getReplenishment({
          equipmentId: row.id
        });
        if (data.code) {
          showSuccessToast(t("device.sentSuccessfully"));
          setTimeout(() => {
            // router.go(0);
            init();
          }, 1500);
        } else {
          showFailToast(data.message);
        }
      }).catch(() => {
        return;
      })
      // Api_getReplenishment({ equipmentId: row.id }).then((res) => {
      //   console.log("res >>>", res);
      //   // Toast(res.data.message);
      //   showDialog({
      //     message: t('device.sentSuccessfully'),
      //   }).then(() => {
      //     //返回上一页
      //     router.go(0);
      //   });
      //   setTimeout(() => {
      //     getList();
      //   }, 500);
      // });
    };
    // 操作弹窗完成的回调
    const operFinish = () => {
      init();
    };
    // 设备状况
    const equipStatus = ref({});
    // 获取设备情况
    const getMachineNum = () => {
      Api_postMachineNum({
        adminId: user.id,
        companyType: searchParams.companyType
      }).then((res) => {
        equipStatus.value = res.data.data || {};
      });
    };
    // 点击运行总数和总设备数
    const eqeStatusClk = (val) => {
      searchParams.eqeStatus = val;
      // 初始化
      searchParams.current = 1;
      list.value = [];
      getList();
    };
    // 点击修改图标
    const editSleepDesc = () => {
      sleepDescBoxShow.value = !sleepDescBoxShow.value;
    }
    // 点击睡眠描述的确定按钮
    const sleepDescChg = async (sleepDesc, id) => {
      console.log(sleepDesc);
      if (!sleepDesc) {
        showToast(t("device.sleepDescPlace"));
      } else {
        const { data } = await changeSleepDesc({
          equipmentId: id,
          sleepDesc,
        });
        if (data.code === "00000") {
          sleepDescBoxShow.value = true;
          showToast(data.message);
          // setTimeout(() => {
          //   gettAdminGetRelation();
          // }, 500);
        }
      }
    }

    // 点击标签
    const active = ref("");
    const clickLabel = (item) => {
      console.log(item);
      list.value = [];
      searchParams.current = 1;
      searchParams.labelId = item.name;
      getList();
    }
    // 分组管理
    const showPopover = ref(false);
    const actions = [
      { text: t("device.group"), value: '0' },
      { text: t("device.addGroup"), value: '1' },
    ];
    const selectLabel = (action) => {
      // showToast(action.value);
      if (action.value == '0') {
        router.push('/labelMan');
      }
      if (action.value == '1') {
        router.push("/labelManAdd");
      }
    }

    // 睡眠切换
    const changeSleep = (item) => {
      let eqeStatus = 1;
      showConfirmDialog({
        title: t('user.tips'),
        message: t("device.changeSleep"),
      }).then(async () => {
        if (item.isSleep) {
          eqeStatus = 0;
        }
        const { data } = await sleepEquipment({
          equipmentId: item.id,
          eqeStatus,
        });
        if (data.code) {
          showSuccessToast(t("device.changeSleepSuccess"));
          setTimeout(() => {
            // router.go(0);
            init();
          }, 1000);
        } else {
          showFailToast(data.message);
        }
      }).catch(() => {
        return;
      })
    };

    // 重启炉头
    const restartHead = (id) => {
      showConfirmDialog({
        title: t('user.tips'),
        message: t('device.restartFurnaceHeadTips'),
      }).then(async () => {
        const { data } = await setFurnace({
          equipmentId: id,
          eqeStatus: 1,
        });
        if (data.code) {
          showSuccessToast(t("device.restartSucceeded"));
          setTimeout(() => {
            router.go(0);
          }, 1000);
        } else {
          showFailToast(data.message);
        }
      }).catch(() => {
        return;
      })
    };
    // 开启/关闭炉头
    const openCloseHead = (id, status) => {
      console.log("id", id);
      console.log("status", status);
      showConfirmDialog({
        title: t('user.tips'),
        message: (status == 1 ? t("device.openFurnaceHeadTips") : t("device.closeFurnaceHeadTips")),
      }).then(async () => {
        const { data } = await setFurnace({
          equipmentId: id,
          eqeStatus: status,
        });
        if (data.code) {
          showSuccessToast((status == 1 ? t("device.open") : t("device.close")) + t("device.success"));
          setTimeout(() => {
            router.go(0);
          }, 1000);
        } else {
          showFailToast(data.message);
        }
      }).catch(() => {
        return;
      })
    };


    return {
      showAlert,
      ...toRefs(searchParams),
      list,
      loading,
      error,
      finished,
      onLoad,
      searchRef,
      searchClick,
      search,
      deviceSet,
      clearAlarm,
      oprRef,
      deviceOprShow,
      showDateTime,
      sys,
      viewPosiClk,
      replenishmentClk,
      Format_calcuDecial,
      operFinish,
      equipStatus,
      eqeStatusClk,
      editSleepDesc,
      sleepDescBoxShow,
      sleepDescChg,
      changeSleep,
      backTop,
      user,
      labelList,
      clickLabel,
      active,
      actions,
      showPopover,
      selectLabel,
      restartHead,
      openCloseHead,
    };
  },
};
</script>

<style lang="less" scoped>
@import "../../common/style/common";
@import "../../styles/device/index";
</style>
