import {
  getCurrentInstance,
  nextTick,
  onMounted,
  ref,
  unref,
  watch
} from "vue";
import { DetailProps } from "../types";
import BasicDescriptions from "/@/components/BasicDescriptions";
import { useResponseHandle } from "/@/hooks";

export function useDetail(props: DetailProps) {
  const data = ref<Record<string, string>>({});
  const responseHandle = useResponseHandle();
  const defaultRef = ref<InstanceType<typeof BasicDescriptions>>(null);
  const hidden = ref(false);
  const emit = getCurrentInstance().emit;

  const getOffsetTop = () => {
    const instance = unref(defaultRef);
    const rect = (instance.$el as HTMLElement).getBoundingClientRect();
    return rect.y;
  };

  //获取详情数据
  async function requesetDetail() {
    const { api, prop, value } = props;
    const {
      code,
      message,
      data: _data
    } = await api({
      [prop]: Array.isArray(value) ? value[0] : value
    });

    responseHandle({
      code,
      message,
      handler: () => (data.value = _data)
    });
  }

  onMounted(() => requesetDetail());

  watch(
    () => data.value,
    () =>
      setTimeout(() => {
        const mapOffsetTop = {
          top: getOffsetTop() - 134,
          title: props.title
        };

        nextTick(() => emit("map-offset-top", mapOffsetTop));
      }, 100)
  );

  return {
    defaultRef,
    hidden,
    data
  };
}
