<template>
  <div class="page-container">
    <div v-if="pending">
      <el-skeleton :rows="5" animated />
    </div>
    <div v-else>
      <support-tabs model-value="documents" />
      <div class="page-header">
        <h1 class="page-title">{{ $t('navigation.documents') }}</h1>
        <el-breadcrumb class="breadcrumb" separator="/">
          <el-breadcrumb-item class="text-md opacity-50">
            <NuxtLink :to="$localePath('/')">{{
              $t('navigation.home')
            }}</NuxtLink>
          </el-breadcrumb-item>
          <el-breadcrumb-item class="text-md opacity-50">
            <NuxtLink :to="$localePath('/support')">{{
              $t('navigation.support')
            }}</NuxtLink>
          </el-breadcrumb-item>
          <el-breadcrumb-item class="text-md opacity-50">
            <NuxtLink :to="$localePath('/support/documents')">{{
              $t('navigation.documents')
            }}</NuxtLink>
          </el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <div class="document-category">
        <el-select v-model="selectedType" placeholder="选择产品类型" clearable>
          <el-option
            v-for="type in productionTypeOptions"
            :key="type.documentId"
            :label="type.type"
            :value="type.documentId"
          />
        </el-select>
        <el-select
          v-model="selectedProduction"
          placeholder="选择系列产品"
          clearable
        >
          <el-option
            v-for="production in productionOptions"
            :key="production.documentId"
            :label="production.title"
            :value="production.documentId"
          />
        </el-select>
        <el-input
          v-model="keyword"
          placeholder="输入关键词..."
          clearable
          :prefix-icon="Search"
        />
      </div>
      <div class="page-content">
        <document-list :documents="filteredDocuments" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { Search } from '@element-plus/icons-vue';

  const { find } = useStrapi();
  const { getStrapiLocale } = useLocalizations();
  const strapiLocale = getStrapiLocale();

  const { data, pending, error } = useAsyncData('documents', () =>
    find<ProductionDocument>('production-documents', {
      populate: ['document', 'related_productions.production_type'],
      locale: strapiLocale,
    })
  );

  // const documents = computed(
  //   () =>
  //     data.value?.data.map((item) => ({
  //       ...item.document,
  //     })) || []
  // );
  const documents = computed(() => data.value?.data ?? []);

  const keyword = ref('');

  const selectedType = ref<string | null>(null);
  const selectedProduction = ref<string | null>(null);

  const productionTypeOptions = computed(() => {
    const types: ProductionType[] = [];
    documents.value.forEach((document: ProductionDocument) => {
      document.related_productions?.forEach((production: Production) => {
        const productionType = production?.production_type;
        if (!types.some((p) => p.documentId === productionType.documentId)) {
          types.push(productionType);
        }
      });
    });

    return types;
  });

  const productionOptions = computed(() => {
    if (!selectedType.value) return [];
    const productions: Production[] = [];
    documents.value.forEach((document: ProductionDocument) => {
      document.related_productions.forEach((production: Production) => {
        if (
          production.production_type?.documentId === selectedType.value &&
          !productions.some((p) => p.documentId === production.documentId)
        ) {
          productions.push(production);
        }
      });
    });
    return productions;
  });

  const filteredDocuments = computed(() =>
    documents.value
      .filter((document: ProductionDocument) => {
        const matchProduction = selectedProduction.value
          ? document.related_productions?.some(
              (production: Production) =>
                production.documentId === selectedProduction.value
            )
          : selectedType.value
            ? document.related_productions?.some(
                (production: Production) =>
                  production.production_type?.documentId === selectedType.value
              )
            : true;

        const matchKeyword = keyword.value
          ? document.document.caption &&
            document.document.caption.includes(keyword.value)
          : true;

        return matchProduction && matchKeyword;
      })
      .map((item) => ({
        ...item.document,
      }))
  );

  watch(selectedType, () => {
    selectedProduction.value = null;
  });

  watch(documents, (value) => {
    console.log(value);
  });

  watch(error, (value) => {
    if (value) {
      console.error('数据获取失败: ', value);
    }
  });
</script>

<style scoped>
  .page-container {
    max-width: 1200px;
    margin: 0 auto;
  }

  .page-header {
    display: flex;
    padding: 2rem 2rem 0rem;
  }

  .page-title {
    font-size: 2rem;
    font-weight: bold;
    color: var(--el-color-primary);
    margin-bottom: 1rem;
  }

  .breadcrumb {
    margin-left: auto;
  }

  .document-category {
    display: flex;
    padding: 0rem 2rem;
    gap: 4px;
  }

  .page-content {
    padding: 1rem 2rem 2rem;
  }
</style>
