<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" @click="searchClick">
                <img class="label2" src="../../assets/device/searchIcon.png" />
              </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="TextGroup4 flex-col">
                  <div class="main6 flex-col justify-between align-center">
                    <span class="word5">{{ equipStatus.machineTotalNum }}</span>
                    <span class="word6">{{
                      $t("device.totalNumberOfEquipment")
                    }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="deviceBox2 flex-col justify-between">
          <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 class="l-flex-RC">
                    <!-- 报警标志 -->
                    <!-- <div v-if="item.hasTodayAlarm" class="box4 flex-col"> -->
                    <!-- <img class="pic1" src="../../assets/device/alarm.png" /> -->
                    <!-- <img class="pic1" src="../../assets/home/M15.png" /> -->
                    <!-- </div> -->
                    <div v-if="item.hasTodayAlarm" class="l-flex-between o-pl-5">
                      <div class="box4 flex-col "></div>
                      <span class="o-pl-2" style="color: #fe5d55">{{ $t("device.alarmClock") }}</span>
                    </div>
                    <div class="layer2 flex-col" :class="{
                      deviceOn: item.eqeStatus === 1,
                      layerLeft: item.hasTodayAlarm,
                    }"></div>
                  </div>
                </div>
                <span class="txt1 o-mt-10">{{ $t("device.affiliatedMerchants") }}：{{
                  item.adminUserName
                }}</span>
                <span class="txt1 o-mt-10 kBordBott">{{ $t("device.machineUniqueCode") }}：{{
                  item.clientId
                }}</span>
                <div class="contentBottomCon" v-if="item.checkType">
                  <img class="pic1" referrerpolicy="no-referrer" src="../../assets/home/line.png" />
                  <!-- 睡眠状态 -->
                  <div class="word4 flex-row justify-between o-ptb-4 kBordBott">
                    <span class="info1 o-ptb-5 kBordBott">{{ $t("device.sleepState") }}：{{
                      item.isSleep
                      ? $t("device.sleeping")
                      : $t("device.notSleeping")
                    }}</span>
                  </div>
                  <div v-if="item.isSleep" class="layer3 o-ptb-7">
                    <span class="word1">
                      <div v-if="!sleepDescBoxShow">
                        <van-field colon center class="word2" v-model="item.sleepDesc"
                          :placeholder="$t('device.sleepDescPlace')" :label="$t('device.sleepDesc')" label-width="auto">
                          <template #button class="button_1">
                            <van-button size="small" type="primary" @click="sleepDescChg(item.sleepDesc, item.id)">{{
                              $t("device.confirm") }}
                            </van-button>
                            <van-button size="small" type="primary" @click="editSleepDesc()">{{ $t("device.cancel")
                            }}</van-button>
                          </template>
                        </van-field>
                        <!-- </span> -->
                      </div>
                      <div v-else>
                        <span class="word3 o-pr-10">{{ $t("device.sleepDesc") }}:</span>
                        <span class="word3">{{ item.sleepDesc == null ? $t("device.SuspendBusiness") :
                          item.sleepDesc }}</span>
                        <van-icon name="edit" size="18" class="editIcon" @click="editSleepDesc()" />
                      </div>
                    </span>
                  </div>
                  <!-- <span class="txt5 o-ptb-10 kBordBott l-flex-RC"><span>一键重启炉头：</span>
                    <van-button type="primary">重启</van-button>
                  </span> -->
                  <!-- 炉头状态 -->
                  <div class="word4 o-ptb-8">
                    <span class="word3 o-pr-5" v-if="item.machineType == '0' || item.machineType == null">{{
                      $t("device.furnHeadStatus") }}: </span>
                    <span class="word3 o-pr-5" v-else>{{ $t("device.deviceStatus") }}: </span>
                    <span>{{ item.eqeStatus === 1 ? $t("device.opened") : $t("device.closed") }}
                    </span>
                    <!-- <div class="l-flex-RC">
                      <van-button type="primary">开启</van-button>
                      <van-button type="primary">关闭</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> -->

                  <!-- 定位： -->
                  <div>
                    <span v-if="item.latitude" class="txt5 o-ptb-3 kBordBott l-flex-RC">
                      <span class="info1">{{ $t("device.position") }}：</span>
                      <a class="clickable-link o-ptb-7" @click="viewPosiClk(item)">{{ item.fullName }}</a>
                    </span>
                  </div>
                  <!-- 机器参数 -->
                  <van-row class="layer5 o-pt-7 kBordBott" justify="space-between"
                    v-if="(item.machineType == '0' || item.machineType == null) && item.equimentType != 'P30'">
                    <van-col class="word5" style="margin-bottom: 12px;">{{ $t("device.furnaceHeadTemperature") }}：{{
                      item.furnaceTm
                    }}{{ $t("device.degree") }}</van-col>
                    <van-col class="word5" style="margin-bottom: 12px;">{{ $t("device.temperatureInCabinet") }}：{{
                      item.cabinetTm
                    }}{{ $t("device.degree") }}</van-col>
                    <van-col class="word5" style="margin-bottom: 12px;">{{ $t("device.humidityInCabinet") }}：{{
                      item.cabinetHd
                    }}{{ $t("device.humidity") }}</van-col>
                  </van-row>
                  <van-row class="layer5 o-pt-7 kBordBott" justify="space-between" v-if="item.machineType == '1'">
                    <van-col class="word5" style="margin-bottom: 12px;">{{ $t("device.stirringTemperature") }}：{{
                      item.stirTm
                    }}{{ $t("device.degree") }}</van-col>
                    <van-col class="word5" style="margin-bottom: 12px;">{{ $t("device.cornGeneratorTemperature") }}：{{
                      item.cornGeneratorTm
                    }}{{ $t("device.degree") }}</van-col>
                    <van-col class="word5" style="margin-bottom: 12px;">{{ $t("device.cupQuantity") }}：{{ item.cupQuantity
                    }}</van-col>
                  </van-row>
                  <template v-if="item.isMaterialUse === '1' && (item.machineType == '0' || item.machineType == null)">
                    <van-row justify="space-between" class="sugarTxt o-pt-7 kBordBott">
                      <van-col style="margin-bottom: 12px;">
                        {{ $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="margin-bottom: 8px;">
                        {{ $t("device.blueSugar") }}：{{ Format_calcuDecial(item.blueSugar) }}%
                      </van-col>
                    </van-row>
                    <div class="info1 o-ptb-5 kBordBott">
                      <span>{{ $t("device.stick") }}：{{
                        Format_calcuDecial(item.stick)
                      }}%</span>
                    </div>
                    <van-row gutter="50" class="sugarTxt o-ptb-7 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="info1 o-ptb-5 kBordBott l-flex-RC"><span>{{ $t("device.oneKeyFeed") }}：</span>
                      <!-- <van-button @click="replenishmentClk(item)" type="primary">{{ $t("device.replenishment") }}
                      </van-button> -->
                      <a class="replenishment o-ptb-7" @click="replenishmentClk(item)">{{ $t("device.replenishment")
                      }}</a>
                    </span>
                  </template>
                  <!-- 最近刷新时间 -->
                  <span class="info1 o-ptb-7 kBordBott">{{ $t("device.lastRefreshTime") }}：{{
                    showDateTime(item.lastUpdateTime)
                  }}</span>
                  <!-- 音量 -->
                  <span v-if="item.machineType != '2'" class="info2 o-ptb-7 kBordBott">{{ $t("device.volume") }}：{{ item.volume }}</span>
                  <!-- 报警内容 -->
                  <div class="l-flex-RC o-ptb-7">
                    <span class="info3 kBordBott">{{ $t("device.alarmContent") }}：</span>
                    <div class="info4 l-flex-RC">
                      <span class="info5 o-pr-10 kBordBott">{{
                        item.alarmList && item.alarmList[0]
                        ? item.alarmList[0].alarmContent
                        : $t("device.alarmContentNoData")
                      }}
                      </span>
                      <van-button v-if="item.alarmList && item.alarmList[0]" type="primary" size="small" color="#07c160"
                        :text="$t('device.eliminateAlarm')" @click="clearAlarm(item.alarmList[0])"></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 o-ml-30" @click="deviceOprShow(item)">
                      <span class="c-text-14">{{
                        $t("device.commonOperations")
                      }}</span>
                      <div class="box2 flex-col"></div>
                    </div>
                  </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 style="background-color: #2d87c8;" @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>
  </div>
</template>


<script>
import {
  Api_postMachineNum,
} from "../../service/home";
import { onMounted, reactive, toRefs, ref, onActivated } from "vue";
import { showFailToast, showSuccessToast, showToast, showDialog } from "vant";
import sHeader from "../../components/SimpleHeader";
import { getLoginUser, Format_calcuDecial } from "../../common/js/utils";
import {
  getDeviceList,
  eliminate,
  Api_getReplenishment,
  changeSleepDesc,
} 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";

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 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"), // 当天时间
    });
    // 初始化页面获取列表
    onMounted(() => {
      sleepDescBoxShow.value = true;
      init();
      updateDataInterval();
      // window.addEventListener('scroll', handleScroll);
      // 加载样式
      // styleUrl('device');
    });
    // 初始化
    const init = () => {
      // 获取设备情况
      getMachineNum();
      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 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) => {
      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"));
        e.alarmList = [];
      } else {
        showFailToast(data.message);
      }
      console.log("/tEquipment/eliminate", e);
    };
    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);
      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);
        }
      }
    }
    return {
      ...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,
      backTop,
    };
  },
};
</script>

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