import cache from '@/plugins/cache'

export const TASK_STORAGE_KEY = 'project-task-dispatch-records-v1'
export const REPORT_STORAGE_KEY = 'project-report-generation-records-v1'

export const MATERIAL_REQUIREMENTS = [
  {
    category: '行业资料',
    materialType: '1',
    files: ['行业研究_2026Q1.pdf', '行业竞争分析.pdf', '区域市场容量评估.docx', '行业政策汇编.pdf', '行业风险清单.xlsx']
  },
  {
    category: '财务资料',
    materialType: '2',
    files: ['财务报表.xlsx', '现金流预测.xlsx', '应收账款明细.xlsx', '预算执行说明.docx']
  },
  {
    category: '法务资料',
    materialType: '3',
    files: ['法务合规.docx', '主体资质文件.pdf', '合同补充协议.pdf', '诉讼仲裁说明.docx']
  },
  {
    category: '担保品资料',
    materialType: '4',
    files: ['担保品清单.pdf', '抵押登记文件.pdf', '估值复核说明.docx']
  },
  {
    category: '其他资料',
    materialType: '1',
    files: ['管理层访谈纪要.docx', '风控补充材料.zip']
  }
]

export const SCORE_ITEMS = [
  { key: 'industry', label: '行业风险控制' },
  { key: 'enterprise', label: '企业风险控制' },
  { key: 'team', label: '管理团队风险控制' },
  { key: 'market', label: '市场风险控制' },
  { key: 'law', label: '政策与法律风险控制' },
  { key: 'guarantee', label: '担保品风险控制' }
]

export const REPORT_TEMPLATE_OPTIONS = [
  '内部模板_v1.0',
  '尽调模板_v2.1',
  '风控模板_季度版'
]

const SCORE_MATCHERS = [
  { keywords: ['行业'], label: '行业风险控制' },
  { keywords: ['财务', '企业'], label: '企业风险控制' },
  { keywords: ['管理团队', '访谈', '治理'], label: '管理团队风险控制' },
  { keywords: ['市场'], label: '市场风险控制' },
  { keywords: ['法务', '法律', '政策'], label: '政策与法律风险控制' },
  { keywords: ['担保'], label: '担保品风险控制' }
]

export function normalizeDate(value) {
  if (!value) {
    return ''
  }
  return `${value}`.slice(0, 10).replace(/\//g, '-')
}

export function nowString() {
  const now = new Date()
  const year = now.getFullYear()
  const month = `${now.getMonth() + 1}`.padStart(2, '0')
  const day = `${now.getDate()}`.padStart(2, '0')
  const hours = `${now.getHours()}`.padStart(2, '0')
  const minutes = `${now.getMinutes()}`.padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

export function todayString() {
  return nowString().slice(0, 10)
}

export function readTaskStore() {
  return cache.local.getJSON(TASK_STORAGE_KEY) || {}
}

export function writeTaskStore(store) {
  cache.local.setJSON(TASK_STORAGE_KEY, store)
  return store
}

export function readReportStore() {
  return cache.local.getJSON(REPORT_STORAGE_KEY) || {}
}

export function writeReportStore(store) {
  cache.local.setJSON(REPORT_STORAGE_KEY, store)
  return store
}

export function resolveScoreItem(taskName) {
  const source = `${taskName || ''}`.trim()
  if (!source) {
    return SCORE_ITEMS[0].label
  }
  const matched = SCORE_MATCHERS.find(item => item.keywords.some(keyword => source.includes(keyword)))
  return matched ? matched.label : SCORE_ITEMS[0].label
}

export function normalizeTaskRow(item, projectName, index) {
  const numericScore = item.score === '' || item.score === null || item.score === undefined
    ? null
    : Number(item.score)
  const submittedAt = item.submittedAt || item.submitTime || ''
  const assignedAssessor = item.assignedAssessor || item.currentAssessor || ''
  const currentAssessor = item.currentAssessor || item.assignedAssessor || '待分配'
  return {
    ...item,
    rowId: item.rowId || `${projectName || 'project'}-${index}`,
    taskName: item.taskName || `评估任务${index + 1}`,
    currentAssessor,
    assignedAssessor,
    status: item.status || '未开始',
    deadline: normalizeDate(item.deadline),
    submissionStatus: item.submissionStatus || (submittedAt ? '已提交' : '待提交'),
    submittedAt,
    score: Number.isNaN(numericScore) ? null : numericScore,
    scoreItem: item.scoreItem || resolveScoreItem(item.taskName),
    isSaved: typeof item.isSaved === 'boolean' ? item.isSaved : Boolean(assignedAssessor),
    isDispatched: typeof item.isDispatched === 'boolean' ? item.isDispatched : false
  }
}

export function getProjectTasks(taskStore, projectName) {
  const rows = Array.isArray(taskStore[projectName]) ? taskStore[projectName] : []
  return rows.map((item, index) => normalizeTaskRow(item, projectName, index))
}

export function saveProjectTasks(taskStore, projectName, rows) {
  const nextStore = {
    ...taskStore,
    [projectName]: rows
  }
  writeTaskStore(nextStore)
  return nextStore
}

export function normalizeMaterialRecord(item) {
  return {
    materialId: item.materialId,
    materialName: item.materialName || '',
    materialType: `${item.materialType || '1'}`,
    projectName: item.projectName || '',
    ownerName: item.ownerName || '',
    submitDate: normalizeDate(item.submitDate),
    filePath: item.filePath || ''
  }
}

export function buildMaterialSummary(projectName, materials) {
  const total = MATERIAL_REQUIREMENTS.reduce((sum, group) => sum + group.files.length, 0)
  const projectMaterials = materials.filter(item => item.projectName === projectName)
  const uploadedNames = new Set(projectMaterials.map(item => item.materialName))
  const uploaded = MATERIAL_REQUIREMENTS.reduce((sum, group) => {
    return sum + group.files.filter(fileName => uploadedNames.has(fileName)).length
  }, 0)
  return {
    uploaded,
    total
  }
}

export function computeAverageScore(tasks) {
  const values = tasks
    .map(item => item.score)
    .filter(item => typeof item === 'number' && !Number.isNaN(item))
  if (values.length === 0) {
    return null
  }
  return values.reduce((sum, item) => sum + item, 0) / values.length
}

export function formatScore(value) {
  if (value === null || value === undefined || value === '' || Number.isNaN(Number(value))) {
    return '-'
  }
  return `${Number(value).toFixed(1).replace(/\.0$/, '')}`
}

export function resolveRiskLevel(averageScore) {
  if (averageScore === null || averageScore === undefined) {
    return '待评估'
  }
  if (averageScore >= 90) {
    return '低风险'
  }
  if (averageScore >= 80) {
    return '中风险'
  }
  return '高风险'
}

export function nextVersion(version) {
  if (!version || version === '-') {
    return 'v1.0'
  }
  const matched = `${version}`.match(/^v(\d+)\.(\d+)$/i)
  if (!matched) {
    return 'v1.0'
  }
  const major = Number(matched[1])
  const minor = Number(matched[2]) + 1
  return `v${major}.${minor}`
}

export function buildReportNo(projectCode) {
  const datePart = todayString().replace(/-/g, '')
  const suffix = `${projectCode || '000'}`.slice(-3).padStart(3, '0')
  return `RPT-${datePart}-${suffix}`
}

export function buildConclusion(riskLevel, averageScore) {
  if (averageScore === null || averageScore === undefined) {
    return '待评估'
  }
  if (riskLevel === '低风险') {
    return '整体风险可控，建议进入报告归档与投后跟踪。'
  }
  if (riskLevel === '中风险') {
    return '风险可控但仍需补充核查，建议附带整改清单后进入报告出具。'
  }
  return '存在较高风险，建议补充尽调并完善风险缓释方案。'
}

export function buildScoreRows(tasks) {
  return SCORE_ITEMS.map(item => {
    const matched = tasks.filter(task => task.scoreItem === item.label && typeof task.score === 'number' && !Number.isNaN(task.score))
    if (matched.length === 0) {
      return {
        label: item.label,
        score: null
      }
    }
    const total = matched.reduce((sum, task) => sum + task.score, 0)
    return {
      label: item.label,
      score: total / matched.length
    }
  })
}
