<script>
export default {
  name: 'LanServiceChecker',
  props: {
    errorMsg: {
      type: String,
      default: '十分抱歉，您当前的网络环境不符合观看要求。为了保障课程信息的安全，您需要接入公司内网才能观看。'
    },
    // 控制是否显示
    value: {type: Boolean, default: false}
  },
  created() {
    this.lanServiceCheck()
  },
  data() {
    return {
      loading: false,
    }
  },
  methods: {
    syncValue(val) {
      this.loading = false
      this.$emit('value', val)
    },
    /**局域网检测*/
    lanServiceCheck() {
      this.loading = true

      // 使用 AbortController 来控制超时
      const controller = new AbortController();
      const timeoutId = setTimeout(() => {
        controller.abort();
        this.syncValue(false);
      }, 1000);

      // 拼接随机参数（时间戳+随机数，确保URL唯一，防止缓存）
      const url = `${window.location.protocol}//uapi.boe.com.cn/500.html?t=${Date.now()}${Math.random()}`;

      // 使用 fetch 发送 HEAD 请求
      fetch(url, {
        method: 'HEAD',
        signal: controller.signal
      })
        .then(response => {
          clearTimeout(timeoutId);
          response.ok ? this.syncValue(true) : this.syncValue(false);
        })
        .catch(error => {
          clearTimeout(timeoutId);
          if (error.name !== 'AbortError') {
            this.syncValue(true)
          }
        });
    },
  }
}
</script>

<template>
  <div class="lan-checker-container">
    <div v-if="value">
      <div>
        <span>{{ errorMsg }}</span>
      </div>
      <div class="check-btn" @click="lanServiceCheck">
        <el-button v-loading="loading" type="primary">重新检测</el-button>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.lan-checker-container {
  height: 100%;

  & > div {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }

  .error-msg {
    margin-top: 40px;
    font-weight: 700;
    font-size: 22px;
    color: #ccc;
  }

  .check-btn {
    margin-top: 20px;
    text-align: center;
  }
}

</style>
