<script setup lang="ts">
import { getAllRobots, RobotBrand, type RobotInfo, RobotType } from '@api/robot';
import type { EditorService } from '@core/editor.service';
import { message } from 'ant-design-vue';
import { isError, isNil } from 'lodash-es';
import { computed, inject, type InjectionKey, ref, type ShallowRef } from 'vue';
import { useI18n } from 'vue-i18n';

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

export type RobotAddModalRef = Ref;
type Ref = {
  open: (gid: string) => void;
};
const open: Ref['open'] = async (id) => {
  const res = await getAllRobots();
  robots.value = res.filter(({ id }) => isNil(editor.value.getRobotById(id)));
  gid.value = id;
  keyword.value = '';
  selected.value = [];
  show.value = true;
};
defineExpose<Ref>({ open });

const { t } = useI18n();

const gid = ref<RobotInfo['gid']>();

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

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

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

const submit = () => {
  try {
    const temp = selected.value.map((v) => robots.value.find(({ id }) => id === v)).filter((v) => !isNil(v));
    editor.value.addRobots(gid.value, temp);
    show.value = false;
  } catch (error) {
    if (isError(error)) {
      message.error(t(error?.message));
    } else {
      console.debug(error);
    }
  }
};
</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="filtered"
      :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('品牌')">
        <template #default="{ text }">
          {{ $t(RobotBrand[text]) }}
        </template>
      </a-table-column>
      <a-table-column dataIndex="type" :title="$t('机器人类型')">
        <template #default="{ text }">
          {{ $t(RobotType[text]) }}
        </template>
      </a-table-column>
    </a-table>
  </a-modal>
</template>
