<script setup lang="ts">
import { computed, onMounted, shallowRef, ref, provide } from "vue";
import { httpDetail } from "/@/api/srarch/standBook";
import { useRoute } from "vue-router";
import { QUERY_MAP } from "./config/query";
import { useResponseHandle } from "/@/hooks";
import { injectStandBookKey } from "./context";
import Anchor from "./components/anchor.vue";

const { query } = useRoute();
const responseHandle = useResponseHandle();

const details = shallowRef<Array<any>>([]);
const collapses = ref<Array<string>>([]);
const mapDetailToTop = ref<Map<string, any>>(new Map());
const goodData = ref<Record<string, string>>({});

const id = computed(() => query.id);

const isDetail = (queryKey: string, report_data: Record<string, string>) => {
  const responseKey = QUERY_MAP[queryKey].responseKey;

  return (
    report_data[responseKey] &&
    QUERY_MAP[queryKey]?.detail &&
    report_data[responseKey].length !== 0
  );
};

//获取该台账单可以查询到的详情
function getDetails(report_data) {
  const filter_keys = Object.keys(QUERY_MAP).filter(queryKey =>
    isDetail(queryKey, report_data)
  );

  return filter_keys.map(key => {
    const {
      api,
      component,
      requesetProp: prop,
      responseKey,
      detail: title
    } = QUERY_MAP[key];

    const value = report_data[responseKey];

    return {
      component,
      prop,
      title,
      api,
      value,
      key
    };
  });
}

async function requesetReportDetail() {
  const { code, message, data } = await httpDetail({
    id: id.value
  });

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

//初始化页面数据
async function initalPageData() {
  await requesetReportDetail();
  //展开所有详情
  details.value.forEach((_, index) => {
    collapses.value.push(_.key);
    mapDetailToTop.value.set(_.title, {
      top: "",
      index
    });
  });
}

function handleSetMapDetailToTop(top, title) {
  const detail = mapDetailToTop.value.get(title);

  mapDetailToTop.value.set(title, {
    ...detail,
    top
  });
}

provide(injectStandBookKey, {
  goodData,
  setGoodData: data => (goodData.value = data)
});

onMounted(() => initalPageData());
</script>

<template>
  <div class="main flex h-full w-full">
    <div bg-white min-w-230px>
      <Anchor :map="mapDetailToTop" />
    </div>

    <div bg-white flex-1>
      <ElCollapse v-model="collapses">
        <ElCollapseItem
          v-for="detail in details"
          :title="detail.title"
          :name="detail.key"
          :key="detail.key"
        >
          <component
            :is="detail.component"
            v-bind="detail"
            @map-offset-top="
              ({ top, title }) => handleSetMapDetailToTop(top, title)
            "
          />
        </ElCollapseItem>
      </ElCollapse>
    </div>
  </div>
</template>
