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

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

type Events = {
  (e: 'change', id: string): void;
};
const emit = defineEmits<Events>();

//#region 接口
const seizeRobots = async () => {
  const res = await seizeRobotByIds([...selected.keys()]);
  editor.value.updateRobots(res, { canControl: true });
};
//#endregion

const keyword = ref<string>('');

//#region 机器人列表
const group = computed<RobotGroup | undefined>(() => editor.value.robotGroups.value?.[0]);
const robots = computed<RobotInfo[]>(() => editor.value.robots.filter(({ label }) => label.includes(keyword.value)));

const selected = reactive<Set<RobotInfo['id']>>(new Set());
watch(
  () => props.editable,
  () => selected.clear(),
);

const isAllSelected = computed<boolean>(() => selected.size > 0 && robots.value.every(({ id }) => selected.has(id)));
const selectAll = (checked: boolean) => {
  if (checked) {
    robots.value.forEach(({ id }) => selected.add(id));
  } else {
    selected.clear();
  }
};

const selectRobot = (id: RobotInfo['id'], checked: boolean) => {
  if (checked) {
    selected.add(id);
  } else {
    selected.delete(id);
  }
};
//#endregion
</script>

<template>
  <a-flex class="full" vertical>
    <a-input class="search mb-16" :placeholder="$t('请输入搜索关键字')" v-model:value="keyword">
      <template #suffix>
        <i class="icon search size-16" />
      </template>
    </a-input>

    <a-flex v-if="editable && false" class="mb-8" style="height: 32px" justify="end" align="center">
      <a-button
        class="icon-btn panel-btn"
        :title="$t('抢占控制权')"
        size="small"
        @click="seizeRobots"
        :disabled="!selected.size"
      >
        <i class="mask control" />
      </a-button>
    </a-flex>

    <a-collapse style="flex: auto; overflow-y: auto" expand-icon-position="end" ghost>
      <template #expandIcon="v">
        <i class="icon dropdown" :class="{ active: v?.isActive }" />
      </template>

      <a-collapse-panel>
        <template #header>
          <a-space align="center" :size="8">
            <a-checkbox
              v-if="editable && false"
              :checked="isAllSelected"
              @change="selectAll($event.target.checked)"
              @click.stop
            />
            <span>{{ group?.label }}</span>
          </a-space>
        </template>

        <a-list rowKey="id" :data-source="robots">
          <template #renderItem="{ item }">
            <a-list-item
              :class="{
                'ph-16': !editable || true,
                // 'pl-12': editable,
                'pr-8': editable,
                selected: item.id === current,
              }"
              style="height: 36px"
              @click="emit('change', item.id)"
            >
              <a-space align="center" :size="8">
                <a-checkbox
                  v-if="editable && false"
                  :checked="selected.has(item.id)"
                  @change="selectRobot(item.id, $event.target.checked)"
                  @click.stop
                />
                <a-typography-text type="secondary">{{ item.label }}</a-typography-text>
              </a-space>
            </a-list-item>
          </template>
        </a-list>
      </a-collapse-panel>
    </a-collapse>
  </a-flex>
</template>

<style scoped lang="scss">
.open-group-btn {
  margin-right: -8px;
  visibility: hidden;

  .ant-collapse-header:hover & {
    visibility: visible;
  }
}
</style>
