import cache from '@/plugins/cache'
import { listProject } from '@/api/risk/project'
import { listMaterial } from '@/api/risk/material'
import { MATERIAL_REQUIREMENTS, buildMaterialSummary, nowString, todayString } from '@/views/project/shared/workbench'

export const ASSESSOR_TASK_STORAGE_KEY = 'assessor-workbench-task-records-v1'
export const ASSESSOR_SUBMISSION_STORAGE_KEY = 'assessor-workbench-submission-records-v1'
export const ASSESSOR_ACTIVITY_STORAGE_KEY = 'assessor-workbench-activity-records-v1'

export const DEFAULT_ASSESSOR_NAME = '评估师A'
export const DEFAULT_ASSESSOR_ROLE = '评估师'
export const DEFAULT_PROJECT_CODE = 'PJT-2026-0401'
export const DEFAULT_PROJECT_NAME = '华东物流园资产投资'
export const DEFAULT_OWNER_NAME = '陈越'

const PROJECT_CODE_MAP = {
  '华东物流园资产投资': 'PJT-2026-0401',
  '西南园区存量资产转化': 'PJT-2026-0326'
}

const DEFAULT_PROJECTS = [
  {
    projectId: 'risk-project-1',
    projectCode: 'PJT-2026-0401',
    projectName: '华东物流园资产投资',
    projectManager: '陈越'
  },
  {
    projectId: 'risk-project-2',
    projectCode: 'PJT-2026-0326',
    projectName: '西南园区存量资产转化',
    projectManager: '李清'
  }
]

const DEFAULT_ACTIVITY_ROWS = [
  { time: '2026-04-15 16:19', operator: '管理员', action: '启用模板TPL-001' },
  { time: '2026-04-15 16:19', operator: '管理员', action: '停用模板TPL-001' },
  { time: '2026-04-15 15:26', operator: '管理员', action: '预览文件:行业研究_2026Q1.pdf' },
  { time: '2026-04-15 15:26', operator: '管理员', action: '预览文件:行业研究_2026Q1.pdf' },
  { time: '2026-04-15 15:11', operator: '管理员', action: '下载归档报告' },
  { time: '2026-04-15 15:02', operator: '管理员', action: '生成报告' }
]

function resolveProjectCode(item, index) {
  return item.projectCode ||
    item.projectNo ||
    item.projectNum ||
    item.projectSn ||
    PROJECT_CODE_MAP[item.projectName] ||
    `PJT-2026-${`${401 + index}`.padStart(4, '0')}`
}

function normalizeProject(item, index) {
  return {
    projectId: item.projectId || `risk-project-${index + 1}`,
    projectCode: resolveProjectCode(item, index),
    projectName: item.projectName || DEFAULT_PROJECTS[index % DEFAULT_PROJECTS.length].projectName,
    projectManager: item.projectManager || DEFAULT_OWNER_NAME
  }
}

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

function normalizeMaterial(item) {
  return {
    materialId: item.materialId,
    materialName: item.materialName || '',
    materialType: `${item.materialType || '1'}`,
    projectName: item.projectName || '',
    ownerName: item.ownerName || DEFAULT_OWNER_NAME,
    materialStatus: `${item.materialStatus || '1'}`,
    filePath: item.filePath || '',
    submitDate: normalizeDateTime(item.submitDate)
  }
}

function resolveCurrentProject(projects) {
  return projects.find(item => item.projectCode === DEFAULT_PROJECT_CODE) ||
    projects.find(item => item.projectName === DEFAULT_PROJECT_NAME) ||
    projects[0] ||
    DEFAULT_PROJECTS[0]
}

function readStore(key) {
  return cache.local.getJSON(key) || {}
}

function writeStore(key, value) {
  cache.local.setJSON(key, value)
  return value
}

function resolveOwnerName(project) {
  return (project && project.projectManager) || DEFAULT_OWNER_NAME
}

function createSubmissionNo(projectCode, index) {
  const matched = `${projectCode || DEFAULT_PROJECT_CODE}`.match(/(\d{4})-(\d{4})/)
  if (!matched) {
    return `SUB-${todayString().replace(/-/g, '')}-${String(index).padStart(3, '0')}`
  }
  return `SUB-${matched[1]}-${matched[2]}-${String(index).padStart(3, '0')}`
}

function buildDefaultTasks(project, assessorName) {
  return [
    {
      rowId: `${project.projectCode}-task-1`,
      taskName: '行业风险评估',
      assessorName,
      deadline: '2026-04-08',
      status: '进行中',
      score: null,
      conclusion: '',
      submittedAt: ''
    },
    {
      rowId: `${project.projectCode}-task-2`,
      taskName: '企业财务评估',
      assessorName,
      deadline: '2026-04-08',
      status: '未开始',
      score: null,
      conclusion: '',
      submittedAt: ''
    },
    {
      rowId: `${project.projectCode}-task-3`,
      taskName: '法务政策评估',
      assessorName,
      deadline: '2026-04-09',
      status: '已完成',
      score: 8,
      conclusion: '已完成核心法务合规点核验，建议补充合同条款执行闭环说明。',
      submittedAt: '2026-04-03 14:20'
    }
  ]
}

function buildDefaultSubmissions(projectCode, assessorName) {
  return [
    {
      submissionNo: createSubmissionNo(projectCode, 1),
      submitter: assessorName,
      taskName: '法务政策评估',
      status: '已提交',
      submitTime: '2026-04-03 09:25',
      score: 8,
      content: '已完成主体资质、合同补充协议及合规要点梳理。'
    },
    {
      submissionNo: createSubmissionNo(projectCode, 4),
      submitter: assessorName,
      taskName: '法务政策评估',
      status: '待复核',
      submitTime: '2026-04-03 14:20',
      score: 8,
      content: '补充上传法务政策评估复核说明，等待项目经理复核确认。'
    }
  ]
}

function buildDefaultActivities(project) {
  return DEFAULT_ACTIVITY_ROWS.map((item, index) => ({
    rowId: `${project.projectCode}-activity-${index + 1}`,
    ...item,
    projectCode: project.projectCode
  }))
}

function getTaskStore() {
  return readStore(ASSESSOR_TASK_STORAGE_KEY)
}

function setTaskStore(store) {
  return writeStore(ASSESSOR_TASK_STORAGE_KEY, store)
}

function getSubmissionStore() {
  return readStore(ASSESSOR_SUBMISSION_STORAGE_KEY)
}

function setSubmissionStore(store) {
  return writeStore(ASSESSOR_SUBMISSION_STORAGE_KEY, store)
}

function getActivityStore() {
  return readStore(ASSESSOR_ACTIVITY_STORAGE_KEY)
}

function setActivityStore(store) {
  return writeStore(ASSESSOR_ACTIVITY_STORAGE_KEY, store)
}

export function getProjectTasks(projectCode, assessorName = DEFAULT_ASSESSOR_NAME, project = DEFAULT_PROJECTS[0]) {
  const store = getTaskStore()
  if (!Array.isArray(store[projectCode])) {
    store[projectCode] = buildDefaultTasks(project, assessorName)
    setTaskStore(store)
  }
  return (store[projectCode] || []).map(item => ({
    rowId: item.rowId,
    taskName: item.taskName,
    assessorName: item.assessorName || assessorName,
    deadline: item.deadline,
    status: item.status,
    score: item.score === null || item.score === undefined || item.score === '' ? null : Number(item.score),
    conclusion: item.conclusion || '',
    submittedAt: item.submittedAt || ''
  }))
}

export function saveProjectTasks(projectCode, rows) {
  const store = getTaskStore()
  store[projectCode] = rows
  setTaskStore(store)
  return rows
}

export function getProjectSubmissions(projectCode, assessorName = DEFAULT_ASSESSOR_NAME) {
  const store = getSubmissionStore()
  if (!Array.isArray(store[projectCode])) {
    store[projectCode] = buildDefaultSubmissions(projectCode, assessorName)
    setSubmissionStore(store)
  }
  return (store[projectCode] || []).map(item => ({
    ...item,
    score: item.score === null || item.score === undefined || item.score === '' ? null : Number(item.score)
  }))
}

export function saveProjectSubmissions(projectCode, rows) {
  const store = getSubmissionStore()
  store[projectCode] = rows
  setSubmissionStore(store)
  return rows
}

export function getProjectActivities(project) {
  const projectCode = project.projectCode || DEFAULT_PROJECT_CODE
  const store = getActivityStore()
  if (!Array.isArray(store[projectCode])) {
    store[projectCode] = buildDefaultActivities(project)
    setActivityStore(store)
  }
  return store[projectCode] || []
}

export function appendProjectActivity(project, operator, action, time = nowString()) {
  const projectCode = project.projectCode || DEFAULT_PROJECT_CODE
  const store = getActivityStore()
  const rows = Array.isArray(store[projectCode]) ? store[projectCode].slice() : buildDefaultActivities(project)
  rows.unshift({
    rowId: `${projectCode}-${Date.now()}`,
    time,
    operator,
    action,
    projectCode
  })
  store[projectCode] = rows.slice(0, 12)
  setActivityStore(store)
  return store[projectCode]
}

function syncTasksWithSubmissions(taskRows, submissionRows) {
  const latestMap = submissionRows.reduce((accumulator, item) => {
    if (!accumulator[item.taskName] || accumulator[item.taskName].submitTime < item.submitTime) {
      accumulator[item.taskName] = item
    }
    return accumulator
  }, {})
  return taskRows.map(item => {
    const matched = latestMap[item.taskName]
    if (!matched) {
      return item
    }
    return {
      ...item,
      status: '已完成',
      score: matched.score,
      conclusion: matched.content || item.conclusion,
      submittedAt: matched.submitTime || item.submittedAt
    }
  })
}

export function submitAssessment(project, taskRow, payload) {
  const projectCode = project.projectCode
  const taskRows = getProjectTasks(projectCode, payload.assessorName, project)
  const submissionRows = getProjectSubmissions(projectCode, payload.assessorName)
  const submitTime = payload.submitTime || nowString()
  const nextTaskRows = taskRows.map(item => {
    if (item.rowId !== taskRow.rowId) {
      return item
    }
    return {
      ...item,
      status: '已完成',
      score: Number(payload.score),
      conclusion: payload.content,
      submittedAt: submitTime
    }
  })
  const nextSubmission = {
    submissionNo: createSubmissionNo(projectCode, submissionRows.length + 1),
    submitter: payload.assessorName,
    taskName: taskRow.taskName,
    status: '已提交',
    submitTime,
    score: Number(payload.score),
    content: payload.content
  }
  saveProjectTasks(projectCode, nextTaskRows)
  saveProjectSubmissions(projectCode, [nextSubmission].concat(submissionRows))
  appendProjectActivity(project, payload.assessorName, `提交评估：${taskRow.taskName}`, submitTime)
  return {
    taskRows: nextTaskRows,
    submissionRows: [nextSubmission].concat(submissionRows)
  }
}

function resolveCategory(material) {
  const matchedGroup = MATERIAL_REQUIREMENTS.find(item => item.files.includes(material.materialName))
  if (matchedGroup) {
    return matchedGroup.category
  }
  const fallbackMap = {
    1: '行业资料',
    2: '财务资料',
    3: '法务资料',
    4: '担保品资料'
  }
  return fallbackMap[material.materialType] || '其他资料'
}

function buildUploadedMaterialRow(material, category) {
  return {
    rowId: material.materialId || `${material.projectName}-${category}-${material.materialName}`,
    category,
    materialName: material.materialName,
    ownerName: material.ownerName || DEFAULT_OWNER_NAME,
    status: material.filePath ? '已上传' : '待补件',
    submitDate: material.submitDate || '',
    filePath: material.filePath || '',
    uploaded: Boolean(material.filePath)
  }
}

function buildPendingMaterialRow(projectName, category, materialName, ownerName) {
  return {
    rowId: `${projectName}-${category}-${materialName}`,
    category,
    materialName,
    ownerName,
    status: '待补件',
    submitDate: '',
    filePath: '',
    uploaded: false
  }
}

export function buildWorkbenchMaterialRows(project, materials) {
  const ownerName = resolveOwnerName(project)
  const projectName = project.projectName || DEFAULT_PROJECT_NAME
  const projectMaterials = materials.filter(item => item.projectName === projectName)
  const usedIds = new Set()
  const rows = []

  MATERIAL_REQUIREMENTS.forEach(group => {
    group.files.forEach(fileName => {
      const matched = projectMaterials.find(item => !usedIds.has(item.materialId) && item.materialName === fileName)
      if (matched) {
        usedIds.add(matched.materialId)
        rows.push(buildUploadedMaterialRow(matched, group.category))
      } else {
        rows.push(buildPendingMaterialRow(projectName, group.category, fileName, ownerName))
      }
    })
  })

  projectMaterials
    .filter(item => !usedIds.has(item.materialId))
    .forEach(item => {
      rows.push(buildUploadedMaterialRow(item, resolveCategory(item)))
    })

  return rows
}

export function buildSummaryCards(assessorName, currentProject, taskRows, submissionRows, materials) {
  const totalTasks = taskRows.length
  const completedTasks = taskRows.filter(item => item.status === '已完成').length
  const pendingTasks = totalTasks - completedTasks
  const materialSummary = buildMaterialSummary(currentProject.projectName, materials)
  const completionRate = materialSummary.total === 0
    ? 0
    : Math.round((materialSummary.uploaded / materialSummary.total) * 100)
  return [
    {
      key: 'account',
      label: '当前账号',
      primary: assessorName,
      secondary: `角色：${DEFAULT_ASSESSOR_ROLE}`
    },
    {
      key: 'tasks',
      label: '我的任务',
      primary: `${completedTasks}/${totalTasks || 0}`,
      secondary: `待处理：${pendingTasks}`
    },
    {
      key: 'submissions',
      label: '我的提交',
      primary: `${submissionRows.length}`,
      secondary: `项目：${currentProject.projectCode}`
    },
    {
      key: 'materials',
      label: '资料完整度',
      primary: `${completionRate}%`,
      secondary: `${materialSummary.uploaded}/${materialSummary.total}`
    }
  ]
}

export async function loadWorkbenchSnapshot() {
  let projects = DEFAULT_PROJECTS
  let materials = []

  try {
    const [projectResponse, materialResponse] = await Promise.all([
      listProject({ pageNum: 1, pageSize: 1000 }),
      listMaterial({ pageNum: 1, pageSize: 1000 })
    ])
    const projectRows = Array.isArray(projectResponse.rows) && projectResponse.rows.length > 0
      ? projectResponse.rows.map(normalizeProject)
      : DEFAULT_PROJECTS
    projects = projectRows
    materials = (materialResponse.rows || []).map(normalizeMaterial)
  } catch (error) {
    projects = DEFAULT_PROJECTS
    materials = []
  }

  const currentProject = resolveCurrentProject(projects)
  const assessorName = DEFAULT_ASSESSOR_NAME
  const submissionRows = getProjectSubmissions(currentProject.projectCode, assessorName)
  const syncedTaskRows = syncTasksWithSubmissions(
    getProjectTasks(currentProject.projectCode, assessorName, currentProject),
    submissionRows
  )
  saveProjectTasks(currentProject.projectCode, syncedTaskRows)

  return {
    assessorName,
    currentProject,
    projectOptions: projects,
    materials,
    materialRows: buildWorkbenchMaterialRows(currentProject, materials),
    taskRows: syncedTaskRows,
    submissionRows,
    activities: getProjectActivities(currentProject),
    summaryCards: buildSummaryCards(assessorName, currentProject, syncedTaskRows, submissionRows, materials)
  }
}

export function normalizeResourcePath(path) {
  if (!path) {
    return ''
  }
  if (/^https?:\/\//.test(path)) {
    return path
  }
  if (path.startsWith('/profile/')) {
    return path
  }
  if (path.startsWith('profile/')) {
    return `/${path}`
  }
  if (path.startsWith('/upload/')) {
    return `/profile${path}`
  }
  return `/profile/${path.replace(/^\//, '')}`
}

export function getPreviewUrl(path) {
  const normalized = normalizeResourcePath(path)
  if (!normalized) {
    return ''
  }
  if (/^https?:\/\//.test(normalized)) {
    return normalized
  }
  return `${process.env.VUE_APP_BASE_API}${normalized}`
}

export function getFileExtension(name) {
  const source = `${name || ''}`.split('?')[0]
  const index = source.lastIndexOf('.')
  return index === -1 ? '' : source.slice(index + 1).toLowerCase()
}

export function resolvePreviewType(nameOrPath) {
  const ext = getFileExtension(nameOrPath)
  if (['png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp'].includes(ext)) {
    return 'image'
  }
  if (ext === 'pdf') {
    return 'pdf'
  }
  if (['txt', 'md', 'json', 'csv', 'xml', 'log'].includes(ext)) {
    return 'text'
  }
  return 'unsupported'
}
