const VALUE_OPPORTUNITY_QUERY_KEY = 'value_opportunity'
const OPPORTUNITY_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu

const DIMENSION_LINKS = [
  { key: 'departmentId', dimensionKey: 'department_id', queryKey: 'value_department_id', label: '部门' },
  { key: 'projectCode', dimensionKey: 'project_code', queryKey: 'value_project_code', label: '项目' },
  { key: 'expenseType', dimensionKey: 'expense_type', queryKey: 'value_expense_type', label: '费用类型' },
  { key: 'supplierId', dimensionKey: 'supplier_id', queryKey: 'value_supplier_id', label: '供应商' },
  { key: 'city', dimensionKey: 'city', queryKey: 'value_city', label: '城市' }
]

export const BUDGET_CONFIGURATION_NOTICE = '预算配置视图只用于核对预算规则、范围与阈值，不代表当前节省机会的真实预算金额。'

export function normalizeValueOpportunityId(value) {
  const raw = Array.isArray(value) ? value[0] : value
  const normalized = String(raw || '').trim()
  return OPPORTUNITY_ID_PATTERN.test(normalized) ? normalized : ''
}

export function readValueOpportunityId(query = {}) {
  return normalizeValueOpportunityId(query[VALUE_OPPORTUNITY_QUERY_KEY])
}

export function hasValueOpportunityQuery(query = {}) {
  return Object.hasOwn(query, VALUE_OPPORTUNITY_QUERY_KEY)
}

export function writeValueOpportunityToQuery(query = {}, opportunityId = '') {
  const result = { ...query }
  const normalized = normalizeValueOpportunityId(opportunityId)
  if (normalized) result[VALUE_OPPORTUNITY_QUERY_KEY] = normalized
  else delete result[VALUE_OPPORTUNITY_QUERY_KEY]
  return result
}

export function shouldClearValueOpportunityError(error) {
  return [403, 404].includes(Number(error?.status || 0))
}

export function opportunityMatchesValueContext(opportunity, filters = {}, window = {}) {
  if (!opportunity || typeof opportunity !== 'object') return false
  const dimensions = opportunity.dimensionJson || {}
  const comparisons = [
    [filters.departmentId, dimensions.department_id],
    [filters.projectCode, dimensions.project_code],
    [filters.expenseType, dimensions.expense_type],
    [filters.supplierId, dimensions.supplier_id],
    [filters.city, dimensions.city],
    [filters.ownerId, opportunity.ownerId],
    [filters.sourceType, opportunity.sourceType],
    [filters.valueKind, opportunity.valueKind],
    [filters.status, opportunity.status]
  ]
  if (comparisons.some(([expected, actual]) => expected && !sameFilterValue(expected, actual))) {
    return false
  }

  const createdAt = new Date(opportunity.createdAt || '').getTime()
  const start = window.start ? new Date(window.start).getTime() : Number.NaN
  const end = window.end ? new Date(window.end).getTime() : Number.NaN
  if ((Number.isFinite(start) || Number.isFinite(end)) && !Number.isFinite(createdAt)) return false
  if (Number.isFinite(start) && createdAt < start) return false
  if (Number.isFinite(end) && createdAt > end) return false
  return true
}

export function buildCfoOpportunitySourceLinks(opportunity = {}, options = {}) {
  const dimensions = opportunity.dimensionJson || {}
  const evidence = collectEvidence(opportunity)
  const riskResource = evidence.find((item) => isRiskResource(item.resourceType))
  const claimResource = evidence.find((item) => isClaimResource(item.resourceType))
  const claimId = safeRouteValue(opportunity.claimId || claimResource?.resourceId)
  const expenseCaseId = safeRouteValue(opportunity.expenseCaseId)
  const aiDecisionId = safeRouteValue(opportunity.aiDecisionId)
  const riskObservationId = safeRouteValue(
    riskResource?.resourceId || (isRiskSource(opportunity) ? opportunity.sourceId : '')
  )
  const returnQuery = buildValueDashboardReturnQuery(options.dashboardQuery, { includeOpportunity: true })
  const links = []

  if (claimId) {
    const riskFocused = Boolean(riskObservationId || isRiskSource(opportunity))
    links.push({
      key: riskFocused ? 'risk-claim' : 'claim',
      kind: 'document',
      label: riskFocused ? '查看风险来源单据' : '查看关联单据',
      description: buildClaimDescription(opportunity, expenseCaseId, riskFocused),
      icon: riskFocused ? 'mdi mdi-shield-search-outline' : 'mdi mdi-file-search-outline',
      to: {
        name: 'app-document-detail',
        params: { requestId: claimId },
        query: compactQuery({
          ...returnQuery,
          returnTo: 'value',
          ...(expenseCaseId ? { expense_case_id: expenseCaseId } : {}),
          ...(riskFocused ? { focus: 'risk' } : {}),
          ...(riskObservationId ? { risk_observation_id: riskObservationId } : {}),
          ...(aiDecisionId ? { ai_decision_id: aiDecisionId } : {})
        }),
        ...(riskFocused ? { hash: '#risk-observation-active-detail' } : {})
      }
    })
  }

  const departmentId = safeRouteValue(dimensions.department_id)
  const departmentName = safeRouteValue(dimensions.department_name)
  const expenseType = safeRouteValue(dimensions.expense_type)
  if (departmentId || departmentName || expenseType) {
    links.push({
      key: 'budget-configuration',
      kind: 'budget',
      label: '查看预算配置视图',
      description: BUDGET_CONFIGURATION_NOTICE,
      icon: 'mdi mdi-wallet-outline',
      to: {
        name: 'app-budget',
        query: compactQuery({
          budget_view: 'configuration',
          budget_department_id: departmentId,
          budget_department_name: departmentName,
          budget_expense_type: expenseType
        })
      }
    })
  }

  links.push(...buildDimensionLinks(opportunity, options.dashboardQuery))
  return links
}

export function readBudgetConfigurationFocus(query = {}) {
  const view = readQueryValue(query.budget_view)
  return {
    active: view === 'configuration',
    departmentId: readQueryValue(query.budget_department_id),
    departmentName: readQueryValue(query.budget_department_name),
    expenseType: readQueryValue(query.budget_expense_type)
  }
}

function buildDimensionLinks(opportunity, dashboardQuery = {}) {
  const dimensions = opportunity.dimensionJson || {}
  const baseQuery = buildValueDashboardReturnQuery(dashboardQuery, { includeOpportunity: false })
  delete baseQuery.value_page
  const links = DIMENSION_LINKS.flatMap((definition) => {
    const value = safeRouteValue(dimensions[definition.dimensionKey])
    if (!value) return []
    return [{
      key: `dimension-${definition.key}`,
      kind: 'dimension',
      label: `按${definition.label}查看 CFO 分析`,
      description: `返回经营价值看板，并筛选${definition.label}“${value}”。`,
      icon: 'mdi mdi-chart-box-outline',
      to: {
        name: 'app-overview',
        query: { ...baseQuery, [definition.queryKey]: value }
      }
    }]
  })

  const ownerId = safeRouteValue(opportunity.ownerId)
  if (ownerId) {
    links.push(buildTopLevelDimensionLink('owner', '负责人', 'value_owner_id', ownerId, baseQuery))
  }
  const sourceType = safeRouteValue(opportunity.sourceType)
  if (sourceType) {
    links.push(buildTopLevelDimensionLink('source', '来源', 'value_source_type', sourceType, baseQuery))
  }
  return links
}

function buildTopLevelDimensionLink(key, label, queryKey, value, baseQuery) {
  return {
    key: `dimension-${key}`,
    kind: 'dimension',
    label: `按${label}查看 CFO 分析`,
    description: `返回经营价值看板，并筛选${label}“${value}”。`,
    icon: 'mdi mdi-chart-box-outline',
    to: { name: 'app-overview', query: { ...baseQuery, [queryKey]: value } }
  }
}

function buildValueDashboardReturnQuery(query = {}, { includeOpportunity } = {}) {
  const result = {}
  Object.entries(query || {}).forEach(([key, value]) => {
    const isOverviewWindow = ['range', 'start', 'end'].includes(key)
    const isValueQuery = key.startsWith('value_')
    if (isOverviewWindow || (isValueQuery && (includeOpportunity || key !== VALUE_OPPORTUNITY_QUERY_KEY))) {
      result[key] = value
    }
  })
  result.dashboard = 'value'
  return result
}

function buildClaimDescription(opportunity, expenseCaseId, riskFocused) {
  const claimLabel = safeRouteValue(opportunity.claimNoSnapshot || opportunity.claimId) || '关联单据'
  const caseSuffix = expenseCaseId ? `，费用案件 ${expenseCaseId}` : ''
  return riskFocused
    ? `打开 ${claimLabel} 的风险证据位置${caseSuffix}。`
    : `打开 ${claimLabel} 核对业务来源${caseSuffix}。`
}

function collectEvidence(opportunity = {}) {
  const rows = [
    ...(Array.isArray(opportunity.evidence) ? opportunity.evidence : []),
    ...(Array.isArray(opportunity.evidenceJson) ? opportunity.evidenceJson : [])
  ]
  return rows.map((item) => ({
    resourceType: String(item?.resourceType || item?.resource_type || '').trim(),
    resourceId: String(item?.resourceId || item?.resource_id || '').trim()
  }))
}

function isRiskResource(value) {
  return /risk|observation/iu.test(String(value || ''))
}

function isClaimResource(value) {
  return /^(expense_)?claim$|reimbursement|application_document/iu.test(String(value || ''))
}

function isRiskSource(opportunity = {}) {
  return /risk|observation/iu.test(`${opportunity.sourceType || ''} ${opportunity.category || ''}`)
}

function sameFilterValue(left, right) {
  return String(left || '').trim().toLocaleLowerCase('zh-CN') === String(right || '').trim().toLocaleLowerCase('zh-CN')
}

function safeRouteValue(value) {
  const normalized = String(value || '').trim()
  return normalized && normalized.length <= 160 ? normalized : ''
}

function readQueryValue(value) {
  return safeRouteValue(Array.isArray(value) ? value[0] : value)
}

function compactQuery(query = {}) {
  return Object.fromEntries(Object.entries(query).filter(([, value]) => value !== '' && value !== undefined && value !== null))
}
