<template>
  <div style="margin-top: 20px">
    <Descriptions bordered>
      <template #title>
        关系信息
        <PermissionButton type="link" @click="visible = true" hasPermission="device/Instance:update">
          <AIcon type="EditOutlined" />编辑<Tooltip title="管理设备与其他业务的关联关系，关系来源于关系配置"
            ><AIcon type="QuestionCircleOutlined"
          /></Tooltip>
        </PermissionButton>
      </template>
      <DescriptionsItem :span="1" v-for="item in dataSource" :key="item.objectId">
        <template #label>
          <Ellipsis>{{ item.relationName }}</Ellipsis>
        </template>
        <Ellipsis>
          {{ item?.related ? (item?.related || []).map((i) => i.name).join(',') : '' }}
        </Ellipsis>
      </DescriptionsItem>
    </Descriptions>
    <Save v-if="visible" @save="saveBtn" @close="visible = false" />
  </div>
</template>

<script lang="ts" setup>
  import { useInstanceStore } from '@jdlinker/func';
  import Save from './Save.vue';
  import { PermissionButton } from '@jdlinker/ui';
  import { ref, watchEffect } from 'vue';
  // @ts-ignore
  import { Descriptions, DescriptionsItem, Ellipsis, AIcon, Tooltip } from 'linker-ui-components';

  const instanceStore = useInstanceStore();

  const dataSource = ref<Record<any, any>[]>([]);
  const visible = ref<boolean>(false);

  watchEffect(() => {
    const arr = (instanceStore.current?.relations || []).reverse();
    dataSource.value = arr as Record<any, any>[];
  });

  const saveBtn = () => {
    visible.value = false;
    if (instanceStore.current.id) {
      instanceStore.refresh(instanceStore.current.id);
    }
  };
</script>
