<script setup lang="ts">
import { type MapPen, MapPointType } from '@api/map';
import type { EditorService } from '@core/editor.service';
import { isNil } from 'lodash-es';
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 PointBindModalRef = Ref;
type Ref = {
  open: (pen: MapPen, filter?: MapPointType) => void;
};
const open: Ref['open'] = (pen, type) => {
  if (!pen?.id) return;
  keyword.value = '';
  filter.value = type;
  id.value = pen.id;
  sn.value = pen.name;
  switch (sn.value) {
    case 'point':
      selected.value = pen.point?.actions ?? [];
      break;
    case 'area':
      selected.value = pen.area?.points ?? [];
      break;
    default:
      selected.value = [];
      break;
  }
  show.value = true;
};
defineExpose<Ref>({ open });

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

const filter = ref<MapPointType>();
const points = computed<MapPen[]>(() =>
  editor.value.points.value
    .filter(
      ({ point }) =>
        point?.type && point.type !== MapPointType.禁行点 && (isNil(filter.value) || point.type === filter.value),
    )
    .filter(({ label }) => label?.includes(keyword.value)),
);

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

const submit = () => {
  switch (sn.value) {
    case 'point':
      editor.value.updatePoint(id.value, { actions: toRaw(selected.value) });
      break;
    case 'area':
      editor.value.updateArea(id.value, { points: toRaw(selected.value) });
      break;
    default:
      selected.value = [];
      break;
  }
  show.value = false;
};
</script>

<template>
  <a-modal :width="300" :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="points"
      :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="['point', 'type']" :title="$t('站点类型')">
        <template #default="{ text }">
          {{ $t(MapPointType[text]) }}
        </template>
      </a-table-column>
    </a-table>
  </a-modal>
</template>
