<template>
  <Modal 
    width="800px"
    title="添加场景" 
    :visible="visible"
    @ok="okHandler"
    @cancel="visible = false"
    okText="确定"
    cancelText="取消"
  >
    <div>
      <div className='model-header'>
        <Search
          className='content-header-search'
          placeholder="输入名称搜索" 
          style="width: 264px"
          @search="val => keyword = val"
        />
      </div>
      <Table 
        :row-key="record => record.modelId"
        :columns="cloumns"
        :rowSelection="rowSelection"
        :data-source="filterScenes"
        :pagination="false"
      />
    </div>
  </Modal>

  <div @click="visible = true">
    <slot></slot>
  </div>
</template>

<script lang="ts" setup>
import { Modal, Input, Table } from 'ant-design-vue'
import { computed, nextTick, ref, watchEffect } from 'vue';
import { scenes, save } from '@/store'
import { createLoadPack } from '@/utils'
import { fuseModels, createFuseModels, addFuseModel, fuseModelsLoaded } from '@/store'

import type { Scene } from '@/api'

type Key = Scene['modelId']

const Search = Input.Search

const selectIds = computed(() => fuseModels.value.map(item => item.modelId))
const visible = ref(false)
const keyword = ref('')
const filterScenes = computed(
  () => scenes.value.filter(item => item.name && item.modelId && item.name.includes(keyword.value))
)
const selects = ref<Key[]>(selectIds.value)
const rowSelection: any = ref({
  selectedRowKeys: selects,
  onChange: (ids: number[]) => {
    selects.value = Array.from(new Set(ids.concat(selectIds.value)))
  }
})
const cloumns = [
  {
    title: '名称',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '拍摄时间',
    dataIndex: 'createTime',
    key: 'createTime',
  }
]

const okHandler = createLoadPack(async () => {
  const addPromises = selects.value
    .filter(modelId => !fuseModels.value.some(model => model.modelId === modelId))
    .map(modelId => createFuseModels({ modelId }))
    .map(addFuseModel)

  await Promise.all(addPromises)

  await new Promise<void>((resolve) => {
    nextTick(() => {
      const stop = watchEffect(() => {
        if (fuseModelsLoaded.value) {
          nextTick(() => stop())
          resolve()
        }
      })
    })
  })
  await save()
  visible.value = false
})
</script>

<style lang="scss" scoped>
.model-header {
  display: flex;
  justify-content: flex-end;
  padding-bottom: 24px;
}
</style>