<template>
  <div class="viewLogsPage flex-col">
    <s-header :name="$t('device.viewLogs')" :noback="false"></s-header>
    <div class="block2 flex-row justify-between">
      <div class="block3 flex-col"></div>
      <span class="info2">{{ $t('device.equipmentName') }}：{{ deviceDetail ? deviceDetail.name : '' }}</span>
    </div>
    <div class="wrap1 flex-col o-pt-15">
      <van-field v-model="logsTime" is-link readonly label="日期" placeholder="点击选择时间" @click="chooseTime()" />
      <van-popup v-model:show="showPicker" round position="bottom">
        <van-datetime-picker type="date" :min-date="minDate" :max-date="maxDate"
                             @confirm="selectTime" @cancel="showPicker = false" />
      </van-popup>
      <van-button v-if="!downloading" round :disabled="logsTime === ''" type="primary" class="volumeChangeButton"
                  @click="downloadBtn">{{ $t('device.download') }}</van-button>
      <van-button v-else disabled loading round class="volumeChangeButton" type="primary"
                  :loading-text="$t('device.downloading')" />
    </div>
  </div>
</template>

<script>
import {
  onMounted,
  computed,
  ref
} from 'vue';
import sHeader from "@/components/SimpleHeader.vue";
import {
  downloadLog,
  getDeviceDetal
} from "@/service/device";
import { $M_ExportFile } from "@/common/js/utils";
import {
  Toast
} from "vant";
import {
  useRoute
} from "vue-router";
import dateUtil from "@/utils/dateUtil";
import { styleUrl } from '../../../common/js/utils';
// import {useI18n} from "vue-i18n";

export default ({
  components: {
    sHeader
  },
  setup() {
    // const { t } = useI18n();
    const route = useRoute();
    const deviceId = route.query.deviceId;
    const deviceDetail = ref(null);
    const showPicker = ref(false);
    const downloading = ref(false);
    const logsTime = ref(null);
    // const curDate = new Date(); // 获取当前时间日期

    // 计算最小日期为当前日期7天前
    const minDate = computed(() => {
      const minTimestamp = (new Date()).getTime() - 6 * 24 * 3600 * 1000;
      const minDate = dateUtil.formateDate(new Date(minTimestamp), "yyyy-MM-dd");
      return new Date(minDate);
    });

    // 计算最大日期为当前日期
    const maxDate = computed(() => {
      return new Date();
    });


    // 初始化页面获取列表
    onMounted(async () => {
      // 加载样式
      styleUrl('viewLogs');
      await getDeviceDetailFun();
      // console.log(deviceDetail.value.name);
    });

    // 选择时间
    const chooseTime = () => {
      // console.log('chooseTime function is called');
      showPicker.value = true;
      console.log(showPicker.value);
    };


    const selectTime = (time) => {
      // console.log('selectTime function is called', time);
      logsTime.value = dateUtil.formateDate(time, "yyyy-MM-dd");
      showPicker.value = false;
    };

    const getDeviceDetailFun = async () => {
      const {
        data
      } = await getDeviceDetal({
        id: deviceId
      });
      if (data.code === '00000') {
        deviceDetail.value = data.data;
      } else {
        Toast.fail(data.message);
      }
    }

    const downloadBtn = async () => {
      const pattern = /^\d{4}-\d{2}-\d{2}$/;
      if (!pattern.test(logsTime.value)) {
        Toast.fail('日期格式有误');
        return;
      }
      const formattedDate = logsTime.value.replace(/-/g, '');
      downloading.value = true;
      try {
        const {
          headers, data
        } = await downloadLog({
          equipmentId: deviceId,
          day: formattedDate,
        });
        console.log('请求成功', headers, data);
        $M_ExportFile(data, headers);
      } catch (error) {
        if (error.code === 'ECONNABORTED') {
          // 处理请求超时的错误
          console.error('请求超时：', error);
          Toast.fail("请求超时");
        } else {
          // 处理其他请求错误
          console.error('请求失败：', error);
          Toast.fail("请求失败");
        }
      } finally {
        downloading.value = false;
      }
    }

    return {
      deviceDetail,
      downloadBtn,
      chooseTime,
      selectTime,
      showPicker,
      logsTime,
      minDate,
      maxDate,
      downloading,
    }
  },

});
</script>

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