<template>
  <UModal v-model="$isLibrarySelectOpen" :ui="{ width: 'w-96 sm:max-w-screen-md' }">
    <UCard :ui="{ ring: '', divide: 'divide-y divide-gray-100 dark:divide-gray-800' }">
      <template #header>
        <div class="flex items-center justify-between">
          <div class="text-xl">选择合集</div>
          <UButton
            leading-icon="i-heroicons-x-mark-20-solid"
            color="gray"
            variant="ghost"
            @click="handleClose"
          />
        </div>
      </template>
      <div class="flex flex-col gap-4">
        <UButton
          leading-icon="i-heroicons-plus-20-solid"
          label="创建新合集"
          color="gray"
          @click="handleOpenCreate"
        />
        <div class="flex flex-col gap-2">
          <UButton
            v-for="item in $collection"
            :key="item.id"
            color="white"
            size="md"
            class="flex"
            @click="handleSelected(item.id)"
          >
            <div class="flex flex-grow justify-between items-center">
              <div>{{ item.name }}</div>
              <UIcon
v-if="selected.includes(item.id)" name="i-heroicons-check-circle-20-solid"
                     class="text-primary text-lg"/>
            </div>
          </UButton>
        </div>
      </div>
      <template #footer>
        <div class="flex justify-end">
          <UButton
            size="md"
            label="保存"
            :loading="loading"
            @click="handleSave"
          />
        </div>
      </template>
    </UCard>
  </UModal>
</template>
<script setup>
const { $isLibrarySelectOpen, $selectCollectionId, $selectThreadId, $collection } = storeToRefs(useLibraryStore())
const { $closeLibrarySelect, $openLibraryCreate, $setSelectCollectionId, $getCollection } = useLibraryStore()
const { saveCollection, deleteCollectionRecord } = useCollectionRequest()
const emits = defineEmits([ 'success' ])
// 合集列表
const selected = ref([])
const loading = ref(false)
function handleClose () {
  $closeLibrarySelect()
}
function handleOpenCreate () {
  handleClose()
  $openLibraryCreate()
}
async function handleSelected(id) {
  selected.value = [ id ]
}
async function handleSave() {
  if (loading.value) return
  loading.value = true
  // 取消合集
  const hasSelected = $selectCollectionId.value
  if (hasSelected.length) {
    const { error } = await deleteCollectionRecord(hasSelected[0], $selectThreadId.value)
    !error.value && $setSelectCollectionId([])
  }
  // 添加合集
  if (selected.value.length) {
    const selectedItem = selected.value[0]
    const { error } = await saveCollection({ collection_id: selectedItem, c_id: $selectThreadId.value })
    !error.value && $setSelectCollectionId([ selectedItem ]) 
  }
  loading.value = false
  handleClose()
  $getCollection()
  emits('success', {
    c_id: $selectThreadId.value,
    collection_id: selected.value[0],
    collection_name: $collection.value.find(i => i.id === selected.value[0]).name
  })
}
watch(() => $isLibrarySelectOpen.value, () => {
  selected.value = [ ...$selectCollectionId.value ]
  if (!$collection.value.length) {
    $getCollection()
  }
})
</script>
