/* eslint-disable eqeqeq */
import { model, getAll } from '../_utils/model';
import { getCloudImageTempUrl } from '../../utils/cloudImageHandler';
import { SPU_SELLING_STATUS } from '../../utils/spuStatus';
import { DATA_MODEL_KEY } from '../../config/model';
import { cloudbaseTemplateConfig } from '../../config/index';
import { CATEGORY, SPU } from '../cloudbaseMock/index';

const CATE_MODEL_KEY = DATA_MODEL_KEY.CATE;
const HOME_SWIPER_MODEL_KEY = DATA_MODEL_KEY.HOME_SWIPER;

// TODO: we should do pagination
export async function getAllSpuOfCate(cateId) {
  if (cloudbaseTemplateConfig.useMock) {
    return { spu: CATEGORY.find((x) => x._id === cateId).spu.map(({ _id }) => SPU.find((x) => x._id === _id)) };
  }

  return (
    await model()[CATE_MODEL_KEY].get({
      filter: {
        where: {
          _id: {
            $eq: cateId,
          },
        },
        relateWhere: {
          spu: {
            where: {
              status: {
                $eq: SPU_SELLING_STATUS,
              },
            },
          },
        },
      },
      select: {
        spu: {
          $master: true,
        },
      },
    })
  ).data;
}

export async function getCates() {
  if (cloudbaseTemplateConfig.useMock) {
    return CATEGORY.filter((x) => x.child_cate?.length > 0);
  }
  const cateSelect = {
    _id: true,
    name: true,
    image: true,
  };

  const allCates = (
    await getAll({
      name: CATE_MODEL_KEY,
      select: {
        ...cateSelect,
        child_cate: cateSelect,
      },
    })
  ).filter((c) => c.child_cate.length !== 0);

  const childCates = allCates.flatMap((c) => c.child_cate);
  const res = await getCloudImageTempUrl(childCates.map((x) => x.image));
  res.forEach((image, index) => (childCates[index].image = image));
  return allCates;
}

export async function getSwipe() {
  // console.log("cloudbaseTemplateConfig.useMock",cloudbaseTemplateConfig.useMock);
  if (cloudbaseTemplateConfig.useMock) {
    // 返回包含多张模拟图片的数据
    return {
      images: [
        'https://qcloudimg.tencent-cloud.cn/raw/1e793c70bb4f521fe277b2c207ab81b4.png',
        'https://qcloudimg.tencent-cloud.cn/raw/063123361b3a397f4ba6894591c3a006.png',
        'https://qcloudimg.tencent-cloud.cn/raw/62eb1d8d8ea3b05302c199636f787438.png'
      ]
    };
  }
  // 实际环境中获取所有记录，然后提取所有图片
  const records = (await model()[HOME_SWIPER_MODEL_KEY].list({ select: { images: true } })).data.records;
 // console.log("records:",records);
 // console.log("records[1].images:",records[1].images);
  // 合并所有记录中的images数组
  const allImages = records[1].images; //records.flatMap(record => record.images || []);
  return { images: allImages.length > 0 ? allImages : [] };
}
