<template>
  <Card :bordered="false" :loading="isLoading">
    <PageHeader
      :title="title"
      @back="() => $router.go(-1)"
    >
      <template #extra>
        <a-button type="primary" @click="$router.go(-1)">返回上一页面</a-button>
      </template>
    </PageHeader>
    <Descriptions bordered :column="3">
      <Descriptions.Item
        v-for="p in displayProps"
        :key="p.key"
        :label="p.title"
        :span="['avatar'].includes(p.key) ? 3 : 1"
      >
        <span v-if="p.key === 'avatar'">
          <Image style="width: 100px" :src="p.value"/>
        </span>
        <template v-else>
          {{ p.value }}
        </template>
      </Descriptions.Item>
    </Descriptions>
  </Card>
</template>
<script lang="ts" setup>
  import { onMounted, computed, ref, Ref } from 'vue';
  import { useRoute } from 'vue-router';
  import { useAsyncState } from '@vueuse/core';
  import { PageHeader, Descriptions, Card } from 'ant-design-vue';
  import { descriptionColumns } from './schema';
  import * as DeviceApi from '@/api/system/deviceApi';
  import { Device } from '@/api/model/device';

  const route = useRoute();
  const id = ref(route.params?.id);
  const title = route.meta.title

  // id 查询
  const {
    state: detail,
    isReady: isDetailReady,
    isLoading,
    execute,
  } = useAsyncState(
    DeviceApi.getById(id.value).then((res: Device) => res),
    null,
    {
      immediate: false,
    },
  );

  onMounted(() => {
    execute();
  });

  const displayProps: Ref<Array<any>> = computed(() => {
    if (!isDetailReady.value) return {};
    const display: any = descriptionColumns.map(({ title, dataIndex = '', customRender }) => ({
      key: dataIndex,
      title,
      value: customRender ? customRender({ text: detail.value[dataIndex], record: detail.value }) : detail.value[dataIndex],
    }));
    return display;
  });
</script>

<style scoped lang="less">
  ::v-deep(.ant-card-body){
    padding-top: 0;
  }
</style>
