import {onMounted, ref, watch} from "vue";
import {message} from "ant-design-vue";
import {ASYNC_STUDENT_STATUS} from "@/api/apis";
import {request} from "@/api/request";
import dialog from "@/utils/dialog";

export function useInterval(fun, time) {
  const timer = ref();

  function start(d) {
    clearInterval(timer.value);
    timer.value = setInterval(async () => {
      if (await fun(d)) {
        clearInterval(timer.value);
      }
    }, time);
  }

  return { start };
}

export function useResetRef(initValue = {}) {
  const valueRef = ref({ ...initValue });

  const reset = v => valueRef.value = { ...initValue, ...v };

  return Object.assign(valueRef, { reset });
}

export function useTimeout(asyncFun, time) {
  const timer = ref();
  const maxCount = ref(0);

  function start(d) {
    clearTimeout(timer.value);
    maxCount.value = 0;
    execute(d);
  }

  async function execute(d) {
    if (maxCount.value > 300) {
      message.error("等待超时，请联系管理员！");
      throw Error("等待超时 查询任务结束");
    }
    try {
      await asyncFun(d);
      maxCount.value = maxCount.value + 1;
      timer.value = setTimeout(() => execute(d), time);
    } catch (e) {
      clearTimeout(timer.value);
      console.log(e);
    }
  }

  return { start };
}

export function useAsyncStu(id, type, func) {
  const loading = ref(false);

  const { start } = useTimeout(async (d = {}) => {
    const { data } = await request(ASYNC_STUDENT_STATUS, { ...{ id, type }, ...d });
    if (!data) {
      loading.value = false;
      throw Error("查询任务结束");
    }
    loading.value = true;
  }, 10000);

  watch(loading, () => {
    loading.value && dialog({
      duration: 3500,
      cancel: false,
      content: "您所在项目有学员正在添加中，请耐心等待，进行其他操作不影响此次添加"
    });
    loading.value || (func && func());
  });

  onMounted(() => {
    id && type && start();
  });
  return { loading, start };
}

