<script setup lang="ts">
import type { MapPen } from '@api/map';
import { type RobotInfo, RobotType } from '@api/robot';
import type { EditorService } from '@core/editor.service';
import { computed, inject, type InjectionKey, ref, type ShallowRef, toRaw } from 'vue';

type Props = {
  token: InjectionKey<ShallowRef<EditorService>>;
};
const props = defineProps<Props>();
const editor = inject(props.token)!;

export type RobotBindModalRef = Ref;
type Ref = {
  open: (pen: MapPen) => void;
};
const open: Ref['open'] = (pen) => {
  if (!pen?.id) return;
  keyword.value = '';
  id.value = pen.id;
  selected.value = pen.point?.robots ?? [];
  show.value = true;
};
defineExpose<Ref>({ open });

const show = ref<boolean>(false);
const keyword = ref<string>('');

const robots = computed<RobotInfo[]>(() => editor.value.robots.filter(({ label }) => label.includes(keyword.value)));

const id = ref<string>('');
const selected = ref<string[]>([]);

const submit = () => {
  editor.value.updatePoint(id.value, { robots: toRaw(selected.value) });
  show.value = false;
};
</script>

<template>
  <a-modal :width="420" :title="$t('绑定机器人')" v-model:open="show" :mask-closable="false" centered @ok="submit">
    <a-input class="search" :placeholder="$t('请输入搜索关键字')" v-model:value="keyword">
      <template #suffix>
        <i class="icon search size-16" />
      </template>
    </a-input>

    <a-table
      class="mt-10"
      rowKey="id"
      :dataSource="robots"
      :pagination="false"
      :rowSelection="{
        columnWidth: 32,
        selectedRowKeys: selected,
        onChange: (keys) => (selected = <string[]>keys),
      }"
      :scroll="{ y: 400 }"
      bordered
    >
      <a-table-column dataIndex="label" :title="$t('机器人')" />
      <a-table-column dataIndex="brand" :title="$t('品牌')" />
      <a-table-column dataIndex="type" :title="$t('机器人类型')">
        <template #default="{ text }">
          {{ $t(RobotType[text]) }}
        </template>
      </a-table-column>
    </a-table>
  </a-modal>
</template>
