import type { AIQuestionBlock, AITemplateResults } from '../ai-types'
import type { AnswerSheetData, KonvaMarkingData, MarkingItem } from '../types'

/**
 * 原始 API 返回的主观题答案数据
 */
interface SubjectiveAnswerData {
  question_id?: number | string
  question_major?: number | string
  question_minor?: number | string
  final_score?: number
  full_score?: number
  teacher_name?: string
  remark?: any // 可能是字符串或对象
}

/**
 * 验证标记数据格式
 */
function validateMarkingData(data: any): data is KonvaMarkingData {
  return (
    data
    && typeof data === 'object'
    && Array.isArray(data.shapes)
    && Array.isArray(data.specialMarks)
    && Array.isArray(data.annotations)
  )
}

/**
 * 数据解析器 - 将 API 数据转换为组件需要的格式
 */
export function useDataParser() {
  /**
   * 解析标记数据（从 remark 字段）
   */
  const parseMarkingData = (remark: any): KonvaMarkingData | null => {
    if (!remark)
      return null

    try {
      // 如果是字符串，尝试解析
      if (typeof remark === 'string') {
        const parsed = JSON.parse(remark)
        return validateMarkingData(parsed) ? parsed : null
      }

      // 如果已经是对象，验证格式
      if (typeof remark === 'object' && validateMarkingData(remark)) {
        return remark
      }

      // 如果是数组，尝试从第一个元素获取
      if (Array.isArray(remark) && remark.length > 0) {
        const firstItem = remark[0]
        if (validateMarkingData(firstItem)) {
          return firstItem
        }
      }

      return null
    }
    catch (error) {
      console.error('解析标记数据失败:', error)
      return null
    }
  }

  /**
   * 创建空的标记数据
   */
  const createEmptyMarkingData = (): KonvaMarkingData => ({
    version: '1.0',
    shapes: [],
    specialMarks: [],
    annotations: [],
  })

  /**
   * 解析区域位置字符串 "x,y,w,h"
   */
  const parseAreaPos = (areaPos: string): [number, number, number, number] => {
    const parts = areaPos.split(',').map(Number)
    if (parts.length !== 4 || parts.some(Number.isNaN)) {
      console.warn('无效的区域位置格式:', areaPos)
      return [0, 0, 0, 0]
    }
    return parts as [number, number, number, number]
  }

  /**
   * 将 API 数据转换为答题卡数据
   */
  const parseAnswerSheetData = (apiData: any): AnswerSheetData | null => {
    if (!apiData)
      return null

    try {
      // 解析 raw_info 获取题目区块信息
      let questionBlocks: AIQuestionBlock[] = []
      if (apiData.raw_info) {
        const rawInfo = JSON.parse(apiData.raw_info)
        // 处理多种可能的数据结构
        let aiData: AITemplateResults | null = null

        if (rawInfo.results && Array.isArray(rawInfo.results)) {
          // 格式: {"message":"OK","results":[{...}]}
          aiData = rawInfo.results[0] as AITemplateResults
        }
        else if (rawInfo.aiData) {
          aiData = rawInfo.aiData as AITemplateResults
        }
        else if (rawInfo.ai_data) {
          aiData = rawInfo.ai_data as AITemplateResults
        }
        else {
          aiData = rawInfo as AITemplateResults
        }

        console.log('[useDataParser] aiData:', aiData)
        questionBlocks = aiData?.data?.question_block || []
        console.log('[useDataParser] questionBlocks:', questionBlocks)
      }

      // 创建题目ID到区块的映射
      const questionBlockMap = new Map<string, AIQuestionBlock>()
      questionBlocks.forEach((block) => {
        // 优先使用 question_major-question_minor 作为 key，因为 question_id 可能不存在
        const majorMinorKey = `${block.question_major}-${block.question_minor}`
        questionBlockMap.set(majorMinorKey, block)

        // 如果有 question_number，也添加一个映射
        if (block.question_number) {
          questionBlockMap.set(block.question_number, block)
        }

        // 如果有 question_id，也添加一个映射
        if (block.question_id) {
          questionBlockMap.set(block.question_id.toString(), block)
        }
      })

      console.log('[useDataParser] questionBlockMap keys:', Array.from(questionBlockMap.keys()))

      // 解析标记列表
      console.log('[useDataParser] subjective_answer:', apiData.subjective_answer)

      const markings: MarkingItem[] = (apiData.subjective_answer || [])
        .map((item: SubjectiveAnswerData): MarkingItem | null => {
          // 优先使用 major-minor 匹配，因为 API 数据中的 question_block 可能没有 question_id
          const majorMinorKey = `${item.question_major}-${item.question_minor}`
          let questionBlock = questionBlockMap.get(majorMinorKey)

          // 如果没找到，尝试用 question_id 匹配
          if (!questionBlock && item.question_id) {
            questionBlock = questionBlockMap.get(item.question_id.toString())
          }

          if (!questionBlock) {
            console.warn('[useDataParser] 未找到题目区块信息:', {
              question_id: item.question_id,
              major: item.question_major,
              minor: item.question_minor,
              majorMinorKey,
              availableKeys: Array.from(questionBlockMap.keys()),
            })
            return null
          }

          console.log('[useDataParser] 匹配成功:', majorMinorKey, questionBlock)

          // 解析标记数据
          let markingData = parseMarkingData(item.remark)
          if (!markingData) {
            markingData = createEmptyMarkingData()
          }

          return {
            questionId: item.question_id?.toString() || majorMinorKey,
            questionMajor: Number(item.question_major || 0),
            questionMinor: Number(item.question_minor || 0),
            imageIndex: questionBlock.image_index,
            areaPos: parseAreaPos(questionBlock.area_pos),
            score: item.final_score || 0,
            fullScore: item.full_score || 0,
            teacherName: item.teacher_name,
            markingData,
          }
        })
        .filter((item): item is MarkingItem => item !== null)

      const result = {
        studentInfo: {
          studentName: apiData.student_name || '',
          examNumber: apiData.student_exam_number || '',
          objectiveScore: apiData.objective_score || 0,
          subjectiveScore: apiData.subjective_score || 0,
          totalScore: apiData.all_score || 0,
          fullScore: apiData.full_score || 0,
        },
        answerSheetImages: apiData.answer_sheet_images || [],
        markings,
      }

      console.log('[useDataParser] 解析结果:', result)
      return result
    }
    catch (error) {
      console.error('解析答题卡数据失败:', error)
      return null
    }
  }

  return {
    parseAnswerSheetData,
    parseMarkingData,
    validateMarkingData,
    createEmptyMarkingData,
  }
}
