const cloud = require("wx-server-sdk");
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV,
});

const db = cloud.database();

const DEFAULT_PHOTO_BOOK_HOME = {
  photographerName: "陪你拍阿柚",
  photographerTagline: "温柔日系私房写真 · 闺蜜情侣生日跟拍",
  heroImage:
    "https://images.unsplash.com/photo-1524504388940-b1c1722653e1?auto=format&fit=crop&w=1200&q=80",
  tags: ["情侣", "闺蜜", "生日", "汉服"],
  works: [
    {
      id: "w1",
      cover:
        "https://images.unsplash.com/photo-1521572267360-ee0c2909d518?auto=format&fit=crop&w=900&q=80",
    },
    {
      id: "w2",
      cover:
        "https://images.unsplash.com/photo-1524863479829-916d8e77f114?auto=format&fit=crop&w=900&q=80",
    },
    {
      id: "w3",
      cover:
        "https://images.unsplash.com/photo-1464863979621-258859e62245?auto=format&fit=crop&w=900&q=80",
    },
  ],
  packages: [
    {
      id: "p1",
      badge: "🔥 热门",
      title: "2小时轻陪拍",
      desc: "含台词一次拍摄片 + 情侣合影",
      price: 399,
    },
    {
      id: "p2",
      badge: "",
      title: "3小时沉浸拍摄",
      desc: "更自由更出片",
      price: 699,
    },
  ],
  ctaText: "去预约一次拍照",
};

const safeGetCollection = async (name, query = {}) => {
  try {
    return await db.collection(name).where(query).get();
  } catch (e) {
    return { data: [] };
  }
};
// 获取openid
const getOpenId = async () => {
  // 获取基础信息
  const wxContext = cloud.getWXContext();
  return {
    openid: wxContext.OPENID,
    appid: wxContext.APPID,
    unionid: wxContext.UNIONID,
  };
};

// 获取小程序二维码
const getMiniProgramCode = async () => {
  // 获取小程序二维码的buffer
  const resp = await cloud.openapi.wxacode.get({
    path: "pages/index/index",
  });
  const { buffer } = resp;
  // 将图片上传云存储空间
  const upload = await cloud.uploadFile({
    cloudPath: "code.png",
    fileContent: buffer,
  });
  return upload.fileID;
};

// 创建集合
const createCollection = async () => {
  try {
    // 创建集合
    await db.createCollection("sales");
    await db.collection("sales").add({
      // data 字段表示需新增的 JSON 数据
      data: {
        region: "华东",
        city: "上海",
        sales: 11,
      },
    });
    await db.collection("sales").add({
      // data 字段表示需新增的 JSON 数据
      data: {
        region: "华东",
        city: "南京",
        sales: 11,
      },
    });
    await db.collection("sales").add({
      // data 字段表示需新增的 JSON 数据
      data: {
        region: "华南",
        city: "广州",
        sales: 22,
      },
    });
    await db.collection("sales").add({
      // data 字段表示需新增的 JSON 数据
      data: {
        region: "华南",
        city: "深圳",
        sales: 22,
      },
    });
    return {
      success: true,
    };
  } catch (e) {
    // 这里catch到的是该collection已经存在，从业务逻辑上来说是运行成功的，所以catch返回success给前端，避免工具在前端抛出异常
    return {
      success: true,
      data: "create collection success",
    };
  }
};

// 查询数据
const selectRecord = async () => {
  // 返回数据库查询结果
  return await db.collection("sales").get();
};

// 更新数据
const updateRecord = async (event) => {
  try {
    // 遍历修改数据库信息
    for (let i = 0; i < event.data.length; i++) {
      await db
        .collection("sales")
        .where({
          _id: event.data[i]._id,
        })
        .update({
          data: {
            sales: event.data[i].sales,
          },
        });
    }
    return {
      success: true,
      data: event.data,
    };
  } catch (e) {
    return {
      success: false,
      errMsg: e,
    };
  }
};

// 新增数据
const insertRecord = async (event) => {
  try {
    const insertRecord = event.data;
    // 插入数据
    await db.collection("sales").add({
      data: {
        region: insertRecord.region,
        city: insertRecord.city,
        sales: Number(insertRecord.sales),
      },
    });
    return {
      success: true,
      data: event.data,
    };
  } catch (e) {
    return {
      success: false,
      errMsg: e,
    };
  }
};

// 删除数据
const deleteRecord = async (event) => {
  try {
    await db
      .collection("sales")
      .where({
        _id: event.data._id,
      })
      .remove();
    return {
      success: true,
    };
  } catch (e) {
    return {
      success: false,
      errMsg: e,
    };
  }
};

// 摄影书主页
const getPhotoBookHome = async () => {
  const profileRes = await safeGetCollection("photographer_profiles", {
    enabled: true,
  });
  const worksRes = await safeGetCollection("photographer_works", {
    enabled: true,
  });
  const packageRes = await safeGetCollection("photo_packages", {
    enabled: true,
  });

  const profile = profileRes.data[0] || {};
  const works = (worksRes.data || []).slice(0, 6);
  const packages = (packageRes.data || []).slice(0, 6);

  const fromCloud = Boolean(
    profile.photographerName || works.length || packages.length
  );

  if (!fromCloud) {
    return {
      success: true,
      source: "fallback",
      data: DEFAULT_PHOTO_BOOK_HOME,
    };
  }

  return {
    success: true,
    source: "cloud",
    data: {
      photographerName:
        profile.photographerName || DEFAULT_PHOTO_BOOK_HOME.photographerName,
      photographerTagline:
        profile.photographerTagline ||
        DEFAULT_PHOTO_BOOK_HOME.photographerTagline,
      heroImage: profile.heroImage || DEFAULT_PHOTO_BOOK_HOME.heroImage,
      tags: profile.tags || DEFAULT_PHOTO_BOOK_HOME.tags,
      works:
        works.map((item) => ({
          id: item._id,
          cover: item.cover,
        })) || DEFAULT_PHOTO_BOOK_HOME.works,
      packages:
        packages.map((item) => ({
          id: item._id,
          badge: item.badge || "",
          title: item.title,
          desc: item.desc,
          price: item.price,
        })) || DEFAULT_PHOTO_BOOK_HOME.packages,
      ctaText: profile.ctaText || DEFAULT_PHOTO_BOOK_HOME.ctaText,
    },
  };
};

// const getOpenId = require('./getOpenId/index');
// const getMiniProgramCode = require('./getMiniProgramCode/index');
// const createCollection = require('./createCollection/index');
// const selectRecord = require('./selectRecord/index');
// const updateRecord = require('./updateRecord/index');
// const fetchGoodsList = require('./fetchGoodsList/index');
// const genMpQrcode = require('./genMpQrcode/index');
// 云函数入口函数
exports.main = async (event, context) => {
  switch (event.type) {
    case "getOpenId":
      return await getOpenId();
    case "getMiniProgramCode":
      return await getMiniProgramCode();
    case "createCollection":
      return await createCollection();
    case "selectRecord":
      return await selectRecord();
    case "updateRecord":
      return await updateRecord(event);
    case "insertRecord":
      return await insertRecord(event);
    case "deleteRecord":
      return await deleteRecord(event);
    case "getPhotoBookHome":
      return await getPhotoBookHome();
  }
};
