import { defineStore } from "pinia";
import { request } from "../api";

export const useExhibitionStore = defineStore({
  id: "exhibition",
  state: () => {
    return {
      isLoadMoreLock: false,
      lists: [],
      detail: {},
      total: 0,
      pagination: {
        type: "",
        endTime: "",
        pageNum: 0,
        pageSize: 20,
        searchKey: "",
        startTime: "",
      },
    };
  },
  getters: {
    canLoadMore() {
      return this.isLoad && !this.isLast && !this.isLoadMoreLock;
    },
    isLoad() {
      return this.total > 0;
    },
    isLast() {
      return (
        this.pagination.current &&
        this.pagination.pages &&
        this.pagination.pages === this.pagination.current
      );
    },
  },
  actions: {
    async fetch() {
      const { data, status } = await request.post("/show/exhibition/pageList", {
        ...this.pagination,
      });
      if (data.code === 0) {
        if (this.pagination.pageNum === 1) {
          this.lists = [];
        }
        const { records, total, current, pages } = data.data;
        const templists = this.lists.concat(records);
        this.lists = templists;
        this.total = total;
        this.pagination.current = current;
        this.pagination.pages = pages;
        this.isLoadMoreLock = false;
        return Promise.resolve(0);
      } else {
        this.lists = [];
        return Promise.resolve(1);
      }
    },
    async getExhibitionList(page, type) {
      this.pagination.pageNum = page || 1;
      this.pagination.type = type === "all" ? "" : type;
      return await this.fetch();
    },

    async getDetail(id) {
      const { data, status } = await request.get(
        `show/exhibition/detail/${id}`
      );
      if (data.code === 0) {
        this.detail = data.data;
      } else {
        this.detail = {};
      }
    },
    async search(searchKey, type) {
      this.pagination.searchKey = searchKey;
      this.pagination.pageNum = 1;
      this.pagination.type = type === all ? "" : type;
      await this.fetch();
    },
    async clearSearch() {
      this.pagination.searchKey = "";
    },
    resetPage() {
      this.total = 0;
      this.pagination = {
        pageNum: 1,
        pageSize: 20,
        searchKey: "",
        type: "",
        current: null,
        pages: null,
      };
    },
    async switchTab() {},
    async loadMore(type) {
      if (!this.isLoadMoreLock && !this.isLast) {
        this.isLoadMoreLock = true;
        this.pagination.type = type === "all" ? "" : type;
        const page =
          this.pagination.pageNum < this.pagination.pages
            ? this.pagination.pageNum + 1
            : this.pagination.pages;

        this.pagination.pageNum = page;

        return await this.fetch();
      }
    },
  },
});
