import { dateFormat } from "@/util";
import { ElMessage } from "element-plus";
import { ref, watchEffect } from "vue";

type SyncProps = {
  start: string;
  end: string;
};

export const useDateRange = <T extends SyncProps>(syncProps: T) => {
  const timeRang = ref<[number, number]>();

  watchEffect(() => {
    if (!timeRang.value?.length) {
      return;
    }
    const start = new Date(timeRang.value[0]);
    const end = new Date(timeRang.value[1]);

    if (end.getTime() - start.getTime() < 0) {
      ElMessage.error("结束日期必须大于开始日期");
    } else {
      syncProps.start = dateFormat(start, "yyyy-MM-dd");
      syncProps.end = dateFormat(end, "yyyy-MM-dd");
    }
  });

  watchEffect(
    () => {
      console.log(syncProps.start, syncProps.end);
      if (!syncProps.start || !syncProps.end) {
        timeRang.value = undefined;
        console.log("???", timeRang.value);
      }
    },
    { flush: "post" }
  );

  return timeRang;
};
