<template>
  <!-- 主容器 -->
  <div>
    <!-- 搜索表单 -->
    <SearchForm
      ref="searchForm"
      :loading="loading"
      :options="searchOptions"
      @search="search"
      @reset="search"
    />
    <!-- 标签选择器 -->
    <a-card
      :bordered="false"
      class="ant-pro-components-tag-select"
      style="margin-bottom: -82px"
    >
      <a-form :form="form" layout="inline">
        <!-- 类目选择 -->
        <standard-form-row title="所属类目" block style="padding-bottom: 11px">
          <a-form-item>
            <!-- 标签选择器组件 -->
            <tag-select>
              <!-- 类目选项 -->
              <!-- 全部选项 -->
              <tag-select-option value="全部" @click.native="getList"
                ><h3><a-icon type="audit" />全部</h3></tag-select-option
              >
              <tag-select-option value="公告" @click.native="search('公告')"
                ><h3><a-icon type="audit" />公告</h3></tag-select-option
              >
              <tag-select-option value="交流" @click.native="search('交流')"
                ><h3><a-icon type="audit" />交流</h3></tag-select-option
              >
              <tag-select-option value="讨论" @click.native="search('讨论')"
                ><h3><a-icon type="audit" />讨论</h3></tag-select-option
              >
            </tag-select>
          </a-form-item>
        </standard-form-row>
      </a-form>
    </a-card>
    <!-- 文章列表 -->
    <a-card style="margin-top: 24px" :bordered="false">
      <a-list
        size="large"
        rowKey="id"
        :loading="loading"
        itemLayout="vertical"
        :dataSource="data"
        :pagination="pagination"
        @change="changePage"
      >
        <div class="side-brick">
          <ul class="brick-box">
            <li class="brick-list" v-for="item in data" key="item.id">
              <router-link :to="'/community/pages?id=' + item.articleId">
                <a class="item-box-retina">
                  <figure class="item-box-img">
                    <!-- 文章图片 -->
                    <!-- 调用extractImageUrl方法并传递文章内容 -->
                    <img
                      class="lazy"
                      :src="extractImageUrl(item.articleContent)"
                      alt="Article Cover"
                    />
                    <!-- <img class="lazy" :src="item.articleContent.match(imageUrlRegex)" > -->
                    <!-- 文章标题 -->
                    <h3>{{ item.articleTitle }}</h3>
                  </figure>
                  <!-- 文章内容 -->
                  <p class="item-user-info" v-html="item.articleContent"></p>
                  <p class="item-user-author">
                    <img src="/logo.png" :alt="userData[item.userId]" />
                    <!-- 文章作者 -->
                    <span class="comment-username"
                      >{{ userData[item.userId]
                      }}<span class="autlv aut-5 vs-level">V</span></span
                    >
                    <span class="comment-tip"
                      ><i class="icon font-time"></i
                      >{{ item.publishTime | formatTime }}</span
                    >
                  </p>
                </a>
              </router-link>
            </li>
          </ul>
        </div>
      </a-list>
    </a-card>
  </div>
</template>

<script>
import TagSelect from "../../components/TagSelect";
import StandardFormRow from "../../components/StandardFormRow";
import ArticleListContent from "../../components/ArticleListContent";
import IconText from "./components/IconText";
const TagSelectOption = TagSelect.Option;
export default {
  components: {
    TagSelect,
    TagSelectOption,
    StandardFormRow,
    ArticleListContent,
    IconText,
  },
  data() {
    return {
      userData: [],
      imageUrlRegex: /(http[s]?:\/\/[^(\s|")]+\.(png|jpg|jpeg|gif|webp))/gi,
      current: 1,
      pageSize: 4,
      loading: true,
      loadingMore: false,
      data: [],
      originalUsers: [],
      total: 0,
      form: this.$form.createForm(this),
    };
  },
  mounted() {
    this.getUser();
    this.$watch(() => [this.pageSize, this.current], this.getList, {
      immediate: true,
    });
  },
  filters: {
    formatTime: function (value) {
      // 在这里编写时间格式化逻辑，例如：
      const parsedTime = new Date(value);
      const year = parsedTime.getFullYear();
      const month = String(parsedTime.getMonth() + 1).padStart(2, "0");
      const day = String(parsedTime.getDate()).padStart(2, "0");
      return `${year}-${month}-${day}`;
    },
  },
  computed: {
    searchOptions() {
      return createSearchOptions.call(this);
    },
    pagination() {
      return {
        current: this.current,
        pageSize: this.pageSize,
        total: this.total,
        showSizeChanger: true,
        pageSizeOptions: ["4", "8", "10", "20"],
        showQuickJumper: true,
        showTotal: (total) => `Total ${total} items`,
        onChange: this.changePage,
        onShowSizeChange: this.changePage,
      };
    },
  },
  methods: {
    extractImageUrl(content) {
      // 定义匹配图片URL的正则表达式
      const imageUrlRegex =
        /(http[s]?:\/\/[^(\s|")]+\.(png|jpg|jpeg|gif|webp))/gi;
      // 使用正则表达式匹配内容中的图片URL
      const matches = content.match(imageUrlRegex);
      // 如果找到匹配项，返回第一张图片的URL
      if (matches && matches.length > 0) {
        return matches[0];
      }
      // 避免浏览器缓存
      const randomSeed = Math.floor(Math.random() * 10000); // 生成一个0到9999之间的随机数
      // 如果没有找到匹配的图片，可以使用随机图片
      return "https://tu.ltyuanfang.cn/api/fengjing.php?" + randomSeed;
    },
    async getImage(articleId) {
      try {
        const res = await this.$api.AllArticle();
        let content = res.data.filter((item) => item.articleId === articleId);

        if (content.length === 0) {
          console.log("未找到对应文章内容");
          return null; // 返回空值，表示未找到封面图片
        }

        const imageUrlRegex =
          /(http[s]?:\/\/[^(\s|")]+\.(png|jpg|jpeg|gif|webp))/gi;
        const images = content[0].articleContent.match(imageUrlRegex);

        if (images && images.length > 0) {
          console.log("找到封面图片链接:", images[0]);
          return images[0]; // 返回第一张匹配到的图片链接
        } else {
          console.log("未找到图片链接");
          return null; // 返回空值，表示未找到封面图片
        }
      } catch (error) {
        console.error("获取文章内容失败:", error);
        return null; // 返回空值，表示未找到封面图片
      }
    },
    // 搜索
    search() {
      this.current = 1;
      this.getList();
    },
    // 分页切换
    changePage(current, pageSize) {
      this.current = current;
      this.pageSize = pageSize;
      this.getList();
    },
    handleChange(value) {
      console.log(`selected ${value}`);
    },
    getUser() {
      this.$api
        .AllUser()
        .then((res) => {
          const users = res.data;
          const userMap = {};
          users.forEach((user) => {
            userMap[user.userId] = user.userName;
          });
          this.userData = userMap;
          console.log(this.userData);
        })
        .catch((error) => {
          console.error(error);
        });
    },
    async getList() {
      try {
        // 开始加载，显示加载指示器
        this.loading = true;
        this.query = this.$refs.searchForm.getResult();
        // 使用 await 直接等待异步操作的结果
        const res = await this.$api.AllArticle();
        // 打印响应结果
        this.originalUsers = res.data;
        this.filterUsers(); // 调用过滤用户方法
        console.log("res", res.data);
        // 使用响应结果更新数据
        this.total = res.data.length;
      } catch (error) {
        // 处理可能出现的错误
        console.error("获取文章列表失败:", error);
      } finally {
        // 无论成功还是失败，最后都会执行，隐藏加载指示器
        this.loading = false;
      }
    },
    // 搜索
    filterUsers() {
      let filteredUsers = this.originalUsers.slice(); // 复制原始用户数据
      console.log(this.query);
      if (this.query.articleTitle) {
        filteredUsers = filteredUsers.filter((user) =>
          user.articleTitle.includes(this.query.articleTitle)
        );
      }

      if (this.query.userName) {
        filteredUsers = filteredUsers.filter((user) =>
          user.userId.includes(this.query.userName)
        );
      }
      if (this.query.articleContent) {
        filteredUsers = filteredUsers.filter((user) =>
          user.articleContent.includes(this.query.articleContent)
        );
      }
      const start = (this.current - 1) * this.pageSize;
      const end = start + this.pageSize;
      this.data = filteredUsers.slice(start, end);
    },
  },
};
// 创建搜索选项
function createSearchOptions() {
  return [
    {
      label: "标题",
      key: "articleTitle",
      default: "",
      component: "input",
    },
    {
      label: "作者",
      key: "userName",
      default: "",
      component: "input",
    },
    {
      label: "内容",
      key: "articleContent",
      default: "",
      component: "input",
    },
    {
      label: "时间",
      key: "publishTime",
      default: () => [],
      mapper: ({ publishTime }) => publishTime.join("~"),
      component: "range-picker",
    },
  ];
}
</script>

<style lang="less" scoped>
/* 全局样式优化 */
body {
  color: #333;
  font-family: "PingFang SC", "Microsoft YaHei", sans-serif;
  font-size: 14px;
  line-height: 1.5;
  background-color: #f6f8fa;
  background-image: linear-gradient(
    to bottom,
    rgba(240, 244, 248, 0.8),
    rgba(255, 255, 255, 0.8)
  );
}

/* 主容器样式 */
.ant-card {
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  overflow: hidden;
  border: none;
}

.ant-card:hover {
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
  transform: translateY(-2px);
}

/* 搜索表单美化 */
.ant-form .ant-form-item {
  margin-bottom: 16px;
}

.ant-input {
  border-radius: 8px;
  padding: 10px 16px;
  transition: all 0.3s;
}

.ant-input:hover,
.ant-input:focus {
  border-color: #3690cf;
  box-shadow: 0 0 0 2px rgba(54, 144, 207, 0.2);
}

.ant-btn {
  border-radius: 8px;
  padding: 8px 20px;
  height: auto;
  font-weight: 500;
  transition: all 0.3s;
}

.ant-btn-primary {
  background: linear-gradient(135deg, #3690cf, #2a78b8);
  border: none;
}

.ant-btn-primary:hover {
  background: linear-gradient(135deg, #2a78b8, #1e5c8e);
  transform: translateY(-1px);
}

/* 标签选择器美化 */
.ant-pro-components-tag-select {
  margin-bottom: 0 !important;
  padding: 16px;
  border-radius: 12px;
}

.tag-select {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.ant-tag {
  border-radius: 20px;
  padding: 6px 16px !important;
  margin-right: 16px !important;
  font-size: 14px !important;
  cursor: pointer;
  transition: all 0.3s;
  background-color: #f0f2f5;
  border: none;
}

.ant-tag:hover {
  background-color: #e6f7ff;
  color: #3690cf;
}

.ant-tag-checkable-checked {
  background: linear-gradient(135deg, #3690cf, #2a78b8) !important;
  color: white !important;
  font-weight: 500;
}

.ant-tag-checkable-checked:hover {
  color: white !important;
  opacity: 0.9;
}

.ant-tag .anticon {
  margin-right: 4px;
}

/* 文章卡片列表样式 */
.side-brick {
  background: white;
  border: none;
  border-radius: 12px;
  padding: 20px;
  box-shadow: none;
}

.brick-box {
  display: flex;
  flex-wrap: wrap;
  margin-right: -20px;
  margin-top: 10px;
}

li.brick-list {
  width: 23%;
  margin-right: 2%;
  margin-bottom: 30px;
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.4s cubic-bezier(0.25, 0.8, 0.25, 1);
  background-color: white;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.05);
}

li.brick-list:hover {
  transform: translateY(-6px);
  box-shadow: 0 12px 20px rgba(0, 0, 0, 0.1);
}

/* 文章图片容器 */
figure.item-box-img {
  height: 190px;
  position: relative;
  overflow: hidden;
  border-radius: 12px 12px 0 0;
}

figure.item-box-img img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.6s;
}

li.brick-list:hover figure.item-box-img img {
  transform: scale(1.08);
}

/* 文章标题样式 */
figure.item-box-img h3 {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  padding: 15px;
  margin: 0;
  background: linear-gradient(to top, rgba(0, 0, 0, 0.7), transparent);
  color: white;
  font-size: 16px;
  font-weight: 500;
  line-height: 1.4;
  z-index: 1;
}

/* 文章内容样式 */
p.item-user-info {
  padding: 0 15px;
  margin-top: 15px;
  height: 44px;
  line-height: 1.6;
  font-size: 13px;
  color: #666;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

/* 文章作者信息 */
p.item-user-author {
  padding: 0 15px 15px;
  margin-top: 10px;
  display: flex;
  align-items: center;
  font-size: 12px;
  color: #999;
  border-top: 1px solid rgba(0, 0, 0, 0.05);
  padding-top: 12px;
}

p.item-user-author img {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  margin-right: 8px;
  border: 2px solid #fff;
  box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.1);
}

.comment-username {
  font-weight: 500;
  color: #555;
  margin-right: 8px;
}

.autlv {
  display: inline-block;
  width: 16px;
  height: 16px;
  line-height: 16px;
  text-align: center;
  font-size: 10px;
  color: white;
  background-color: #ff9800;
  border-radius: 3px;
  margin-left: 4px;
  vertical-align: text-top;
}

.comment-tip {
  margin-left: auto;
  color: #aaa;
}

.comment-tip i {
  margin-right: 4px;
}

/* 分页样式 */
.ant-pagination {
  margin-top: 20px;
  text-align: center;
}

.ant-pagination-item {
  border-radius: 8px;
  transition: all 0.3s;
}

.ant-pagination-item:hover {
  border-color: #3690cf;
}

.ant-pagination-item-active {
  background-color: #3690cf;
  border-color: #3690cf;
}

.ant-pagination-item-active a {
  color: white;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  li.brick-list {
    width: 31.333%;
    margin-right: 2%;
  }
}

@media (max-width: 768px) {
  li.brick-list {
    width: 48%;
    margin-right: 2%;
  }

  figure.item-box-img {
    height: 160px;
  }
}

@media (max-width: 480px) {
  li.brick-list {
    width: 100%;
    margin-right: 0;
  }

  figure.item-box-img {
    height: 180px;
  }
}

/* 优化卡片布局 */
.item-box-retina {
  display: block;
  height: 100%;
  display: flex;
  flex-direction: column;
  border-radius: 12px;
  overflow: hidden;
  text-decoration: none !important;
}

/* 额外美化细节 */
.side-title-wrap h3.widget-title {
  font-size: 18px;
  font-weight: 600;
  border-left: 4px solid #3690cf;
  padding-left: 12px;
  margin-bottom: 20px;
}

/* 添加按钮悬停效果 */
.ant-btn-primary {
  position: relative;
  overflow: hidden;
}

.ant-btn-primary:after {
  content: "";
  position: absolute;
  top: 50%;
  left: 50%;
  width: 10px;
  height: 10px;
  background: rgba(255, 255, 255, 0.3);
  opacity: 0;
  border-radius: 100%;
  transform: scale(1, 1) translate(-50%);
  transform-origin: 50% 50%;
}

.ant-btn-primary:hover:after {
  animation: ripple 1s ease-out;
}

@keyframes ripple {
  0% {
    transform: scale(0, 0);
    opacity: 0.5;
  }
  20% {
    transform: scale(25, 25);
    opacity: 0.3;
  }
  100% {
    opacity: 0;
    transform: scale(40, 40);
  }
}

/* 优化搜索表单 */
.search-form {
  background: white;
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 24px;
}

.search-form .ant-form-item-label > label {
  font-weight: 500;
  color: #333;
}

/* 自定义滚动条 */
::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 10px;
}

::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 10px;
}

::-webkit-scrollbar-thumb:hover {
  background: #3690cf;
}
</style>
