/**
 * 全景雷达(JRZQ7F1A) 数据拆分工具
 * 将原始的全景雷达报告拆分为申请行为详情、放款还款详情和大数据详情三个独立模块
 * 以便在 BaseReport 中按 Tab 展示
 */

/**
 * 判断数据对象是否有效（非空且包含至少一个键）
 * @param {object} data
 * @returns {boolean}
 */
const EMPTY_STRING_MARKERS = new Set(['-', '--', '0', '0.0', '暂无数据', '无数据', 'null', 'NULL'])

function hasData(data, visited = new WeakSet()) {
  if (data === null || data === undefined) {
    return false
  }

  if (typeof data === 'number') {
    return data !== 0 && !Number.isNaN(data)
  }

  if (typeof data === 'string') {
    const trimmed = data.trim()
    if (!trimmed) return false
    return !EMPTY_STRING_MARKERS.has(trimmed)
  }

  if (typeof data === 'boolean') {
    return data
  }

  if (Array.isArray(data)) {
    if (data.length === 0) return false
    return data.some(item => hasData(item, visited))
  }

  if (typeof data === 'object') {
    if (visited.has(data)) return false
    visited.add(data)
    const values = Object.values(data)
    if (values.length === 0) return false
    return values.some(value => hasData(value, visited))
  }

  return false
}

const createDefaultObject = (fields, defaultValue = '0') =>
  fields.reduce((acc, key) => {
    acc[key] = defaultValue
    return acc
  }, {})

const APPLY_REPORT_FIELDS = [
  'A22160001',
  'A22160002',
  'A22160003',
  'A22160004',
  'A22160005',
  'A22160006',
  'A22160007',
  'A22160008',
  'A22160009',
  'A22160010'
]

const APPLY_REPORT_DEFAULTS = createDefaultObject(APPLY_REPORT_FIELDS)

const BEHAVIOR_REPORT_FIELDS = [
  'B22170001',
  'B22170002',
  'B22170003',
  'B22170004',
  'B22170005',
  'B22170006',
  'B22170007',
  'B22170008',
  'B22170009',
  'B22170010',
  'B22170011',
  'B22170012',
  'B22170013',
  'B22170014',
  'B22170015',
  'B22170016',
  'B22170017',
  'B22170018',
  'B22170019',
  'B22170020',
  'B22170021',
  'B22170022',
  'B22170023',
  'B22170024',
  'B22170025',
  'B22170026',
  'B22170027',
  'B22170028',
  'B22170029',
  'B22170030',
  'B22170031',
  'B22170032',
  'B22170033',
  'B22170034',
  'B22170035',
  'B22170036',
  'B22170037',
  'B22170038',
  'B22170039',
  'B22170040',
  'B22170041',
  'B22170042',
  'B22170043',
  'B22170044',
  'B22170045',
  'B22170046',
  'B22170047',
  'B22170048',
  'B22170049',
  'B22170050',
  'B22170051',
  'B22170052',
  'B22170053',
  'B22170054'
]

const BEHAVIOR_REPORT_DEFAULTS = createDefaultObject(BEHAVIOR_REPORT_FIELDS)

const BIG_DATA_REPORT_FIELDS = [
  'C22180001',
  'C22180002',
  'C22180003',
  'C22180004',
  'C22180005',
  'C22180006',
  'C22180007',
  'C22180008',
  'C22180009',
  'C22180010',
  'C22180011',
  'C22180012'
]

const BIG_DATA_REPORT_DEFAULTS = createDefaultObject(BIG_DATA_REPORT_FIELDS)

const normalizeModuleData = (source, defaults) => {
  const normalized = { ...defaults }
  if (!source || typeof source !== 'object') {
    return normalized
  }

  Object.entries(source).forEach(([key, value]) => {
    if (value === undefined || value === null) {
      return
    }
    normalized[key] = value
  })

  return normalized
}

/**
 * 拆分 JRZQ7F1A 报告数据
 * @param {Array} reportData - 原始报告数据数组
 * @returns {Array} 拆分后的报告数据数组
 */
export function splitJRZQ7F1AForTabs(reportData) {
  const targetIndex = reportData.findIndex(item => item.data?.apiID === 'JRZQ7F1A');
  const target = targetIndex >= 0 ? reportData[targetIndex] : null;

  if (!target || !target.data?.data) {
    return reportData;
  }

  const originalData = target.data.data;
  const baseTimestamp = target.data.timestamp;
  const success = target.data.success ?? true;

  const splitModules = [];

  const pushModule = (suffix, payload, defaults) => {
    splitModules.push({
      data: {
        apiID: `JRZQ7F1A_${suffix}`,
        data: normalizeModuleData(payload, defaults),
        success,
        timestamp: baseTimestamp,
      }
    });
  };

  pushModule('ApplyReport', originalData.apply_report_detail, APPLY_REPORT_DEFAULTS);
  pushModule('BehaviorReport', originalData.behavior_report_detail, BEHAVIOR_REPORT_DEFAULTS);
  pushModule('BigDataReport', originalData.current_report_detail, BIG_DATA_REPORT_DEFAULTS);

  // 未能拆出子模块则直接返回原数据
  if (splitModules.length === 0) {
    return reportData;
  }

  const result = [...reportData];
  result.splice(targetIndex, 1, ...splitModules);

  return result;
}

