const { photoBookHome } = require("../../mock/photoBook");

Page({
  data: {
    home: photoBookHome,
    errorText: "",
  },

  onLoad() {
    this.fetchHomeData();
  },

  async fetchHomeData() {
    const app = getApp();
    if (!app.globalData.env) {
      this.setData({
        home: photoBookHome,
        errorText: "未配置云环境，当前展示 mock 数据",
      });
      return;
    }

    try {
      const res = await wx.cloud.callFunction({
        name: "quickstartFunctions",
        data: {
          type: "getPhotoBookHome",
        },
      });

      const payload = res && res.result && res.result.data;
      if (!payload) {
        throw new Error("empty payload");
      }

      this.setData({
        home: this.normalizeHome(payload),
        errorText: "",
      });
    } catch (err) {
      console.error("getPhotoBookHome failed", err);
      this.setData({
        home: photoBookHome,
        errorText: "云端数据拉取失败，已展示 mock 数据",
      });
    }
  },

  normalizeHome(home) {
    const next = { ...photoBookHome, ...(home || {}) };
    const works = Array.isArray(next.works) ? next.works : [];
    const packages = Array.isArray(next.packages) ? next.packages : [];

    if (works.length < 3) {
      next.works = photoBookHome.works;
    } else {
      next.works = works.map((item, idx) => {
        if (typeof item === "string") {
          return {
            id: `w_${idx}`,
            cover: item,
            category: "全部",
            ratio: idx === 0 ? "wide" : "tall",
            title: `客片 ${idx + 1}`,
            scene: "街拍",
          };
        }
        return {
          id: item.id || `w_${idx}`,
          cover: item.cover || photoBookHome.works[0].cover,
          category: item.category || "全部",
          ratio: item.ratio || (idx === 0 ? "wide" : "tall"),
          title: item.title || `客片 ${idx + 1}`,
          scene: item.scene || "街拍",
        };
      });
    }

    if (!packages.length) {
      next.packages = photoBookHome.packages;
    }

    if (!Array.isArray(next.tags) || !next.tags.length) {
      next.tags = photoBookHome.tags;
    }

    if (!next.heroImage) {
      next.heroImage = photoBookHome.heroImage;
    }
    if (!next.portfolioCount) {
      next.portfolioCount = photoBookHome.portfolioCount || next.works.length;
    }
    if (!next.updateText) {
      next.updateText = photoBookHome.updateText || "最近更新客片";
    }

    return next;
  },

  onTapHomeWorkPreview(e) {
    const index = Number(e.currentTarget.dataset.index || 0);
    const works = this.data.home.works || [];
    const urls = works.map((item) => item.cover).filter(Boolean);
    if (!urls.length) {
      return;
    }
    wx.previewImage({
      current: urls[index] || urls[0],
      urls,
    });
  },

  onTapLookWorks() {
    wx.switchTab({
      url: "/pages/works/index",
    });
  },

  onTapViewAllWorks() {
    wx.switchTab({
      url: "/pages/works/index",
    });
  },

  onTapPackage(e) {
    const packageId = e.currentTarget.dataset.id || "";
    wx.navigateTo({
      url: `/pages/package-detail/index?id=${packageId}`,
    });
  },

  onTapPackageDetail(e) {
    const packageId = e.currentTarget.dataset.id || "";
    wx.navigateTo({
      url: `/pages/package-detail/index?id=${packageId}`,
    });
  },

  onTapPackageBook(e) {
    const packageId = e.currentTarget.dataset.id || "";
    wx.navigateTo({
      url: `/pages/booking/index?packageId=${packageId}`,
    });
  },

  onTapBookNow() {
    wx.navigateTo({
      url: "/pages/booking/index",
    });
  },
});
