<!-- eslint-disable @typescript-eslint/no-unused-vars -->
<!--
 * async await return
  -->
<script setup lang="ts">
import { onMounted, ref } from 'vue';

const primeNum = ref(1000000);
const msg = ref('');
const requestMsg = ref('');

onMounted(() => {
  fun1();
});
function getMag(name: any) {
  return `Hello, my name is ${name}.`;
}
function fun1() {
  const name = '张三';
  const msg = getMag(name);
  console.log(msg); // Hello, my name is 张三.
}

// 生成素数
function generatePrimes() {
  function isPrime(n: any) {
    // Math.sqrt() 函数返回一个数的平方根
    for (let c = 2; c <= Math.sqrt(n); ++c) {
      if (n % c === 0) {
        return false;
      }
    }
    return true;
  }

  let primes: number[] = [];
  const maximum = 1000000;
  while (primes.length < primeNum.value) {
    const candidate = Math.floor(Math.random() * (maximum + 1));
    if (isPrime(candidate)) {
      primes.push(candidate);
    }
  }
  msg.value = `已生成素数${primes.length}个`;
}

function xhrClick() {
  requestMsg.value = '';
  const xhr = new XMLHttpRequest();
  xhr.addEventListener('loadend', () => {
    requestMsg.value = `${requestMsg.value}完成！状态码：${xhr.status}`;
  });
  xhr.open(
    'GET',
    'https://raw.githubusercontent.com/mdn/content/main/files/en-us/_wikihistory.json'
  );
  xhr.send();
  requestMsg.value = '请求已发起\n';
}
function heavyLoad() {
  document.location.reload();
}

function fetchApi() {
  fn().then(
    function (data) {
      console.log('resolve回调', data);
      // console.log(somedata); // somedata未定义
    },
    function (error) {
      console.log('reject回调', error);
    }
  );
}

function fn() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      // Math.random 生成0~1的随机数
      // Math.ceil 向上取整
      let num = Math.ceil(Math.random() * 10); // 生成1~10的随机整数
      if (num <= 5) {
        resolve(`执行成功，num的值为:${num}`);
      } else {
        reject(`执行失败，该数字大于5，num的值为${num}`);
      }
    }, 1000);
  });
}

async function fetchProducts() {
  try {
    // 在这一行之后，我们的函数将等待 `fetch()` 调用完成
    // 调用 `fetch()` 将返回一个“响应”或抛出一个错误
    const response = await fetch(
      'https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/products.json'
    );
    if (!response.ok) {
      throw new Error(`HTTP 请求错误：${response.status}`);
    } else {
      console.log(response);
    }
    // 在这一行之后，我们的函数将等待 `response.json()` 的调用完成
    // `response.json()` 调用将返回 JSON 对象或抛出一个错误
    const json = await response.json();
    console.log(json[0].name);
  } catch (error) {
    console.error(`无法获取产品列表：${error}`);
  }
}
// await fetchAPI示例
</script>
<template>
  <div class="fit">
    <div class="q-mb-md">async await return</div>
    <div class="q-mb-md">
      <a
        href="https://blog.csdn.net/huchaoyue_/article/details/127686795"
        target="_blank"
        >详细内容请查看CSDN</a
      >
    </div>
    <div class="content q-gutter-md">
      <q-card class="my-card bg-primary text-white">
        <q-card-section>
          <div class="q-mb-md q-gutter-sm">
            <q-btn
              color="white"
              text-color="primary"
              label="生成素数"
              @click="generatePrimes"
            />
          </div>
          <div>
            <q-input
              dark
              filled
              label-color="white"
              v-model="primeNum"
              label="素数个数"
            />
          </div>
          <div>{{ msg }}</div>
        </q-card-section>
      </q-card>

      <q-card class="my-card bg-orange-4 text-white">
        <q-card-section>
          <div class="q-mb-md q-gutter-sm">
            <q-btn
              color="white"
              text-color="orange-4"
              label="点击发起请求"
              @click="xhrClick"
            />
            <q-btn outline text-color="white" label="重载" @click="heavyLoad" />
          </div>
          <div>{{ requestMsg }}</div>
        </q-card-section>
      </q-card>

      <q-card class="my-card bg-purple-3 text-white">
        <q-card-section>
          <div class="q-mb-md q-gutter-sm">
            <q-btn
              no-caps
              color="white"
              text-color="purple-3"
              label="fetch API"
              @click="fetchApi"
            />
          </div>
        </q-card-section>
      </q-card>

      <q-card class="my-card bg-pink-3 text-white">
        <q-card-section>
          <div class="q-mb-md q-gutter-sm">
            <q-btn
              no-caps
              color="white"
              text-color="pink-3"
              label="async await"
              @click="fetchProducts"
            />
          </div>
        </q-card-section>
      </q-card>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.content {
  display: flex;
  flex-flow: row wrap;
  align-items: flex-start;
}
.my-card {
  width: 300px;
}
</style>
