/**
 * CQYGL3F8E企业关联数据拆分工具
 * 将企业关联数据拆分为投资企业记录、高管任职记录和涉诉风险三个独立模块
 */

/**
 * 拆分CQYGL3F8E数据为多个独立的tab模块
 * @param {Array} reportData - 报告数据数组
 * @returns {Array} 拆分后的数据数组
 */
export function splitCQYGL3F8EForTabs(reportData) {
    const result = []

    reportData.forEach(item => {
        if (item.data?.apiID === 'QYGL3F8E') {
            // 将QYGL3F8E拆分成多个独立的tab
            const qyglData = item.data.data
            const baseTimestamp = item.data.timestamp

            // 投资类关系
            const investRelations = ["sh", "his_sh", "lp", "his_lp"]

            // 高管类关系
            const managerRelations = ["tm", "his_tm"]

            // 获取投资企业记录（股东、历史股东、法人、历史法人）
            const investCompanies = (qyglData?.items || []).filter((item) => {
                const relationships = item?.relationship || []
                return relationships.some((r) => investRelations.includes(r))
            })

            // 获取高管任职记录（高管、历史高管）
            const managerPositions = (qyglData?.items || []).filter((item) => {
                const relationships = item?.relationship || []
                return relationships.some((r) => managerRelations.includes(r))
            })

            // 获取有涉诉风险的企业
            const lawsuitCompanies = (qyglData?.items || []).filter((item) => {
                const lawsuit = item?.lawsuitInfo || {}
                return (
                    (lawsuit.entout && lawsuit.entout.data && Object.keys(lawsuit.entout.data).length > 0) ||
                    (lawsuit.sxbzxr && lawsuit.sxbzxr.data && lawsuit.sxbzxr.data.sxbzxr && lawsuit.sxbzxr.data.sxbzxr.length > 0) ||
                    (lawsuit.xgbzxr && lawsuit.xgbzxr.data && lawsuit.xgbzxr.data.xgbzxr && lawsuit.xgbzxr.data.xgbzxr.length > 0)
                )
            })

            // 1. 投资企业记录模块
            result.push({
                data: {
                    apiID: 'CQYGL3F8E_Investment',
                    data: investCompanies,
                    success: true,
                    timestamp: baseTimestamp
                }
            })

            // 2. 高管任职记录模块
            result.push({
                data: {
                    apiID: 'CQYGL3F8E_SeniorExecutive',
                    data: managerPositions,
                    success: true,
                    timestamp: baseTimestamp
                }
            })
            // 3. 涉诉风险模块
            result.push({
                data: {
                    apiID: 'CQYGL3F8E_Lawsuit',
                    data: {
                        lawsuitCompanies: lawsuitCompanies,
                        totalCompanies: qyglData?.items?.length || 0
                    },
                    success: true,
                    timestamp: baseTimestamp
                }
            })
      // 4. 对外投资历史模块 - 从所有企业中收集投资历史
      const allInvestHistory = []
      qyglData?.items?.forEach(company => {
        if (company.invest_history?.items) {
          company.invest_history.items.forEach(investment => {
            allInvestHistory.push({
              ...investment,
              companyName: company.orgName, // 添加企业名称
              companyInfo: {
                orgName: company.orgName,
                relationship: company.relationship,
                basicInfo: company.basicInfo
              }
            })
          })
        }
      })
      result.push({
        data: {
          apiID: 'CQYGL3F8E_InvestHistory',
          data: { items: allInvestHistory, total: allInvestHistory.length },
          success: true,
          timestamp: baseTimestamp
        }
      })
      
      // 5. 融资历史模块 - 从所有企业中收集融资历史
      const allFinancingHistory = []
      qyglData?.items?.forEach(company => {
        if (company.financing_history?.items) {
          company.financing_history.items.forEach(financing => {
            allFinancingHistory.push({
              ...financing,
              companyName: company.orgName, // 添加企业名称
              companyInfo: {
                orgName: company.orgName,
                relationship: company.relationship,
                basicInfo: company.basicInfo
              }
            })
          })
        }
      })
      result.push({ 
        data: {
          apiID: 'CQYGL3F8E_FinancingHistory',
          data: { items: allFinancingHistory, total: allFinancingHistory.length },
          success: true,
          timestamp: baseTimestamp
        }
      })
      
      // 6. 行政处罚模块 - 从所有企业中收集行政处罚
      const allPunishmentInfo = []
      qyglData?.items?.forEach(company => {
        if (company.punishment_info?.items) {
          company.punishment_info.items.forEach(punishment => {
            allPunishmentInfo.push({
              ...punishment,
              companyName: company.orgName, // 添加企业名称
              companyInfo: {
                orgName: company.orgName,
                relationship: company.relationship,
                basicInfo: company.basicInfo
              }
            })
          })
        }
      })
      result.push({
        data: {
          apiID: 'CQYGL3F8E_Punishment',
          data: { items: allPunishmentInfo, total: allPunishmentInfo.length },
          success: true,
          timestamp: baseTimestamp
        }
      })
      
      // 7. 经营异常模块 - 从所有企业中收集经营异常
      const allAbnormalInfo = []
      qyglData?.items?.forEach(company => {
        if (company.abnormal_info?.items) {
          company.abnormal_info.items.forEach(abnormal => {
            allAbnormalInfo.push({
              ...abnormal,
              companyName: company.orgName, // 添加企业名称
              companyInfo: {
                orgName: company.orgName,
                relationship: company.relationship,
                basicInfo: company.basicInfo
              }
            })
          })
        }
      })
      result.push({
        data: {
          apiID: 'CQYGL3F8E_Abnormal',
          data: { items: allAbnormalInfo, total: allAbnormalInfo.length },
          success: true,
          timestamp: baseTimestamp
        }
      })
      
      // 8. 税务风险模块 - 包含欠税公告和税收违法
      const taxRiskCompanies = (qyglData?.items || []).filter((item) => {
        const ownTax = item?.own_tax || {};
        const taxContravention = item?.tax_contravention || {};
        return (ownTax.total > 0 && ownTax.items && ownTax.items.length > 0) ||
               (taxContravention.total > 0 && taxContravention.items && taxContravention.items.length > 0);
      });
      
      result.push({
        data: {
          apiID: 'CQYGL3F8E_TaxRisk',
          data: { items: taxRiskCompanies },
          success: true,
          timestamp: baseTimestamp
        }
      })

        } else {
            // 其他数据直接添加
            result.push(item)
        }
    })

    return result
}

/**
 * 获取关系文本描述
 * @param {string} relation - 关系代码
 * @returns {string} 关系文本
 */
export function getRelationshipText(relation) {
    const relationshipMap = {
        sh: '股东',
        his_sh: '曾任股东',
        lp: '法人',
        his_lp: '曾任法人',
        tm: '高管',
        his_tm: '曾任高管'
    }
    return relationshipMap[relation] || relation
}

/**
 * 获取关系样式类
 * @param {string} relation - 关系代码
 * @returns {string} 样式类名
 */
export function getRelationshipClass(relation) {
    const relationshipMap = {
        sh: 'bg-blue-100 text-blue-700',
        his_sh: 'bg-blue-50 text-blue-600',
        lp: 'bg-green-100 text-green-700',
        his_lp: 'bg-green-50 text-green-600',
        tm: 'bg-purple-100 text-purple-700',
        his_tm: 'bg-purple-50 text-purple-600'
    }
    return relationshipMap[relation] || 'bg-gray-100 text-gray-600'
}

/**
 * 获取企业状态对应的样式类
 * @param {string} status - 企业状态
 * @returns {string} 样式类名
 */
export function getStatusClass(status) {
    if (!status) return 'bg-gray-100 text-gray-500'

    if (status.includes('注销') || status.includes('吊销')) {
        return 'bg-red-50 text-red-600'
    } else if (status.includes('存续') || status.includes('在营')) {
        return 'bg-green-50 text-green-600'
    } else if (status.includes('筹建') || status.includes('新设')) {
        return 'bg-blue-50 text-blue-600'
    } else {
        return 'bg-yellow-50 text-yellow-600'
    }
}

/**
 * 格式化资本金额显示
 * @param {string|number} capital - 资本金额
 * @param {string} currency - 货币类型
 * @returns {string} 格式化后的金额
 */
export function formatCapital(capital, currency) {
    if (!capital) return '—'

    let unit = ''
    let value = parseFloat(capital)

    // 处理原始数据中可能带有的单位
    if (typeof capital === 'string' && capital.includes('万')) {
        unit = '万'
        const numMatch = capital.match(/[\d.]+/)
        value = numMatch ? parseFloat(numMatch[0]) : 0
    } else if (value >= 10000) {
        // 大额数字转换为万元显示
        value = value / 10000
        unit = '万'
    }

    // 格式化数字，保留两位小数（如果有小数部分）
    const formattedValue = value.toLocaleString('zh-CN', {
        minimumFractionDigits: 0,
        maximumFractionDigits: 2,
    })

    return `${formattedValue}${unit} ${currency || '人民币'}`
}

/**
 * 格式化日期显示
 * @param {string} dateStr - 日期字符串
 * @returns {string} 格式化后的日期
 */
export function formatDate(dateStr) {
    if (!dateStr) return '—'
    return dateStr
}
