<template>
  <div class="tabs">
    <a-tooltip placement="topLeft" :title="$t('scene.addTip')">
      <span class="help">
        <QuestionOutlined />
      </span>
    </a-tooltip>
    <a-tabs :active-key="params.type" @update:active-key="updateType">
      <a-tab-pane
        v-for="option in tabOptions"
        :key="option.key"
        :tab="(option.label as any)"
      />
    </a-tabs>
  </div>
  <a-input-search
    v-model:value="sceneName"
    allow-clear
    :placeholder="$t('scene.nameRule')"
    @search="
      () => {
        params.sceneName = sceneName
        pagination.current = 1
      }
    "
  />
  <a-table
    style="margin-top: 10px"
    row-key="num"
    :data-source="list"
    :columns="sceneColumns"
    :pagination="pagination"
    :row-selection="{
      getCheckboxProps: (scene: Scene) => ({
        disabled: isDisableScene(scene)
      }),
      selectedRowKeys: typeNums[params.type],
      onChange: changeSelectNums
    }"
  >
    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'name'">
        <a-tooltip v-if="record.name.length > 15">
          <template #title>
            <span>{{ record.name }}</span>
          </template>
          <span>{{ record.name.substring(0, 15) }}...</span>
        </a-tooltip>
        <span v-else>
          {{ record.name }}
        </span>
      </template>
    </template>
  </a-table>
</template>

<script lang="ts" setup>
import { selectSceneColumns as sceneColumns } from './columns'
import { computed, reactive, ref, watchEffect } from 'vue'
import { fetchScenes, SceneType, SceneTypeDesc } from '@/api'
import { usePaging } from '@/hook'

import type { SelectTypeScenes, Scene } from '@/store'

defineOptions({ name: 'SelectSceneList' })

const props = defineProps<{
  sceneList: Scene[]
  typeNums: SelectTypeScenes
  scenesCount: { [key in string]: number }
}>()
const emit = defineEmits<{
  (e: 'update:typeNums', value: SelectTypeScenes): void
  (e: 'update:sceneList', value: Scene[]): void
}>()

const tabOptions = [
  SceneType.SWSG,
  SceneType.SWSS,
  SceneType.SWKJ,
  SceneType.SWKK
].map(type => ({
  key: type,
  label: SceneTypeDesc[type]
}))

const defaultTypeNums = { ...props.typeNums }
const sceneName = ref('')
const params = reactive({ type: SceneType.SWSG, sceneName: '' })
const selectFirstScene = computed(() =>
  Object.entries(props.typeNums).find(([k, v]) => v.length > 0)
)
const selectType = computed(() => selectFirstScene.value?.[0])
const selectNum = computed(() => {
  const nums = selectFirstScene.value?.[1]
  return nums && props.scenesCount[nums[0]]
})
const isDisableScene = (scene: Scene) => {
  return (
    (scene.bind &&
      !defaultTypeNums[params.type].some(num => scene.num === num)) ||
    (selectFirstScene.value &&
      (scene.type.toString() !== selectType.value ||
        scene.shootCount !== selectNum.value))
  )
}
const { list, pagination } = usePaging(fetchScenes, params)

const updateType = (type: any) => {
  pagination.current = 1
  params.type = type
}

const changeSelectNums = (nums: any[]) => {
  const currentNums = props.typeNums[params.type]
  const reserve = currentNums.filter(num =>
    list.value.every(scene => scene.num !== num)
  )

  const scenes = list.value.filter(item => nums.includes(item.num))
  emit('update:sceneList', [
    ...props.sceneList.filter(item => item.type === params.type),
    ...scenes
  ])

  emit('update:typeNums', {
    ...props.typeNums,
    [params.type]: [...reserve, ...nums]
  })
}

watchEffect(() => {
  const scenes = props.sceneList.filter(scene => !isDisableScene(scene))
  if (scenes.length === props.sceneList.length) return

  const typeNums = scenes.reduce(
    (t, scene) => {
      t[scene.type].push(scene.num)
      return t
    },
    {
      [SceneType.SWKJ]: [],
      [SceneType.SWKK]: [],
      [SceneType.SWSS]: [],
      [SceneType.SWSG]: []
    } as SelectTypeScenes
  )

  emit('update:sceneList', scenes)
  emit('update:typeNums', typeNums)
})
</script>

<style lang="scss" scoped>
.tabs {
  position: relative;
  .help {
    position: absolute;
    right: 0;
    top: 10px;
    width: 20px;
    height: 20px;
    z-index: 99;
    text-align: center;
    line-height: 20px;
  }
}
</style>
