<script setup>
import { computed, onMounted, onUnmounted, ref } from 'vue';
import { useStore } from 'vuex';
import SearchBar from 'components/search-bar.vue';
import { getDatas } from 'apis';
import { ElMessage } from 'element-plus';
import dayjs from 'dayjs';
import { REALTIME_DATA_INTERVAL } from '@/config/config';

const page = ref({
  page: 1,
  size: 50,
});
let timer = null;
let apiTimer = null;
const store = useStore();
const token = computed(() => store.getters['user/token']);
const currentDeviceId = computed(() => store.state.device.currentDeviceId); // 正在操作的设备的id
const contentHeight = ref(600);
const loadingSearch = ref(false);
const data = ref(null);

// 获取设备完整信息列表
const getData = async () => {
  try {
    if (token && token.value) {
      if (!currentDeviceId.value) {
        return ElMessage.error('请选择站点');
      }

      const date = [dayjs().startOf('day').format('x'), dayjs().endOf('day').format('x')];
      const params = {
        deviceId: currentDeviceId.value,
        date,
        page: page.value.page,
        size: page.value.size,
        type: 1,
        sort: -1,
      };

      loadingSearch.value = true;
      const resData = await getDatas(params);
      loadingSearch.value = false;

      data.value = resData.data;
      page.value = resData.page;
      timer && clearTimeout(timer);
      timer = null;

      // 定时轮询请求新数据
      if (!apiTimer) {
        apiTimer = setInterval(() => {
          getData();
        }, REALTIME_DATA_INTERVAL);
      }
    } else {
      timer = setTimeout(() => {
        getData();
      }, 20);
    }
  } catch (error) {
    ElMessage.error(error.message || '获取数据失败');
    console.log('error: ', error);
  }
};

// 设置表格高度
onMounted(() => {
  const winHeight = document.documentElement.clientHeight;
  contentHeight.value = winHeight - 170;
  currentDeviceId.value && getData();
});

onUnmounted(() => {
  apiTimer && clearInterval(apiTimer);
  apiTimer = null;
});

/**
 * 当前 码变化
 * 更新page 重新 取数据
 * @param {number} e   的页码
 */
const onCurrentPageChange = e => {
  page.value.page = e;
  getData();
};

const onSizeChange = e => {
  page.value.size = e;
  getData();
};

// 下一页
const onNext = e => {
  page.value.page = e + 1;
  getData();
};

// 上一页
const onPrev = e => {
  page.value.page = e - 1;
  getData();
};

/**
 * 格式化时间
 * @param {number} time 时间戳
 * @returns {string}
 */
function formatTime(time) {
  return dayjs(new Date(time)).format('YYYY-MM-DD HH:mm:ss');
}
</script>

<template>
  <SearchBar @search="getData" />

  <template v-if="data">
    <el-table :data="data" :max-height="contentHeight" border stripe style="width: 100%">
      <el-table-column align="center" fixed label="设备编号" min-width="80" prop="deviceNo" />
      <el-table-column align="center" label="ICCID" min-width="190" prop="iccid" />
      <el-table-column align="center" label="IMEI" min-width="150" prop="imei" />
      <el-table-column align="center" label="信号强度" min-width="80" prop="signal" />
      <el-table-column align="center" label="基站编号" min-width="130" prop="stationNo" />
      <el-table-column align="center" label="硬件版本" min-width="80" prop="hardwareVersion" />
      <el-table-column align="center" label="软件版本" min-width="80" prop="softwareVersion" />
      <el-table-column align="center" label="采集时间" min-width="170">
        <template #default="scope">
          {{ formatTime(+scope.row.time) }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="后台接受时间" min-width="170">
        <template #default="scope">
          {{ formatTime(+scope.row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="太阳能电压" min-width="94" prop="solarVoltage" />
      <el-table-column align="center" label="蓄电池电压" min-width="94" prop="batteryVoltage" />
      <el-table-column align="center" label="电压百分比" min-width="94" prop="batteryVoltagePercentage" />
      <el-table-column align="center" label="剩余电量" min-width="94" prop="batteryVoltageRemain" />
      <el-table-column align="center" label="电池损耗量" min-width="94" prop="batteryLoss" />
      <el-table-column align="center" label="机箱温度" min-width="80" prop="deviceTemperature" />
      <el-table-column align="center" label="机箱湿度" min-width="80" prop="deviceHumidity" />
      <el-table-column align="center" label="环境温度" min-width="80" prop="environmentTemperature" />
      <el-table-column align="center" label="环境湿度" min-width="80" prop="environmentHumidity" />
      <el-table-column align="center" label="SO2" min-width="50" prop="so2" />
      <el-table-column align="center" label="盐分" min-width="50" prop="salt" />
      <el-table-column align="center" label="腐流1" min-width="60" prop="corrosion1" />
      <el-table-column align="center" label="腐流2" min-width="60" prop="corrosion2" />
      <el-table-column align="center" label="腐流3" min-width="60" prop="corrosion3" />
      <el-table-column align="center" label="腐流4" min-width="60" prop="corrosion4" />
    </el-table>

    <el-pagination
      :current-page="page.page"
      :default-page-size="50"
      :page-count="page.count"
      :page-size="page.size"
      :page-sizes="[1, 10, 20, 50, 100]"
      :total="page.total"
      background
      class="my-3 float-right"
      layout="total, sizes, prev, pager, next, jumper"
      @current-change="onCurrentPageChange"
      @size-change="onSizeChange"
      @prev-click="onPrev"
      @next-click="onNext"
    ></el-pagination>
  </template>
</template>
