/**
 * 解析多头借贷数据
 * @param {Array} riskInfo - riskInfo_report_v3.1 数组
 * @returns {Object} 解析后的结构化数据
 */
export function parseRiskData(riskInfo) {
  if (!Array.isArray(riskInfo)) {
    return {}
  }

  // 创建 riskCode 到 riskCodeValue 的映射
  const riskMap = {}
  riskInfo.forEach(item => {
    const code = String(item.riskCode)
    const value = item.riskCodeValue
    riskMap[code] = value
  })

  const result = {
    // 多头共债子分
    multipleDebtScore: {
      general: parseValue(riskMap['41001']), // 多头申请通用分
      shortCycle: parseValue(riskMap['41002']), // 短周期多头共债子分
      longCycle: parseValue(riskMap['41003']), // 长周期多头共债子分
      nonBank: parseValue(riskMap['41004']), // 非银行多头共债子分
      bank: parseValue(riskMap['41005']), // 银行多头共债子分
    },

    // 多头申请
    multipleApplication: parseMultipleApplication(riskMap),

    // 多头逾期
    multipleOverdue: parseMultipleOverdue(riskMap),

    // 圈团风险
    circleRisk: {
      riskScore1: parseValue(riskMap['21007']), // 圈团1浓度分V2
      riskLevel2: parseValue(riskMap['22006']), // 圈团2风险等级V1
      riskScore3: parseValue(riskMap['23006']), // 圈团3浓度分V1
    },

    // 可疑欺诈风险
    fraudRisk: {
      riskLevel1: parseValue(riskMap['31006']), // 疑似准入风险V1
      riskLevel2: parseValue(riskMap['310018']), // 疑似准入风险V2
    },

    // 查询天数差
    queryDays: {
      earliestQueryDays: parseValue(riskMap['40189']), // 最早一次查询距今的天数
      latestQueryDays: parseValue(riskMap['40190']), // 最近一次查询距今的天数
      earliestBankDays: parseValue(riskMap['40191']), // 最早一次在银行机构距今的天数
      latestBankDays: parseValue(riskMap['40192']), // 最近一次在银行机构距今的天数
      earliestNonBankDays: parseValue(riskMap['40193']), // 最早一次在非银机构距今的天数
      latestNonBankDays: parseValue(riskMap['40194']), // 最近一次在非银机构距今的天数
    },
  }

  return result
}

/**
 * 解析多头申请数据
 */
function parseMultipleApplication(riskMap) {
  const periods = ['7d', '15d', '30d', '60d', '90d', '180d', '360d', '720d']
  const periodMap = {
    '7d': 0,
    '15d': 1,
    '30d': 2,
    '60d': 3,
    '90d': 4,
    '180d': 5,
    '360d': 6,
    '720d': 7,
  }

  const industries = ['total', 'bank', 'licensedConsumer', 'fintech', 'tech', 'other']
  const industryMap = {
    total: 0,
    bank: 1,
    licensedConsumer: 2,
    fintech: 3,
    tech: 4,
    other: 5,
  }

  // 行业次数 (40001-40048)
  const applicationCounts = {}
  periods.forEach((period, pIdx) => {
    applicationCounts[period] = {}
    industries.forEach((industry, iIdx) => {
      const code = 40001 + pIdx * 6 + iIdx
      applicationCounts[period][industry] = parseValue(riskMap[String(code)])
    })
  })

  // 行业平台数 (40049-40096)
  const platformCounts = {}
  periods.forEach((period, pIdx) => {
    platformCounts[period] = {}
    industries.forEach((industry, iIdx) => {
      const code = 40049 + pIdx * 6 + iIdx
      platformCounts[period][industry] = parseValue(riskMap[String(code)])
    })
  })

  // 总白天/凌晨申请数 (40097-40112)
  const dayNightCounts = {
    day: {},
    night: {},
  }
  periods.forEach((period, pIdx) => {
    dayNightCounts.day[period] = parseValue(riskMap[String(40097 + pIdx)])
    dayNightCounts.night[period] = parseValue(riskMap[String(40105 + pIdx)])
  })

  // 银行白天/凌晨申请数 (40113-40128)
  const bankDayNightCounts = {
    day: {},
    night: {},
  }
  periods.forEach((period, pIdx) => {
    bankDayNightCounts.day[period] = parseValue(riskMap[String(40113 + pIdx)])
    bankDayNightCounts.night[period] = parseValue(riskMap[String(40121 + pIdx)])
  })

  // 总白天/凌晨申请平台数 (40129-40144)
  const dayNightPlatforms = {
    day: {},
    night: {},
  }
  periods.forEach((period, pIdx) => {
    dayNightPlatforms.day[period] = parseValue(riskMap[String(40129 + pIdx)])
    dayNightPlatforms.night[period] = parseValue(riskMap[String(40137 + pIdx)])
  })

  // 银行白天/凌晨申请平台数 (40145-40160)
  const bankDayNightPlatforms = {
    day: {},
    night: {},
  }
  periods.forEach((period, pIdx) => {
    bankDayNightPlatforms.day[period] = parseValue(riskMap[String(40145 + pIdx)])
    bankDayNightPlatforms.night[period] = parseValue(riskMap[String(40153 + pIdx)])
  })

  // 新增总平台数 (40161-40174)
  const newTotalPlatforms = {
    '7d_vs_30d': parseValue(riskMap['40161']),
    '7d_vs_90d': parseValue(riskMap['40162']),
    '7d_vs_180d': parseValue(riskMap['40163']),
    '7d_vs_360d': parseValue(riskMap['40164']),
    '7d_vs_720d': parseValue(riskMap['40165']),
    '15d_vs_30d': parseValue(riskMap['40166']),
    '15d_vs_90d': parseValue(riskMap['40167']),
    '15d_vs_180d': parseValue(riskMap['40168']),
    '15d_vs_360d': parseValue(riskMap['40169']),
    '15d_vs_720d': parseValue(riskMap['40170']),
    '30d_vs_90d': parseValue(riskMap['40171']),
    '30d_vs_180d': parseValue(riskMap['40172']),
    '30d_vs_360d': parseValue(riskMap['40173']),
    '30d_vs_720d': parseValue(riskMap['40174']),
  }

  // 新增银行总平台数 (40175-40188)
  const newBankPlatforms = {
    '7d_vs_30d': parseValue(riskMap['40175']),
    '7d_vs_90d': parseValue(riskMap['40176']),
    '7d_vs_180d': parseValue(riskMap['40177']),
    '7d_vs_360d': parseValue(riskMap['40178']),
    '7d_vs_720d': parseValue(riskMap['40179']),
    '15d_vs_30d': parseValue(riskMap['40180']),
    '15d_vs_90d': parseValue(riskMap['40181']),
    '15d_vs_180d': parseValue(riskMap['40182']),
    '15d_vs_360d': parseValue(riskMap['40183']),
    '15d_vs_720d': parseValue(riskMap['40184']),
    '30d_vs_90d': parseValue(riskMap['40185']),
    '30d_vs_180d': parseValue(riskMap['40186']),
    '30d_vs_360d': parseValue(riskMap['40187']),
    '30d_vs_720d': parseValue(riskMap['40188']),
  }

  return {
    applicationCounts,
    platformCounts,
    dayNightCounts,
    bankDayNightCounts,
    dayNightPlatforms,
    bankDayNightPlatforms,
    newTotalPlatforms,
    newBankPlatforms,
    totalApplications: applicationCounts,
  }
}

/**
 * 解析多头逾期数据
 */
function parseMultipleOverdue(riskMap) {
  const periods = ['1week', '1month', '3month', '6month', '12month', 'over1year']
  const periodCodeMap = {
    '1week': { platform: 17001, count: 17101 },
    '1month': { platform: 17002, count: 17102 },
    '3month': { platform: 17003, count: 17103 },
    '6month': { platform: 17004, count: 17104 },
    '12month': { platform: 17005, count: 17105 },
    'over1year': { platform: 17006, count: 17106 },
  }

  const industries = ['total', 'bank', 'insurance', 'securities', 'trust', 'assetManagement', 'licensedConsumer', 'fintech', 'loanSupermarket', 'dataRisk', 'other']
  const industryCodeMap = {
    total: 0,
    bank: 1,
    insurance: 2,
    securities: 3,
    trust: 4,
    assetManagement: 5,
    licensedConsumer: 6,
    fintech: 7,
    loanSupermarket: 8,
    dataRisk: 9,
    other: 10,
  }

  const overduePlatforms = {}
  const overdueCounts = {}

  periods.forEach(period => {
    const { platform: basePlatformCode, count: baseCountCode } = periodCodeMap[period]
    
    overduePlatforms[period] = {}
    overdueCounts[period] = {}

    industries.forEach(industry => {
      const codeOffset = industryCodeMap[industry]

      // 处理特殊的 code 格式
      // 总计用基础code，其他行业用 baseCode * 10 + offset
      let finalPlatformCode, finalCountCode
      if (codeOffset === 0) {
        finalPlatformCode = basePlatformCode
        finalCountCode = baseCountCode
      } else {
        // 如 170011 = 17001 * 10 + 1
        finalPlatformCode = basePlatformCode * 10 + codeOffset
        finalCountCode = baseCountCode * 10 + codeOffset
      }

      overduePlatforms[period][industry] = parseValue(riskMap[String(finalPlatformCode)])
      overdueCounts[period][industry] = parseValue(riskMap[String(finalCountCode)])
    })
  })

  return {
    overduePlatforms,
    overdueCounts,
  }
}

/**
 * 解析数值（处理字符串和数字）
 */
function parseValue(value) {
  if (value === undefined || value === null || value === '') {
    return 0
  }
  const num = Number(value)
  return isNaN(num) ? 0 : num
}

