<template>
  <div class="press-releases-page">
    <main class="mx-auto">
      <div class="title-section">
        <div class="title-decoration"></div>
        <div class="title">
          {{ t("press_releases.title") }}
        </div>
      </div>
      <div class="search-container">
        <custom-select
          :options="state.selectOptions"
          v-model="state.selectedValue"
          class="search-select"
        />
        <input
          v-model="state.inputValue"
          type="text"
          :placeholder="t('press_releases.search.placeholder')"
          class="search-input"
        />
        <button @click="handleSearch" class="search-button">
          {{ t("press_releases.search.button") }}
        </button>
      </div>
      <div class="reports-list">
        <div
          v-for="(item, idx) in state.filterNewsData"
          :key="idx"
          class="news-item table-row"
        >
          <div class="content">
            <div class="file-content">
              <div class="file-info">
                <div class="vertical-line"></div>
                <div
                  class="news-item-title text-[#000] cursor-pointer"
                  style="
                    word-break: break-all;
                    display: -webkit-box;
                    -webkit-line-clamp: 1;
                    line-clamp: 1;
                    -webkit-box-orient: vertical;
                    overflow: hidden;
                    text-overflow: ellipsis;
                  "
                  @click="handleNewClick(item)"
                >
                  {{ item.title }}
                </div>
                <svg
                  class="arrow-icon"
                  width="7"
                  height="14"
                  viewBox="0 0 7 14"
                  fill="none"
                  xmlns="http://www.w3.org/2000/svg"
                  @click="handleNewClick(item)"
                >
                  <path
                    d="M1 1L6 7L1 13"
                    stroke="#FF7BAC"
                    stroke-width="2"
                    stroke-linecap="round"
                    stroke-linejoin="round"
                  />
                </svg>
              </div>
              <n-tooltip trigger="hover" :disabled="true" width="trigger">
                <template #trigger>
                  <div
                    :ref="(el) => setTitleRef(el, idx)"
                    class="news-item-content file-description"
                    style="
                      word-break: break-all;
                      display: -webkit-box;
                      -webkit-line-clamp: 1;
                      line-clamp: 1;
                      -webkit-box-orient: vertical;
                      overflow: hidden;
                      text-overflow: ellipsis;
                    "
                  >
                    {{ item.summary }}
                  </div>
                </template>
                <div slot="content">
                  {{ item.summary }}
                </div>
              </n-tooltip>
              <div class="download-section">
                <div class="news-item-date">
                  {{
                    locale === "zh" || locale === "zh-TW"
                      ? dayjs(item.date).format("YYYY年M月D日")
                      : dayjs(item.date).format("MMMM D, YYYY")
                  }}
                </div>
              </div>
            </div>
          </div>
          <div class="separator-line"></div>
        </div>
      </div>

      <!-- 分页器 -->
      <div class="pagination-container" v-if="state.total > 0">
        <div class="pagination-info text-[#455363] mr-[15PX]">
          {{
            t("financialinformation.quarterlyreports.pagination.displaying", {
              start: (state.currentPage - 1) * state.pageSize + 1,
              end: Math.min(state.currentPage * state.pageSize, state.total),
              total: state.total,
            })
          }}
        </div>
        <NPagination
          v-model:page="state.currentPage"
          v-model:page-size="state.pageSize"
          show-size-picker
          show-quick-jumper
          :item-count="state.total"
          :page-sizes="[
            {
              label: t('historic_stock.pagination.perPage', { size: 10 }),
              value: 10,
            },
            {
              label: t('historic_stock.pagination.perPage', { size: 25 }),
              value: 25,
            },
            {
              label: t('historic_stock.pagination.perPage', { size: 50 }),
              value: 50,
            },
          ]"
          @update:page="getPressReleasesDisplay"
          @update:page-size="getPressReleasesDisplay"
        >
          <template #goto>{{
            t("financialinformation.quarterlyreports.pagination.goto")
          }}</template>
        </NPagination>
      </div>
    </main>
  </div>
</template>

<script setup>
import customDefaultPage from "@/components/customDefaultPage/index.vue";
import customSelect from "@/components/customSelect/index.vue";
import { reactive, onMounted, watch, nextTick, ref } from "vue";
import { NTooltip, NPagination } from "naive-ui";
import { useI18n } from "vue-i18n";
import axios from "axios";
import dayjs from "dayjs";

import { useRouter } from "vue-router";
const router = useRouter();
const { t } = useI18n();
const runtimeConfig = useRuntimeConfig();

const state = reactive({
  selectedValue: "all_years", //选中值
  selectOptions: [
    {
      label: "All Years",
      value: "all_years",
    },
    ...Array.from({ length: 2025 - 1990 + 1 }, (_, i) => {
      const year = 2025 - i;
      return { label: String(year), value: String(year) };
    }),
  ], //下拉选项
  inputValue: "", //输入值
  filterNewsData: [],
  loading: false, //是否正在加载数据
  currentPage: 1, //当前页码
  pageSize: 10,
  total: 0,
});

const titleRefs = ref([]);

const setTitleRef = (el, idx) => {
  if (el) titleRefs.value[idx] = el;
};

const checkAllTitleOverflow = () => {
  state.filterNewsData.forEach((item, idx) => {
    const el = titleRefs.value[idx];
    if (!el) {
      item.showTooltip = false;
      return;
    }
    item.showTooltip =
      el.scrollHeight > el.clientHeight || el.scrollWidth > el.clientWidth;
  });
};

onMounted(() => {
  getPressReleasesDisplay();

  nextTick(() => {
    checkAllTitleOverflow();
  });
});

watch(
  () => state.filterNewsData,
  () => {
    nextTick(() => {
      checkAllTitleOverflow();
    });
  },
  { deep: true }
);

const map = {
  en: "enUS",
  ja: "jaJP",
  zh: "zhCN",
  "zh-TW": "zhTW",
};

// 获取新闻列表
const getPressReleasesDisplay = () => {
  state.loading = true;
  let url = `${runtimeConfig.public.apiBase}/fiee/pressreleases/display`;
  let params = {
    query: state.inputValue,
    page: state.currentPage,
    pageSize: state.pageSize,
    timeStart: state.selectedValue
      ? state.selectedValue === "all_years"
        ? null
        : new Date(state.selectedValue).getTime()
      : null,
    langType: map[locale.value],
  };
  axios
    .post(url, params)
    .then((res) => {
      if (res.status === 200) {
        if (res.data.status === 0) {
          // res.data.data?.data?.forEach((item) => {
          //   item.date = new Date(item.date).toLocaleDateString("en-US", {
          //     month: "short",
          //     day: "numeric",
          //     year: "numeric",
          //   });
          // });
          state.filterNewsData = res.data.data?.data || [];
          state.total = res.data.data?.total || 0;
        }
      }
    })
    .finally(() => {
      state.loading = false;
    });
};

watch(locale, (newLocale, oldLocale) => {
  // 页码重置为第一页
  state.currentPage = 1;
  getPressReleasesDisplay();
});
// 添加 watcher 来实现自动筛选
watch(
  () => [state.selectedValue, state.inputValue],
  () => {
    state.currentPage = 1;
    getPressReleasesDisplay();
  }
);

watch(
  () => state.pageSize,
  () => {
    state.currentPage = 1;
    getPressReleasesDisplay();
  }
);

watch(
  () => state.currentPage,
  (newPage) => {
    getPressReleasesDisplay();
  }
);

const handleSearch = () => {
  state.currentPage = 1;
  getPressReleasesDisplay();
};

const handleNewClick = (item) => {
  router.push({
    path: "/news",
    query: {
      id: item.uuid,
    },
  });
};
</script>

<style scoped lang="scss">
.press-releases-page {
  width: 1240px;
  margin: 0 auto;
}
.title-section {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 0 16px;
  margin-bottom: 40px;
}
.title-decoration {
  width: 58px;
  height: 7px;
  background: #ff7bac;
  margin: auto 0;
  margin-top: 43px;
}
.title {
  font-family: "PingFang SC", sans-serif;
  font-size: 48px;
  font-style: normal;
  font-weight: 500;
  line-height: 58px;
  color: #000;
}

.search-container {
  margin-bottom: 20px;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: flex-start;
  gap: 16px;
  padding: 0 16px;
}

.search-select {
  width: 200px;
}

.search-input {
  flex: 1;
  height: 46px;
  padding: 7px 12px;
  border: 1px solid #e0e0e6;
  border-radius: 3px;
  font-family: "PingFang SC", sans-serif;
  font-weight: 400;
  font-size: 16px;
  line-height: 1.375em;
  letter-spacing: 0.03em;
  color: #455363;
  box-sizing: border-box;

  &::placeholder {
    color: #b6b6b6;
  }
}

.search-button {
  height: 46px;
  padding: 7px 12px;
  min-width: 201px;
  background: #ff7bac;
  color: #fff;
  border: none;
  border-radius: 3px;
  cursor: pointer;
  font-family: "PingFang SC", sans-serif;
  font-weight: 400;
  font-size: 16px;
  line-height: 1.375em;
  letter-spacing: 0.03em;
  box-sizing: border-box;
  &:hover {
    background: #ff7bac;
    color: #fff;
  }
}

.reports-list {
  display: flex;
  flex-direction: column;
  gap: 4px;
  background: #fff;
}

.table-row {
  display: flex;
  flex-direction: column;
  position: relative;
  border-radius: 8px;

  // &:last-child {
  //   .separator-line {
  //     display: none;
  //   }
  // }
}

.content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.table-row .content {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  gap: 0;
  padding: 24px 0;
}

.file-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  padding-right: 16px;
  &:hover {
    background: #fff8fb;
  }
}

.file-info {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 16px;
  flex: 1;
}

.news-item-title {
  font-family: "PingFang SC", sans-serif;
  font-weight: 500;
  font-size: 20px;
  line-height: 24px;
  color: #000000;
}

.arrow-icon {
  margin-left: auto;
  flex-shrink: 0;
  cursor: pointer;
}

.vertical-line {
  width: 1px;
  height: 20px;
  background: #ff7bac;
  flex-shrink: 0;
}

.file-description {
  font-family: "PingFang SC", sans-serif;
  font-weight: 400;
  font-size: 16px;
  line-height: 1.375em;
  letter-spacing: 0.03em;
  color: #455363;
  margin: 0;
  padding: 0 21px;
  margin-top: 4px;
}

.news-item-date {
  font-family: "PingFang SC", sans-serif;
  font-weight: 400;
  font-size: 20px;
  line-height: 24px;
  color: #455363;
}

.download-section {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  width: 100%;
  padding: 4px 16px;
}

.separator-line {
  width: 100%;
  height: 1px;
  background: repeating-linear-gradient(
    to right,
    #e0e0e6 0px,
    #e0e0e6 4px,
    transparent 4px,
    transparent 8px
  );
  margin-top: 0;
}

// 分页器样式
.pagination-container {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 15px;
  margin-bottom: 30px;
  gap: 21px;
}

.pagination-info {
  font-family: "PingFang SC", sans-serif;
  font-weight: 400;
  font-size: 16px;
  line-height: 1.4375em;
  color: #455363;
  text-align: right;
}

:deep(.n-base-loading__icon) {
  color: #ff7bac;
}
</style>
