<template>
  <div class="expense-application-mask" @click.self="emit('close')">
    <section class="expense-application-dialog" role="dialog" aria-modal="true" aria-labelledby="expense-application-title">
      <header class="application-dialog-header">
        <div>
          <span class="application-dialog-eyebrow">费用申请</span>
          <h2 id="expense-application-title">发起申请</h2>
        </div>
        <button class="dialog-icon-btn" type="button" aria-label="关闭" @click="emit('close')">
          <i class="mdi mdi-close"></i>
        </button>
      </header>

      <div class="application-dialog-body">
        <section class="application-input-panel">
          <label class="application-field-label" for="application-intent-input">申请意图</label>
          <textarea
            id="application-intent-input"
            v-model="draft"
            rows="5"
            placeholder="例如：申请下周去北京做客户现场验收，预计费用18000元"
          ></textarea>

          <div class="application-example-row">
            <button
              v-for="example in APPLICATION_EXAMPLES"
              :key="example"
              class="application-example-chip"
              type="button"
              @click="applyExample(example)"
            >
              {{ example }}
            </button>
          </div>

          <button class="primary-parse-btn" type="button" :disabled="parsing || !draft.trim()" @click="parseApplication">
            <i :class="parsing ? 'mdi mdi-loading mdi-spin' : 'mdi mdi-brain'"></i>
            <span>{{ parsing ? '识别中' : '识别申请字段' }}</span>
          </button>

          <p v-if="error" class="application-error">{{ error }}</p>
        </section>

        <section class="application-ontology-panel">
          <div class="ontology-panel-head">
            <span>本体识别结果</span>
            <strong>{{ confidenceLabel }}</strong>
          </div>

          <div v-if="!fields" class="ontology-empty-state">
            <i class="mdi mdi-file-search-outline"></i>
            <p>输入申请事项后，系统会调用本体解析费用场景、金额、时间、地点和附件要求。</p>
          </div>

          <template v-else>
            <div class="ontology-chip-row">
              <span class="ontology-chip">scenario: {{ ontology?.scenario || '-' }}</span>
              <span class="ontology-chip">intent: {{ ontology?.intent || '-' }}</span>
              <span class="ontology-chip">{{ fields.documentTypeLabel }}</span>
            </div>

            <div class="application-field-grid">
              <div class="application-field-card">
                <span>费用场景</span>
                <strong>{{ fields.expenseTypeLabel }}</strong>
              </div>
              <div class="application-field-card">
                <span>申请金额</span>
                <strong>{{ fields.amountDisplay }}</strong>
              </div>
              <div class="application-field-card">
                <span>业务时间</span>
                <strong>{{ fields.timeRange }}</strong>
              </div>
              <div class="application-field-card">
                <span>业务地点</span>
                <strong>{{ fields.location }}</strong>
              </div>
              <div class="application-field-card">
                <span>申请人</span>
                <strong>{{ fields.applicant }}</strong>
              </div>
              <div class="application-field-card">
                <span>所属部门</span>
                <strong>{{ fields.department }}</strong>
              </div>
            </div>

            <div class="application-policy-strip" :class="fields.attachmentPolicy.level">
              <i class="mdi mdi-paperclip-check"></i>
              <div>
                <strong>附件要求：{{ fields.attachmentPolicy.label }}</strong>
                <p>{{ fields.attachmentPolicy.description }}</p>
              </div>
            </div>

            <div class="application-reason-block">
              <span>申请事由</span>
              <p>{{ fields.reason }}</p>
            </div>

            <div v-if="fields.missingSlots.length" class="application-missing-block">
              <span>待补充字段</span>
              <div>
                <em v-for="slot in fields.missingSlots" :key="slot.key">{{ slot.label }}</em>
              </div>
            </div>
          </template>
        </section>
      </div>

      <footer class="application-dialog-footer">
        <button class="secondary-btn" type="button" @click="emit('close')">取消</button>
        <button class="confirm-btn" type="button" :disabled="!fields" @click="confirmApplication">
          <i class="mdi mdi-check-circle-outline"></i>
          <span>确认本体字段</span>
        </button>
      </footer>
    </section>
  </div>
</template>

<script setup>
import { computed, ref } from 'vue'

import { useSystemState } from '../../composables/useSystemState.js'
import { fetchOntologyParse } from '../../services/ontology.js'
import {
  APPLICATION_EXAMPLES,
  buildApplicationFieldsFromOntology,
  buildExpenseApplicationOntologyContext
} from '../../utils/expenseApplicationOntology.js'

const emit = defineEmits(['close', 'confirmed'])

const { currentUser } = useSystemState()
const draft = ref(APPLICATION_EXAMPLES[0])
const parsing = ref(false)
const error = ref('')
const ontology = ref(null)
const fields = ref(null)

const confidenceLabel = computed(() => {
  if (!ontology.value) return '待识别'
  return `${Math.round(Number(ontology.value.confidence || 0) * 100)}%`
})

function applyExample(example) {
  draft.value = example
}

async function parseApplication() {
  const query = draft.value.trim()
  if (!query) return

  parsing.value = true
  error.value = ''
  try {
    const payload = await fetchOntologyParse({
      query,
      user_id: currentUser.value?.username || currentUser.value?.name || 'anonymous',
      context_json: buildExpenseApplicationOntologyContext(currentUser.value || {})
    })
    ontology.value = payload
    fields.value = buildApplicationFieldsFromOntology(payload, query, currentUser.value || {})
  } catch (err) {
    ontology.value = null
    fields.value = null
    error.value = err?.message || '申请字段识别失败，请稍后重试。'
  } finally {
    parsing.value = false
  }
}

function confirmApplication() {
  if (!fields.value) return
  emit('confirmed', {
    ontology: ontology.value,
    fields: fields.value,
    sourceText: draft.value.trim()
  })
}
</script>

<style scoped src="../../assets/styles/components/expense-application-dialog.css"></style>
