<template>
  <el-dialog
    v-model="workbenchVisible"
    append-to-body
    fullscreen
    :show-close="false"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :lock-scroll="true"
    :destroy-on-close="false"
    class="assistant-el-dialog"
    modal-class="assistant-el-overlay"
    body-class="assistant-el-dialog-body"
    transition="assistant-dialog-zoom"
    aria-label="智能报销助手"
    @opened="handleAssistantModalAfterEnter"
    @closed="emitCloseAfterLeave"
  >
    <section class="assistant-modal">
          <div class="assistant-header-actions">
            <button
              type="button"
              class="assistant-toggle-btn"
              :class="{ disabled: !hasInsightPanelContent }"
              :disabled="!hasInsightPanelContent || sessionSwitchBusy"
              :title="insightPanelToggleLabel"
              :aria-label="insightPanelToggleLabel"
              @click="toggleInsightPanel"
            >
              <i :class="showInsightPanel ? 'mdi mdi-arrow-collapse-right' : 'mdi mdi-arrow-expand-right'"></i>
            </button>
            <button
              type="button"
              class="session-trash-btn"
              :disabled="!canDeleteCurrentSession || submitting || reviewActionBusy || deleteSessionBusy || sessionSwitchBusy"
              title="删除当前会话"
              aria-label="删除当前会话"
              @click="openDeleteSessionDialog"
            >
              <i class="mdi mdi-delete-outline"></i>
            </button>
            <button
              class="assistant-close-btn"
              type="button"
              title="关闭工作台"
              aria-label="关闭对话工作台"
              @click="requestCloseWorkbench"
            >
              <i class="mdi mdi-close"></i>
            </button>
          </div>

          <div class="assistant-modal-stage">
            <header class="assistant-header">
              <div class="assistant-header-main">
                <div>
                  <h2 class="assistant-title">{{ assistantHeaderTitle }}</h2>
                  <p class="assistant-subtitle">{{ assistantHeaderDescription }}</p>
                </div>
              </div>
            </header>

            <div
              class="assistant-layout"
              :class="{
                'can-show-insight': hasInsightPanelContent,
                'has-insight': hasInsightPanelContent && showInsightPanel
              }"
            >
              <section class="dialog-panel">
                <div v-if="shortcuts.length" class="dialog-toolbar">
                  <span class="dialog-toolbar-label">
                    <i class="mdi mdi-swap-horizontal"></i>
                    智能体切换
                  </span>
                  <div class="shortcut-chip-wrap">
                    <button
                      v-for="shortcut in shortcuts"
                      :key="shortcut.label"
                      type="button"
                      class="shortcut-chip"
                      :class="{ active: shortcut.active }"
                      :aria-pressed="shortcut.active ? 'true' : 'false'"
                      :disabled="shortcut.active || submitting || reviewActionBusy || deleteSessionBusy || sessionSwitchBusy"
                      @click="runShortcut(shortcut)"
                    >
                      <i :class="shortcut.icon"></i>
                      <span>{{ shortcut.label }}</span>
                    </button>
                  </div>
                </div>

                <transition-group tag="div" name="message-row-reveal" ref="messageListRef" class="message-list" aria-live="polite">
                  <div
                    v-if="showStewardInitialRecognition"
                    class="steward-initial-recognition"
                    role="status"
                    aria-live="polite"
                    key="initial-recognition"
                  >
                    <div class="steward-initial-recognition-icon">
                      <i class="mdi mdi-brain"></i>
                    </div>
                    <div class="steward-initial-recognition-copy">
                      <strong>小财管家正在识别意图</strong>
                      <p>我正在读取您的输入，准备拆解申请、报销和附件任务。</p>
                    </div>
                  </div>

                  <TravelReimbursementMessageItem
                    v-for="message in messages"
                    :key="message.id"
                    :message="message"
                    :ui="messageItemUi"
                  />
                </transition-group>

                <form class="composer" @submit.prevent="submitComposer">
                  <input
                    ref="fileInputRef"
                    class="hidden-file-input"
                    type="file"
                    multiple
                    accept=".pdf,.jpg,.jpeg,.png,.webp,.doc,.docx,.xls,.xlsx"
                    @change="handleFilesChange"
                  />

                  <div v-if="!isKnowledgeSession && attachedFiles.length" class="composer-files-panel">
                      <div class="composer-files-head">
                        <strong>已添加 {{ attachedFiles.length }} 份附件</strong>
                        <div class="composer-files-actions">
                          <button
                            v-if="hiddenAttachedFileCount"
                            type="button"
                            class="composer-file-link"
                            :disabled="submitting || reviewActionBusy"
                            @click="toggleAttachedFilesExpanded"
                          >
                            <i :class="composerFilesExpanded ? 'mdi mdi-chevron-up' : 'mdi mdi-chevron-down'"></i>
                            {{ composerFilesExpanded ? '收起附件' : `展开其余 ${hiddenAttachedFileCount} 份` }}
                          </button>
                          <button
                            type="button"
                            class="composer-file-link danger"
                            :disabled="submitting || reviewActionBusy"
                            @click="clearAttachedFiles"
                          >
                            清空
                          </button>
                        </div>
                      </div>

                      <div class="composer-file-chip-row">
                        <span v-for="file in visibleAttachedFiles" :key="file.name" class="file-chip active composer-file-chip">
                          <i class="mdi mdi-paperclip"></i>
                          <span class="file-chip-label" :title="file.name">{{ file.name }}</span>
                          <button
                            type="button"
                            class="file-chip-remove"
                            :disabled="submitting || reviewActionBusy"
                            :aria-label="`移除 ${file.name}`"
                            @click="removeAttachedFile(file)"
                          >
                            <i class="mdi mdi-close"></i>
                          </button>
                        </span>

                        <button
                          v-if="hiddenAttachedFileCount"
                          type="button"
                          class="file-chip active summary"
                          :disabled="submitting || reviewActionBusy"
                          @click="toggleAttachedFilesExpanded"
                        >
                          <i class="mdi mdi-file-multiple-outline"></i>
                          另外 {{ hiddenAttachedFileCount }} 份
                        </button>
                      </div>

                      <div v-if="composerFilesExpanded && hiddenAttachedFileCount" class="composer-files-expanded">
                        <article
                          v-for="file in attachedFiles.slice(visibleAttachedFiles.length)"
                          :key="`${file.name}-expanded`"
                          class="composer-expanded-file"
                        >
                          <div class="composer-expanded-file-copy">
                            <i class="mdi mdi-file-document-outline"></i>
                            <span :title="file.name">{{ file.name }}</span>
                          </div>
                          <button
                            type="button"
                            class="composer-expanded-file-remove"
                            :disabled="submitting || reviewActionBusy"
                            :aria-label="`移除 ${file.name}`"
                            @click="removeAttachedFile(file)"
                          >
                            <i class="mdi mdi-close"></i>
                          </button>
                        </article>
                      </div>
                    </div>

                  <div v-if="isStewardSession" class="composer-row steward-composer-row">
                    <div class="composer-leading-actions steward-composer-leading-actions">
                      <button
                        type="button"
                        class="tool-btn composer-side-btn"
                        :disabled="submitting || reviewActionBusy || sessionSwitchBusy"
                        aria-label="上传附件"
                        title="上传附件"
                        @click="triggerFileUpload"
                      >
                        <i class="mdi mdi-paperclip"></i>
                      </button>
                    </div>

                    <div class="composer-shell steward-composer-shell">
                      <div class="composer-shell-body">
                        <textarea
                          ref="composerTextareaRef"
                          v-model="composerDraft"
                          rows="1"
                          :placeholder="composerPlaceholder"
                          :disabled="submitting || reviewActionBusy || sessionSwitchBusy"
                          @input="handleComposerInput"
                          @keydown.enter.exact.prevent="handleComposerEnter"
                          @keydown.ctrl.enter.prevent="submitComposer"
                        />
                      </div>
                    </div>

                    <button class="send-btn composer-side-btn" type="submit" :disabled="!canSubmit || reviewActionBusy || sessionSwitchBusy" aria-label="发送">
                      <i :class="submitting ? 'mdi mdi-loading mdi-spin' : 'mdi mdi-send'"></i>
                    </button>
                  </div>

                  <div v-else class="composer-row" :class="{ 'knowledge-mode': isKnowledgeSession }">
                    <div v-if="!isKnowledgeSession" class="composer-leading-actions">
                      <button
                        type="button"
                        class="tool-btn composer-side-btn"
                        :disabled="submitting || reviewActionBusy || sessionSwitchBusy"
                        aria-label="上传附件"
                        @click="triggerFileUpload"
                      >
                        <i class="mdi mdi-paperclip"></i>
                      </button>
                      <div class="composer-date-anchor">
                        <button
                          type="button"
                          class="tool-btn composer-side-btn"
                          :class="{ active: composerDatePickerOpen }"
                          :disabled="submitting || reviewActionBusy || sessionSwitchBusy"
                          aria-label="选择日期"
                          :aria-expanded="composerDatePickerOpen"
                          @click.stop="toggleComposerDatePicker"
                        >
                          <i class="mdi mdi-calendar-range"></i>
                        </button>
                        <div
                          v-if="composerDatePickerOpen"
                          class="composer-date-popover"
                          role="dialog"
                          aria-label="日期选择"
                          @click.stop
                        >
                          <div class="composer-date-mode-tabs">
                            <button
                              type="button"
                              class="composer-date-mode-btn"
                              :class="{ active: composerDateMode === 'single' }"
                              @click="setComposerDateMode('single')"
                            >
                              当天
                            </button>
                            <button
                              type="button"
                              class="composer-date-mode-btn"
                              :class="{ active: composerDateMode === 'range' }"
                              @click="setComposerDateMode('range')"
                            >
                              时间段
                            </button>
                          </div>
                          <div v-if="composerDateMode === 'single'" class="composer-date-fields">
                            <label class="composer-date-field">
                              <span>日期</span>
                              <input v-model="composerSingleDate" type="date" @change="handleComposerDateInputChange('single')" />
                            </label>
                          </div>
                          <div v-else class="composer-date-fields composer-date-fields-range">
                            <label class="composer-date-field">
                              <span>开始</span>
                              <input v-model="composerRangeStartDate" type="date" @change="handleComposerDateInputChange('range-start')" />
                            </label>
                            <span class="composer-date-range-sep">至</span>
                            <label class="composer-date-field">
                              <span>结束</span>
                              <input
                                v-model="composerRangeEndDate"
                                type="date"
                                :min="composerRangeStartDate"
                                @change="handleComposerDateInputChange('range-end')"
                              />
                            </label>
                          </div>
                          <p v-if="composerDateMode === 'range' && !composerCanApplyDateSelection" class="composer-date-hint">
                            请确认结束日期不早于开始日期。
                          </p>
                        </div>
                      </div>
                      <div v-if="canShowTravelCalculator" class="travel-calculator-anchor">
                        <button
                          type="button"
                          class="tool-btn composer-side-btn travel-calculator-trigger"
                          :class="{ active: travelCalculatorOpen }"
                          :disabled="submitting || reviewActionBusy || sessionSwitchBusy"
                          aria-label="差旅计算器"
                          title="差旅计算器"
                          :aria-expanded="travelCalculatorOpen"
                          @click.stop="toggleTravelCalculator"
                        >
                          <i class="mdi mdi-calculator"></i>
                        </button>
                        <div
                          v-if="travelCalculatorOpen"
                          class="travel-calculator-popover"
                          role="dialog"
                          aria-label="差旅计算器"
                          @click.stop
                        >
                          <div class="travel-calculator-mini-head">
                            <strong>差旅计算器</strong>
                            <span>按规则中心差旅表测算</span>
                          </div>
                          <div class="travel-calculator-form">
                            <label class="travel-calculator-field">
                              <span>实际天数</span>
                              <input
                                v-model="travelCalculatorForm.days"
                                type="number"
                                min="1"
                                step="1"
                                inputmode="numeric"
                                :disabled="travelCalculatorBusy"
                                @keydown.enter.prevent="submitTravelCalculator"
                              />
                            </label>
                            <label class="travel-calculator-field">
                              <span>出差地点</span>
                              <input
                                v-model="travelCalculatorForm.location"
                                type="text"
                                placeholder="例如：北京、成都"
                                :disabled="travelCalculatorBusy"
                                @keydown.enter.prevent="submitTravelCalculator"
                              />
                            </label>
                          </div>
                          <p v-if="travelCalculatorError" class="travel-calculator-error">
                            {{ travelCalculatorError }}
                          </p>
                          <div class="composer-date-popover-actions">
                            <button type="button" class="composer-date-cancel-btn" :disabled="travelCalculatorBusy" @click="closeTravelCalculator">
                              取消
                            </button>
                            <button
                              type="button"
                              class="composer-date-apply-btn"
                              :disabled="!travelCalculatorCanSubmit"
                              @click="submitTravelCalculator"
                            >
                              {{ travelCalculatorBusy ? '计算中...' : 'AI计算' }}
                            </button>
                          </div>
                        </div>
                      </div>
                    </div>

                    <div class="composer-shell">
                      <div class="composer-shell-body">
                        <span
                          v-for="tag in composerBusinessTimeTags"
                          :key="tag.id"
                          class="composer-biz-time-tag"
                        >
                          <i class="mdi mdi-calendar-check"></i>
                          <span class="composer-biz-time-tag-label">{{ tag.label }}</span>
                          <button
                            type="button"
                            class="composer-biz-time-tag-remove"
                            :disabled="submitting || reviewActionBusy || sessionSwitchBusy"
                            aria-label="移除日期"
                            @click="removeComposerBusinessTimeTag(tag.id)"
                          >
                            <i class="mdi mdi-close"></i>
                          </button>
                        </span>
                        <textarea
                          ref="composerTextareaRef"
                          v-model="composerDraft"
                          rows="1"
                          :placeholder="composerPlaceholder"
                          :disabled="submitting || reviewActionBusy || sessionSwitchBusy"
                          @input="handleComposerInput"
                          @keydown.enter.exact.prevent="handleComposerEnter"
                          @keydown.ctrl.enter.prevent="submitComposer"
                        />
                      </div>
                    </div>

                    <button class="send-btn composer-side-btn" type="submit" :disabled="!canSubmit || reviewActionBusy || sessionSwitchBusy" aria-label="发送">
                      <i :class="submitting ? 'mdi mdi-loading mdi-spin' : 'mdi mdi-send'"></i>
                    </button>
                  </div>
                </form>
              </section>

              <Transition name="el-fade-in-linear" appear>
                <TravelReimbursementInsightPanel
                  v-if="hasInsightPanelContent"
                  :ui="insightPanelUi"
                />
              </Transition>

            </div>
          </div>
    </section>
  </el-dialog>

    <ConfirmDialog
      :open="deleteSessionDialogOpen"
      badge="删除会话"
      badge-tone="danger"
      title="确认删除当前会话内容？"
      description="删除后将清空当前类型会话下的全部对话内容，且无法恢复。"
      cancel-text="取消"
      confirm-text="确认删除"
      busy-text="删除中..."
      confirm-tone="danger"
      confirm-icon="mdi mdi-delete-outline"
      :busy="deleteSessionBusy"
      @close="closeDeleteSessionDialog"
      @confirm="confirmDeleteCurrentSession"
    />

    <ConfirmDialog
      :open="applicationSubmitConfirmDialog.open"
      badge="提交确认"
      badge-tone="primary"
      title="确认提交当前费用申请？"
      description="提交后申请将进入领导审核流程，请确认关键申请信息和预计费用已经核对无误。"
      cancel-text="再检查一下"
      confirm-text="确认提交"
      busy-text="提交中..."
      confirm-tone="primary"
      confirm-icon="mdi mdi-send-check-outline"
      :busy="reviewActionBusy"
      @close="closeApplicationSubmitConfirm"
      @confirm="confirmApplicationSubmit"
    />

    <ConfirmDialog
      :open="nextStepConfirmDialog.open"
      badge="提交确认"
      badge-tone="primary"
      title="确认提交当前单据？"
      description="提交后单据将进入审批流程，请确认关键信息、票据和风险提示已经核对无误。"
      cancel-text="再检查一下"
      confirm-text="确认提交"
      busy-text="提交中..."
      confirm-tone="primary"
      confirm-icon="mdi mdi-send-check-outline"
      :busy="reviewActionBusy"
      @close="closeReviewNextStepConfirm"
      @confirm="confirmReviewNextStepSubmit"
    />

    <Teleport to="body">
      <Transition name="assistant-modal">
        <div v-if="documentPreviewDialog.open" class="assistant-overlay review-overlay">
        <section class="review-preview-modal">
          <header class="review-preview-head">
            <div>
              <span class="assistant-badge">票据原图</span>
              <h3>{{ documentPreviewDialog.filename }}</h3>
            </div>
            <button class="close-btn" type="button" aria-label="关闭原图预览" @click="closeDocumentPreview">
              <i class="mdi mdi-close"></i>
            </button>
          </header>

          <div class="review-preview-body" :class="documentPreviewDialog.kind">
            <img
              v-if="documentPreviewDialog.kind === 'image'"
              :key="documentPreviewDialog.renderKey"
              :src="documentPreviewDialog.url"
              :alt="documentPreviewDialog.filename"
            />
            <iframe
              v-else-if="documentPreviewDialog.kind === 'pdf'"
              :key="documentPreviewDialog.renderKey"
              :src="documentPreviewDialog.url"
              title="票据 PDF 原图预览"
            ></iframe>
            <div v-else class="review-side-empty">
              <span class="review-side-empty-icon">
                <i class="mdi mdi-file-outline"></i>
              </span>
              <strong>当前文件暂不支持内置预览</strong>
              <p>请重新上传图片或 PDF 票据，以便在这里查看原图。</p>
            </div>
          </div>
        </section>
        </div>
      </Transition>

    </Teleport>
</template>

<script src="./scripts/TravelReimbursementCreateView.js"></script>

<style scoped src="../assets/styles/views/travel-reimbursement-create-view.css"></style>
<style scoped src="../assets/styles/views/travel-reimbursement-create-view-part2.css"></style>
<style scoped src="../assets/styles/views/travel-reimbursement-create-view-part3.css"></style>
<style scoped src="../assets/styles/views/travel-reimbursement-create-view-part4.css"></style>
