import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import test from 'node:test'
import { fileURLToPath } from 'node:url'

const detailTemplate = readFileSync(
  fileURLToPath(new URL('../src/views/TravelRequestDetailView.vue', import.meta.url)),
  'utf8'
)
const detailScript = readFileSync(
  fileURLToPath(new URL('../src/views/scripts/TravelRequestDetailView.js', import.meta.url)),
  'utf8'
)
const detailStyles = readFileSync(
  fileURLToPath(new URL('../src/assets/styles/views/travel-request-detail-view.css', import.meta.url)),
  'utf8'
)
const approvalDialog = readFileSync(
  fileURLToPath(new URL('../src/components/travel/TravelRequestApprovalDialog.vue', import.meta.url)),
  'utf8'
)
const budgetAnalysisComponent = readFileSync(
  fileURLToPath(new URL('../src/components/travel/TravelRequestBudgetAnalysis.vue', import.meta.url)),
  'utf8'
)
const reimbursementService = readFileSync(
  fileURLToPath(new URL('../src/services/reimbursements.js', import.meta.url)),
  'utf8'
)

function extractFunction(source, name) {
  const signatureIndex = source.indexOf(`function ${name}(`)
  assert.notEqual(signatureIndex, -1, `${name} should exist`)

  const bodyStart = source.indexOf('{', signatureIndex)
  assert.notEqual(bodyStart, -1, `${name} should have a body`)

  let depth = 0
  for (let index = bodyStart; index < source.length; index += 1) {
    const char = source[index]
    if (char === '{') {
      depth += 1
    } else if (char === '}') {
      depth -= 1
      if (depth === 0) {
        return source.slice(signatureIndex, index + 1)
      }
    }
  }

  assert.fail(`${name} body should be closed`)
}

test('approval-mode detail collects leader opinion inside confirm dialog before API call', () => {
  assert.match(detailScript, /approvalMode:/)
  assert.match(detailScript, /const leaderOpinion = ref\(''\)/)
  assert.match(detailScript, /const approveConfirmDialogOpen = ref\(false\)/)
  assert.match(detailScript, /const canApproveRequest = computed/)
  assert.match(detailScript, /canApproveLeaderExpenseClaims/)
  assert.match(detailScript, /canApproveBudgetExpenseApplications/)
  assert.match(detailScript, /isCurrentDirectManagerForRequest/)
  assert.match(detailScript, /isCurrentRequestApplicant/)
  assert.match(detailScript, /isFinanceApprovalStage/)
  assert.match(detailScript, /const isBudgetApprovalStage = computed/)
  assert.match(detailScript, /const showBudgetAnalysis = computed/)
  assert.match(detailScript, /const isCurrentApplicant = computed/)
  assert.match(detailScript, /const isCurrentDirectManagerApprover = computed/)
  assert.match(detailScript, /const canProcessFinanceApprovalStage = computed/)
  assert.match(detailScript, /const canProcessBudgetApprovalStage = computed/)
  assert.match(detailScript, /approvalOpinionTitle/)
  assert.match(detailScript, /approvalConfirmDescription/)
  assert.doesNotMatch(detailScript, /approvalNextStage/)
  assert.doesNotMatch(detailScript, /showApplicationLeaderOpinionInput/)
  assert.doesNotMatch(detailScript, /showLeaderApprovalPanel/)
  assert.match(detailScript, /const requiresApprovalOpinion = computed\(\(\) => false\)/)
  assert.match(detailScript, /approvalOpinionTitle = computed\(\(\) => \(isFinanceApprovalStage\.value \? '财务意见' : '附加意见'\)\)/)
  assert.match(detailScript, /buildLeaderApprovalEvents/)
  assert.match(detailScript, /buildLeaderApprovalInfo/)
  assert.match(detailScript, /const leaderApprovalEvents = computed/)
  assert.match(detailScript, /const hasLeaderApprovalEvents = computed/)
  assert.match(
    detailScript,
    /const showApplicationLeaderOpinion = computed\(\(\) => \(\s*isApplicationDocument\.value\s*&& hasLeaderApprovalEvents\.value\s*\)\)/
  )
  assert.match(detailScript, /isDirectManagerApprovalStage\.value\)[\s\S]*return isCurrentDirectManagerApprover\.value/)
  assert.match(detailScript, /isDirectManagerApprovalStage\.value[\s\S]*&& isCurrentDirectManagerApprover\.value/)
  assert.match(detailScript, /canProcessFinanceApprovalStage\.value/)
  assert.match(detailScript, /canProcessBudgetApprovalStage\.value/)
  assert.doesNotMatch(detailScript, /leaderApprovalReadonlyText/)
  assert.match(detailScript, /resolveGeneratedDraftClaimNo/)
  assert.match(detailScript, /approveActionLabel/)
  assert.match(detailScript, /approveExpenseClaim\(request\.value\.claimId, \{[\s\S]*opinion: leaderOpinion\.value\.trim\(\) \|\| '同意'/)
  assert.match(detailScript, /报销草稿 \$\{generatedDraftClaimNo\} 已生成/)
  assert.match(detailScript, /流转至预算管理者审批/)

  assert.doesNotMatch(detailTemplate, /v-if="showLeaderApprovalPanel"/)
  assert.doesNotMatch(detailTemplate, /showApplicationLeaderOpinionInput/)
  assert.doesNotMatch(detailTemplate, /class="leader-approval-card/)
  assert.doesNotMatch(detailTemplate, /class="inline-leader-opinion/)
  assert.match(detailTemplate, /v-if="showApplicationLeaderOpinion"/)
  assert.match(detailTemplate, /class="application-leader-opinion"/)
  assert.match(detailTemplate, /v-if="hasLeaderApprovalEvents"/)
  assert.match(detailTemplate, /class="application-leader-opinion-timeline"/)
  assert.match(detailTemplate, /v-for="event in leaderApprovalEvents"/)
  assert.match(detailTemplate, /class="application-leader-opinion-event"/)
  assert.match(detailTemplate, /event\.type === 'returned'/)
  assert.doesNotMatch(detailTemplate, /leaderApprovalReadonlyText/)
  assert.doesNotMatch(detailTemplate, /\u5f85\u76f4\u5c5e\u9886\u5bfc\u586b\u5199\u5ba1\u6279\u610f\u89c1/)
  assert.match(detailTemplate, /领导意见/)
  assert.match(detailTemplate, /<TravelRequestBudgetAnalysis[\s\S]*v-if="showBudgetAnalysis"[\s\S]*:claim-id="request\.claimId"/)
  assert.match(approvalDialog, /\{\{ opinionTitle \}\}/)
  assert.doesNotMatch(detailTemplate, /v-model="leaderOpinion"/)
  assert.match(detailTemplate, /@click="handleApproveRequest"/)
  assert.match(detailTemplate, /\{\{ approveBusy \? approveBusyLabel : approveActionLabel \}\}/)
  assert.match(detailTemplate, /:open="approveConfirmDialogOpen"/)
  assert.match(detailTemplate, /:badge="approvalConfirmBadge"/)
  assert.match(detailTemplate, /:description="approvalConfirmDescription"/)
  assert.match(detailTemplate, /:confirm-text="approveConfirmText"/)
  assert.match(detailTemplate, /:busy-text="approveBusyText"/)
  assert.doesNotMatch(detailTemplate, /:next-stage="approvalNextStage"/)
  assert.doesNotMatch(approvalDialog, /submit-confirm-summary/)
  assert.doesNotMatch(approvalDialog, /单据编号/)
  assert.doesNotMatch(approvalDialog, /当前节点/)
  assert.match(detailTemplate, /v-model:opinion="leaderOpinion"/)
  assert.match(detailTemplate, /:opinion-placeholder="approvalOpinionPlaceholder"/)
  assert.match(detailTemplate, /:opinion-hint="approvalOpinionHint"/)
  assert.match(detailTemplate, /:opinion-required="requiresApprovalOpinion"/)
  assert.match(detailTemplate, /@confirm="confirmApproveRequest"/)
  assert.match(detailTemplate, /:description="returnDialogDescription"/)
  assert.match(detailTemplate, /:application="isApplicationDocument"/)

  const handleApproveRequest = extractFunction(detailScript, 'handleApproveRequest')
  const confirmApproveRequest = extractFunction(detailScript, 'confirmApproveRequest')
  assert.doesNotMatch(handleApproveRequest, /approveExpenseClaim/)
  assert.doesNotMatch(handleApproveRequest, /leaderOpinion\.value\.trim/)
  assert.match(confirmApproveRequest, /approveExpenseClaim/)
  assert.doesNotMatch(confirmApproveRequest, /requiresApprovalOpinion\.value && !leaderOpinion\.value\.trim\(\)/)
  assert.doesNotMatch(confirmApproveRequest, /请先填写领导意见，填写后才能确认审核。/)

  assert.match(approvalDialog, /<textarea/)
  assert.match(approvalDialog, /update:opinion/)
  assert.match(approvalDialog, /opinionPlaceholder/)
  assert.match(approvalDialog, /opinionHint/)
  assert.match(approvalDialog, /opinionRequired/)
  assert.match(approvalDialog, /\{\{ currentOpinion\.length \}\}\/500/)

  assert.match(detailStyles, /\.detail-card-title-with-icon \{[\s\S]*display: inline-flex;[\s\S]*align-items: center;[\s\S]*gap: 8px;/)
  assert.match(detailStyles, /\.detail-card-title-with-icon i \{[\s\S]*font-size: 18px;[\s\S]*line-height: 1;/)
  assert.match(detailStyles, /\.application-leader-opinion-head span \{[\s\S]*display: inline-flex;[\s\S]*align-items: center;[\s\S]*gap: 8px;/)
  assert.doesNotMatch(detailStyles, /\.leader-approval-card/)
  assert.doesNotMatch(detailStyles, /\.inline-leader-opinion/)
  assert.match(detailStyles, /\.application-leader-opinion-timeline \{/)
  assert.match(detailStyles, /\.application-leader-opinion-event \{/)
  assert.match(detailStyles, /\.application-leader-opinion-event\.danger::before \{/)
  assert.match(detailStyles, /\.application-leader-opinion-event\.success::before \{/)

  assert.match(reimbursementService, /export function approveExpenseClaim\(claimId, payload = \{\}\)/)
  assert.match(reimbursementService, /\/approve/)
  assert.match(reimbursementService, /export function fetchExpenseClaimBudgetAnalysis/)
  assert.match(reimbursementService, /\/budget-analysis/)
  assert.match(budgetAnalysisComponent, /预算分析/)
  assert.match(budgetAnalysisComponent, /当前预算额度/)
  assert.match(budgetAnalysisComponent, /此次费用占预算/)
  assert.match(budgetAnalysisComponent, /综合评分/)
  assert.match(budgetAnalysisComponent, /fetchExpenseClaimBudgetAnalysis/)
})
