<script setup lang="ts">
import { MAP_ROUTE_TYPE, type MapPen, MapRoutePassType } from '@api/map';
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 RouteBindModalRef = 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.area?.routes ?? [];
  show.value = true;
};
defineExpose<Ref>({ open });

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

const routes = computed<MapPen[]>(() =>
  editor.value.routes.value.filter(({ label }) => label?.includes(keyword.value)),
);

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

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

<template>
  <a-modal :width="572" :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="routes"
      :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 :width="140" :dataIndex="['route', 'type']" :title="$t('路段类型')">
        <template #default="{ text }">
          {{ $t(MAP_ROUTE_TYPE[text]) }}
        </template>
      </a-table-column>
      <a-table-column :width="128" :dataIndex="['route', 'pass']" :title="$t('可通行类型')">
        <template #default="{ text }">
          {{ $t(MapRoutePassType[text ?? MapRoutePassType.无]) }}
        </template>
      </a-table-column>
    </a-table>
  </a-modal>
</template>
