<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-date-picker :min-date="minDate" :max-date="maxDate" @confirm="selectTime" @cancel="showPicker = false" />
      </van-popup>
      <van-cell-group>
        <van-field readonly v-model="message" rows="2" autosize label="使用教程" type="textarea" show-word-limit />
      </van-cell-group>
      <div class="button-container">
        <van-button round style="padding: 1em 2em;" type="primary" @click="uploadLogBtn">上传</van-button>
        <van-button round style="padding: 1em 2em;" type="primary" @click="queryLogBtn">查询</van-button>
      </div>
      <van-cell v-if="fileName != ''" :title="fileName" :clickable=true @click="downloadFile">
        <!-- 使用 right-icon 插槽来自定义右侧图标 -->
        <template #right-icon>
          <van-icon name="down" class="search-icon" />
        </template>
      </van-cell>
    </div>
  </div>
</template>

<script>
import {
  onMounted,
  computed,
  ref
} from 'vue';
import sHeader from "@/components/SimpleHeader.vue";
import {
  downloadLog,
  getDeviceDetal,
  uploadLog,
  queryLog
} from "@/service/device";
import { $M_ExportFile } from "@/common/js/utils";
import {
  showFailToast,
  showToast
} 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 fileName = ref(''); // 文件名
    const message = ref('选择日期点击上传，等待几秒后点击查询，找到文件点击下载到本地查看。');
    // 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();
    });

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


    const selectTime = ({ selectedValues }) => {
      logsTime.value = selectedValues.join("-");
      showPicker.value = false;
    };

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

    const downloadBtn = async () => {
      const pattern = /^\d{4}-\d{2}-\d{2}$/;
      if (logsTime.value == null) {
        showToast('请选择日期');
        return;
      }
      if (!pattern.test(logsTime.value)) {
        showToast('日期格式有误');
        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);
          showFailToast("请求超时");
        } else {
          // 处理其他请求错误
          console.error('请求失败：', error);
          showFailToast("请求失败");
        }
      } finally {
        downloading.value = false;
      }
    }

    const uploadLogBtn = async () => {
      const pattern = /^\d{4}-\d{2}-\d{2}$/;
      if (logsTime.value == '') {
        showToast('请选择日期');
        return;
      }
      if (!pattern.test(logsTime.value)) {
        showToast('日期格式有误');
        return;
      }
      const formattedDate = logsTime.value.replace(/-/g, '');
      const { data } = await uploadLog({
        equipmentId: deviceId,
        day: formattedDate,
      });
      if (data.code == '00000') {
        showToast('上传信号发送成功，请等待几秒后查询下载');
      } else {
        showFailToast(data.message);
      }
    }

    // 查询日志是否上传成功
    const queryLogBtn = async () => {
      if (logsTime.value == '') {
        showToast('请选择日期');
        return;
      }
      const pattern = /^\d{4}-\d{2}-\d{2}$/;
      if (!pattern.test(logsTime.value)) {
        showToast('日期格式有误');
        return;
      }
      const formattedDate = logsTime.value.replace(/-/g, '');
      const { data } = await queryLog({
        equipmentId: deviceId,
        day: formattedDate,
      });
      if (data.code == '00000') {
        // console.log(data.data);
        showToast("查询成功，点击下载")
        fileName.value = data.data.substring(4);
      } else {
        fileName.value = '';
        showToast("找不到文件，请重试上传或检查机器网络");
      }
    }

    const downloadFile = async () => {
      // 文件链接
      const fileUrl = 'http://qiniuyun.sunzee.com.cn/log/' + fileName.value;
      // 文件名
      const newFileName = fileName.value;
      try {
        const response = await fetch(fileUrl, {
          headers: {
            'Cache-Control': 'no-store', // 禁用缓存
            'Pragma': 'no-cache',
          }
        });
        console.log('response', response);

        // 将文件内容创建为Blob
        const fileBlob = await response.blob();

        // 创建一个下载链接
        const downloadLink = document.createElement('a');
        downloadLink.href = URL.createObjectURL(fileBlob);
        downloadLink.download = newFileName;

        // 模拟点击下载链接
        document.body.appendChild(downloadLink);
        downloadLink.click();

        // 清理添加的链接元素
        document.body.removeChild(downloadLink);
      } catch (error) {
        console.error('请求超时：', error);
      }
    }

    return {
      deviceDetail,
      downloadBtn,
      chooseTime,
      selectTime,
      showPicker,
      logsTime,
      minDate,
      maxDate,
      downloading,
      downloadFile,
      uploadLogBtn,
      queryLogBtn,
      fileName,
      message
    }
  },

});
</script>

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

.search-icon {
  font-size: 16px;
  line-height: inherit;
}

.button-container {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
  /* 根据需要添加上下边距 */
  margin-bottom: 30px;
  gap: 20px;
}

.van-button--primary {
  background-color: #2d87c8;
  border-color: #2d87c8;
}
</style>
