<template>
  <div class="material-page">
    <!-- 返回按钮 -->
    <div class="header">
      <van-icon name="arrow-left" @click="goBack" />
      <span>{{ $t('material.materialCenter') }}</span>
      <span></span>
    </div>

    <!-- 搜索 -->
    <div class="search-bar">
      <van-search
        v-model="keyword"
        :placeholder="$t('material.searchMaterial')"
        shape="round"
        background="transparent"
        @search="onSearch"
      />
    </div>

    <!-- 类型筛选 -->
    <div class="type-tabs">
      <div
        class="tab-item"
        :class="{ active: type === '' }"
        @click="type = ''"
      >
        {{ $t('common.all') }}
      </div>
      <div
        class="tab-item"
        :class="{ active: type === 'image' }"
        @click="type = 'image'"
      >
        {{ $t('material.image') }}
      </div>
      <div
        class="tab-item"
        :class="{ active: type === 'text' }"
        @click="type = 'text'"
      >
        {{ $t('material.text') }}
      </div>
      <div
        class="tab-item"
        :class="{ active: type === 'video' }"
        @click="type = 'video'"
      >
        {{ $t('material.video') }}
      </div>
    </div>

    <!-- 素材列表 -->
    <div class="material-list">
      <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
        <van-list
          v-model:loading="loading"
          :finished="finished"
          :finished-text="materialList.length ? '' : $t('common.noData')"
          @load="loadMore"
        >
          <!-- 图片素材 -->
          <div class="image-grid" v-if="(type === 'image' || type === '') && imageList.length">
            <div
              class="image-item"
              v-for="item in imageList"
              :key="item.id"
              @click="previewImage(item)"
            >
              <img :src="getMediaUrl(item)" />
              <div class="image-actions">
                <van-icon name="eye-o" @click.stop="previewImage(item)" />
                <van-icon name="down" @click.stop="downloadImage(item)" />
              </div>
            </div>
          </div>

          <!-- 文本素材 -->
          <div class="text-list" v-if="(type === 'text' || type === '') && textList.length">
            <div
              class="text-item"
              v-for="item in textList"
              :key="item.id"
            >
              <div class="text-title">{{ getName(item) }}</div>
              <div class="text-content">{{ item.content }}</div>
              <div class="text-actions">
                <van-button size="small" @click="copyText(item.content || '')">
                  {{ $t('common.copy') }}
                </van-button>
              </div>
            </div>
          </div>

          <!-- 视频素材 -->
          <div class="video-list" v-if="(type === 'video' || type === '') && videoList.length">
            <div
              class="video-item"
              v-for="item in videoList"
              :key="item.id"
            >
              <video :src="getMediaUrl(item)" controls></video>
              <div class="video-title">{{ getName(item) }}</div>
            </div>
          </div>
        </van-list>
      </van-pull-refresh>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from "vue";
import { useRouter } from "vue-router";
import { useI18n } from "vue-i18n";
import { showToast, showImagePreview } from "vant";
import { requestGetMaterialList, type MaterialInfo } from "@/api/material";

const { t } = useI18n();
const router = useRouter();

const keyword = ref('');
const type = ref<'' | 'image' | 'text' | 'video'>('');
const materialList = ref<MaterialInfo[]>([]);
const loading = ref(false);
const finished = ref(false);
const refreshing = ref(false);
const page = ref(1);
const pageSize = 20;

// 获取素材的URL (图片/视频)
const getMediaUrl = (item: MaterialInfo): string => {
  return item.url || '';
};

// 获取素材名称
const getName = (item: MaterialInfo): string => {
  return item.name || '';
};

const imageList = computed(() =>
  materialList.value.filter(m => m.type === 'image')
);

const textList = computed(() =>
  materialList.value.filter(m => m.type === 'text')
);

const videoList = computed(() =>
  materialList.value.filter(m => m.type === 'video')
);

const getMaterials = async (isRefresh = false) => {
  if (isRefresh) {
    page.value = 1;
    finished.value = false;
  }

  try {
    const res = await requestGetMaterialList({
      current: page.value,
      size: pageSize
    });

    if (res.code === 200) {
      let list = res.data?.list || [];

      // 前端过滤类型
      if (type.value) {
        list = list.filter(m => m.type === type.value);
      }

      // 前端过滤关键词
      if (keyword.value) {
        const kw = keyword.value.toLowerCase();
        list = list.filter(m =>
          m.name?.toLowerCase().includes(kw) ||
          m.content?.toLowerCase().includes(kw)
        );
      }

      if (isRefresh) {
        materialList.value = list;
      } else {
        materialList.value = [...materialList.value, ...list];
      }

      // 判断是否还有更多数据
      const total = res.data?.paging?.total || 0;
      if (materialList.value.length >= total || list.length < pageSize) {
        finished.value = true;
      }
    } else {
      finished.value = true;
    }
  } catch (e) {
    console.error('获取素材列表失败', e);
    finished.value = true;
  }

  loading.value = false;
  refreshing.value = false;
};

const onSearch = () => {
  getMaterials(true);
};

const onRefresh = () => {
  getMaterials(true);
};

const loadMore = () => {
  page.value++;
  getMaterials();
};

const previewImage = (item: MaterialInfo) => {
  const url = getMediaUrl(item);
  if (url) {
    showImagePreview({
      images: [url],
      startPosition: 0
    });
  }
};

const downloadImage = (item: MaterialInfo) => {
  const url = getMediaUrl(item);
  if (url) {
    const link = document.createElement('a');
    link.href = url;
    link.download = item.name || `material_${item.id}.jpg`;
    link.target = '_blank';
    link.click();
    showToast(t('material.download') + ' started');
  }
};

const copyText = async (content: string) => {
  try {
    await navigator.clipboard.writeText(content);
    showToast(t('common.copySuccess'));
  } catch (e) {
    const textarea = document.createElement('textarea');
    textarea.value = content;
    document.body.appendChild(textarea);
    textarea.select();
    document.execCommand('copy');
    document.body.removeChild(textarea);
    showToast(t('common.copySuccess'));
  }
};

const goBack = () => {
  router.back();
};

watch(type, () => {
  getMaterials(true);
});

onMounted(() => {
  getMaterials(true);
});
</script>

<style lang="scss" scoped>
.material-page {
  min-height: 100vh;
  background: #121212;
  padding-bottom: 80px;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  color: #fff;
  font-size: 16px;
  font-weight: 600;

  .van-icon {
    font-size: 20px;
  }
}

.search-bar {
  padding: 0 16px;

  :deep(.van-search) {
    padding: 0;

    .van-search__content {
      background: rgba(255, 255, 255, 0.08);
    }

    .van-field__control {
      color: #fff;
    }

    .van-icon {
      color: rgba(255, 255, 255, 0.5);
    }
  }
}

.type-tabs {
  display: flex;
  gap: 8px;
  padding: 16px;

  .tab-item {
    flex: 1;
    text-align: center;
    padding: 8px 0;
    background: rgba(255, 255, 255, 0.05);
    border-radius: 8px;
    font-size: 12px;
    color: rgba(255, 255, 255, 0.6);

    &.active {
      background: linear-gradient(135deg, #ffc300 0%, #ff9500 100%);
      color: #000;
      font-weight: 600;
    }
  }
}

.material-list {
  padding: 0 16px;
}

.image-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
  margin-bottom: 16px;

  .image-item {
    position: relative;
    border-radius: 12px;
    overflow: hidden;
    background: rgba(255, 255, 255, 0.05);

    img {
      width: 100%;
      height: 120px;
      object-fit: cover;
    }

    .image-actions {
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      display: flex;
      justify-content: center;
      gap: 24px;
      padding: 8px;
      background: linear-gradient(to top, rgba(0, 0, 0, 0.8), transparent);

      .van-icon {
        font-size: 20px;
        color: #fff;
      }
    }
  }
}

.text-list {
  .text-item {
    padding: 16px;
    background: rgba(255, 255, 255, 0.05);
    border-radius: 12px;
    margin-bottom: 12px;

    .text-title {
      font-size: 14px;
      font-weight: 600;
      color: #fff;
      margin-bottom: 8px;
    }

    .text-content {
      font-size: 13px;
      color: rgba(255, 255, 255, 0.7);
      line-height: 1.5;
      margin-bottom: 12px;
    }

    .text-actions {
      text-align: right;

      .van-button {
        background: linear-gradient(135deg, #ffc300 0%, #ff9500 100%);
        border: none;
        color: #000;
        font-weight: 600;
      }
    }
  }
}

.video-list {
  .video-item {
    margin-bottom: 16px;

    video {
      width: 100%;
      border-radius: 12px;
    }

    .video-title {
      font-size: 13px;
      color: rgba(255, 255, 255, 0.7);
      margin-top: 8px;
    }
  }
}
</style>
