<template>
  <BodyPanlHeader>
    <a-button type="primary" @click="insertScene">{{
      $t('scene.create')
    }}</a-button>
    <div>
      <a-input-search
        v-model:value="filterName"
        style="width: 280px"
        :placeholder="$t('scene.nameRule')"
        allow-clear
      />
    </div>
  </BodyPanlHeader>

  <BodyPanlBody>
    <a-table
      :data-source="filterScene"
      :columns="sceneColumns"
      :pagination="pagination"
      :scroll="{ x: '100%', y: 350 }"
    >
      <template #bodyCell="{ column, text }">
        <template v-if="column.dataIndex === 'name'">
          <template v-if="text.length <= maxNameLength">
            {{ text }}
          </template>
          <a-popover v-else>
            <template #content>{{ text }}</template>
            {{ text.substring(0, maxNameLength) }}...
          </a-popover>
        </template>
      </template>
    </a-table>
  </BodyPanlBody>
</template>

<script lang="ts" setup>
import InsertScene from './insert.vue'
import { computed, reactive, ref, watch, onDeactivated } from 'vue'
import { BodyPanlHeader, BodyPanlBody } from '@/layout/panl'
import { useProject } from '@/store'
import { sceneColumns } from './columns'
import { renderModal } from '@/helper'

const filterName = ref('')
const projectStore = useProject()
const filterScene = computed(() =>
  projectStore.scenes.filter(
    scene => !scene.name || scene.name?.includes(filterName.value)
  )
)
const maxNameLength = 50
const pagination = reactive({
  current: 1,
  total: filterScene.value.length,
  pageSize: 10,
  showSizeChanger: false,
  onChange(num: number) {
    pagination.current = num
  }
})
onDeactivated(() => {
  filterName.value = ''
})
watch(filterName, () => (pagination.current = 1), { flush: 'sync' })
const insertScene = () => {
  renderModal(InsertScene, {
    showBim: !projectStore.current!.bimData,
    project: projectStore.current! as any,
    async onSave({ type, payload }) {
      if (type === 'bim') {
        await projectStore.addBim(payload)
      } else if (type === 'scene') {
        await projectStore.replaceScenes(payload)
      }
    }
  })
}
</script>
