export const APPLICATION_NON_BLOCKING_MISSING_FIELDS = new Set([
  'amount',
  'attachments',
  'employee_no',
  'employee_name',
  'department_name'
])

export const FLOW_EXPENSE_TYPE_LABELS = {
  travel: '差旅费'
}

const FIELD_DISPLAY_CONFIG = {
  expense_type: {
    label: '费用类型',
    hint: '例如差旅、交通、住宿、业务招待'
  },
  time_range: {
    label: '发生时间',
    hint: '申请时填出差起止日期，报销时填费用发生日期'
  },
  location: {
    label: '地点',
    hint: '出差城市或费用发生地点'
  },
  reason: {
    label: '事由',
    hint: '出差、报销或业务活动的具体原因'
  },
  amount: {
    label: '金额',
    hint: '申请时为预计金额，报销时为实际报销金额'
  },
  transport_mode: {
    label: '出行方式',
    hint: '例如高铁、飞机、自驾、出租车'
  },
  attachments: {
    label: '附件/凭证',
    hint: '发票、行程单、付款截图或其他证明材料'
  },
  customer_name: {
    label: '客户或项目对象',
    hint: '涉及的客户、单位或项目名称'
  },
  merchant_name: {
    label: '商户/开票方',
    hint: '发票或付款凭证上的商户名称'
  },
  department_name: {
    label: '所属部门',
    hint: '申请人或费用归属部门'
  },
  employee_name: {
    label: '申请人',
    hint: '发起申请或报销的员工姓名'
  },
  employee_no: {
    label: '员工编号',
    hint: '公司内部员工编号'
  }
}

const FIELD_ALIASES = {
  occurred_date: 'time_range',
  business_time: 'time_range',
  reason_value: 'reason',
  transport_type: 'transport_mode',
  application_transport_mode: 'transport_mode'
}

const FIELD_VALUE_DISPLAY_CONFIG = {
  expense_type: {
    travel: '差旅',
    business_entertainment: '业务招待',
    transportation: '交通费',
    traffic: '交通费',
    accommodation: '住宿费',
    meal: '餐饮费'
  }
}

export function normalizeFieldKey(field) {
  const key = String(field || '').trim()
  return FIELD_ALIASES[key] || key
}

export function resolveFieldDisplay(field, taskType = '') {
  const key = normalizeFieldKey(field)
  const config = FIELD_DISPLAY_CONFIG[key] || {
    label: key.replace(/_/g, ' '),
    hint: ''
  }
  if (key === 'amount') {
    return {
      key,
      label: taskType === 'expense_application' ? '预计金额' : '报销金额',
      hint: taskType === 'expense_application'
        ? '本次申请预计发生的费用'
        : '本次需要报销的实际金额'
    }
  }
  return {
    key,
    label: config.label,
    hint: config.hint
  }
}

export function formatStewardFieldDisplayValue(field, value) {
  const key = normalizeFieldKey(field)
  const normalizedValue = String(value || '').trim()
  return FIELD_VALUE_DISPLAY_CONFIG[key]?.[normalizedValue] || normalizedValue
}

export function buildStewardFieldItems(fields = [], taskType = '') {
  const safeFields = filterStewardBlockingMissingFields(fields, taskType)
  const seen = new Set()
  return safeFields
    .map((field) => normalizeFieldKey(field))
    .filter((field) => {
      if (!field || seen.has(field)) {
        return false
      }
      seen.add(field)
      return true
    })
    .map((field) => resolveFieldDisplay(field, taskType))
}

export function formatStewardMissingFieldList(fields = [], taskType = '', options = {}) {
  const includeHints = options.includeHints !== false
  return buildStewardFieldItems(fields, taskType)
    .map((item) => includeHints && item.hint ? `${item.label}（${item.hint}）` : item.label)
    .join('、')
}

export function filterStewardBlockingMissingFields(fields = [], taskType = '') {
  const safeFields = Array.isArray(fields) ? fields : []
  const seen = new Set()
  if (taskType !== 'expense_application') {
    return safeFields
      .map((field) => normalizeFieldKey(field))
      .filter((field) => {
        if (!field || seen.has(field)) {
          return false
        }
        seen.add(field)
        return true
      })
  }
  return safeFields
    .map((field) => normalizeFieldKey(field))
    .filter((field) => {
      if (!field || seen.has(field) || APPLICATION_NON_BLOCKING_MISSING_FIELDS.has(field)) {
        return false
      }
      seen.add(field)
      return true
    })
}

export function formatStewardOntologyFields(fields = {}, taskType = '') {
  return Object.entries(fields || {})
    .filter(([, value]) => String(value || '').trim())
    .map(([key, value]) => {
      const field = resolveFieldDisplay(key, taskType)
      return `${field.label}：${formatStewardFieldDisplayValue(field.key, value)}`
    })
    .join('；')
}

function buildStewardOntologyFieldRows(fields = {}, taskType = '') {
  return Object.entries(fields || {})
    .filter(([, value]) => String(value || '').trim())
    .map(([key, value]) => {
      const field = resolveFieldDisplay(key, taskType)
      return {
        label: field.label,
        value: formatStewardFieldDisplayValue(field.key, value)
      }
    })
}

function escapeMarkdownTableCell(value) {
  return String(value || '').replace(/\|/g, '\\|').replace(/\n+/g, ' ').trim()
}

export function formatStewardOntologyFieldsTable(fields = {}, taskType = '') {
  const rows = buildStewardOntologyFieldRows(fields, taskType)
  if (!rows.length) {
    return ''
  }
  return [
    '| 字段 | 内容 |',
    '| --- | --- |',
    ...rows.map((row) => `| ${escapeMarkdownTableCell(row.label)} | ${escapeMarkdownTableCell(row.value)} |`)
  ].join('\n')
}
