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, callback?: (data: any) => void) {
  const data = ref<Record<string, string>>({});
  const responseHandle = useResponseHandle();
  const defaultRef = ref<InstanceType<typeof BasicDescriptions>>(null);
  const hidden = ref(false);
  const code = ref("");
  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: _code,
      message,
      data: _data
    } = await api({
      [prop]: Array.isArray(value) ? value[0] : value
    });

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

  onMounted(() => {
    if (props.api && !props.noRequeset) {
      return requesetDetail();
    }
  });

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

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

  return {
    defaultRef,
    hidden,
    code,
    data
  };
}
