import { computed, ref } from "vue";
import { useRoute } from "vue-router";

interface Config {
  baseName?: string;
  collapseLen?: number;
  initalDetailCallback?: (id?: string) => any;
}

export function useDetail(config: Config = {}) {
  const { query } = useRoute();

  const collapses = ref<string[]>([]);

  const id = computed(() => {
    return query.id as string | undefined;
  });

  const label = computed(() => {
    const { baseName } = config;
    return isDetail.value ? `${baseName}详情` : `创建${baseName}`;
  });

  const isDetail = computed(() => {
    return !!id.value;
  });

  const isCreate = computed(() => {
    return !id.value;
  });

  if (config.collapseLen) {
    const chunks = Array(config.collapseLen).fill(0);
    collapses.value = chunks.map((_, index) => String(index + 1));
  }

  function initalDetail(callbacK: Function) {
    if (isDetail.value && id.value) {
      config.initalDetailCallback && config.initalDetailCallback(id.value);
      callbacK(id.value);
    }
  }

  if (isDetail.value && id.value) {
    config.initalDetailCallback && config.initalDetailCallback(id.value);
  }

  return {
    id,
    label,
    isDetail,
    isCreate,
    collapses,
    initalDetail
  };
}
