import { getQuestionInfoByIds, CollectionAndWrong } from "@/api";

/**收藏与错题列表模型 */
export class CollectionModel {
  private collectionApi;

  constructor(apiType: CollectionAndWrongType.type) {
    this.collectionApi = new CollectionAndWrong(apiType);
  }

  /**获取列表 */
  async getList(params: CollectionAndWrongType.ListParams): Promise<{
    total: number;
    rows: Test.QuestionInfo[];
    collectionList: CollectionAndWrongType.QuestionRes[];
  }> {
    const collectionListRes = await this.collectionApi.getList(params);
    if (collectionListRes.rows.length > 0) {
      const ids = collectionListRes.rows.map((item) => item.questionId);
      const questions = await getQuestionInfoByIds({
        ids,
      });
      return {
        total: collectionListRes.total,
        rows: questions.rows,
        collectionList: collectionListRes.rows,
      };
    } else {
      return {
        total: collectionListRes.total,
        rows: [],
        collectionList: collectionListRes.rows,
      };
    }
  }

  /** 删除已收藏的问题 */
  async deletes(
    ids: number[],
    collectionList: CollectionAndWrongType.QuestionRes[]
  ) {
    const deletesCollectionList = collectionList.filter((item) => {
      return ids.includes(item.questionId);
    });
    const deletesIds = deletesCollectionList.map((item) => item.id);
    const res = await this.collectionApi.deletes(deletesIds);
    return res;
  }

  /** 新增收藏或者错题 */
  async adds(params: CollectionAndWrongType.AddCullectionsParams) {
    const res = await this.collectionApi.adds(params);
    return res.data;
  }
}
