import type { FindPageResponse } from '../basic'

import { get, post } from '#/api/http'

import { BasicService } from '../basic'

const chapterTree2options = (tree: any[]): any[] => {
  if (!tree || tree.length === 0) {
    return undefined as any
  }
  return tree.map((item: any) => {
    return {
      label: item.name,
      value: item.id,
      children: chapterTree2options(item.children || []),
    }
  })
}

class SchoolBookService extends BasicService {
  override async findPage(
    _current: number,
    _size: number,
    condition: any,
  ): Promise<FindPageResponse> {
    const data = await get<any[]>('/xkw/textbook/myTextbooks', condition)
    const rows = (data || []).map((item: any) => ({
      ...item,
      id: item.id ?? item.textbookId,
      name: item.name ?? item.textbookName,
    }))
    return {
      current: 1,
      size: rows.length,
      totalPage: 1,
      totalRows: rows.length,
      rows,
    }
  }

  async getChapterTree(textBookId: any) {
    return await get('/xkw/textbookCatalog/tree', { textbookId: textBookId })
  }

  async getChapterTreeOptions(textBookId: any) {
    const res = await this.getChapterTree(textBookId)
    return chapterTree2options(res as any)
  }

  protected findPageUrl(): string {
    return '/xkw/textbook/myTextbooks'
  }

  protected removeUrl(): string {
    throw new Error('Method not implemented.')
  }

  protected saveOrUpdateUrl(): string {
    throw new Error('Method not implemented.')
  }
}

export const schoolBookService = new SchoolBookService()

class XkwQuestionTitleService extends BasicService {
  override async findPage(
    current: number,
    size: number,
    condition: any,
  ): Promise<FindPageResponse> {
    const catalogIds = condition?.catalogIds
    if (!catalogIds || (Array.isArray(catalogIds) && catalogIds.length === 0)) {
      return { current: 1, size: 0, totalPage: 0, totalRows: 0, rows: [] }
    }
    const params = {
      ...condition,
      catalogIds: Array.isArray(catalogIds) ? catalogIds.join(',') : catalogIds,
      current,
      size,
    }
    const data = await get<any>(this.findPageUrl(), params)
    const list = data?.rows ?? data ?? []
    const rows = list.map((item: any) => ({
      ...item,
      title: item.stemHtml || item.stem,
      answer: item.answerHtml || item.answer,
      titleAnalyze: item.explanation,
      options: item.optionHtml || item.optionSqs,
      titleTypeBaseId: item.typeId,
      titleChannelType: item.typeId,
      titleChannelTypeName: item.typeName,
    }))
    if (data?.totalRows !== undefined) {
      return { ...data, rows }
    }
    return {
      current,
      size: rows.length,
      totalPage: 1,
      totalRows: rows.length,
      rows,
    }
  }

  protected findPageUrl(): string {
    return '/xkw/question/title/list'
  }

  protected removeUrl(): string {
    throw new Error('Method not implemented.')
  }

  protected saveOrUpdateUrl(): string {
    throw new Error('Method not implemented.')
  }
}

export const xkwQuestionTitleService = new XkwQuestionTitleService()

export async function saveOrUpdateXkwQuestionTitle(data: any) {
  return await post('/xkw/question/title/saveOrUpdate', data)
}

export async function batchUpdateTypeId(
  data: Array<{ id: string; typeId: string }>,
) {
  return await post('/xkw/question/title/batch/updateTypeId', data)
}

export async function getQuestionTypeList(params?: Record<string, any>) {
  const res = await get<any>('/xkw/questionType/list', params)
  return (res?.rows ?? res ?? []) as any[]
}

const ALLOWED_ORIGINS = [
  'https://admin.xuexiaole.com',
  'https://tiku.qzdyai.com',
  'https://tiku.lingxixue.com',
]
const DEFAULT_ORIGIN = 'https://admin.xuexiaole.com'

export async function getXkwAuthorizeUrl(params: {
  chapterId: any
  courseId: any
  targetPaperId: any
  textbookId: any
}) {
  const origin = ALLOWED_ORIGINS.includes(window.location.origin)
    ? window.location.origin
    : DEFAULT_ORIGIN
  return await post<{ authorizeUrl: string }>('/xkw/oauth/authorize-url', {
    baseUrl: origin,
    ...params,
  })
}
