<template>
  <section class="skill-center">
    <Transition name="skill-view" mode="out-in">
      <article
        v-if="selectedSkill"
        key="detail"
        class="skill-detail"
        :class="{
          'spreadsheet-skill-detail': selectedSkill.usesSpreadsheetRule,
          'json-risk-skill-detail': selectedSkill.usesJsonRiskRule
        }"
      >
        <div class="detail-scroll">
          <section v-if="detailError" class="detail-inline-state panel error">
            <i class="mdi mdi-alert-circle-outline"></i>
            <div>
              <strong>资产详情加载失败</strong>
              <p>{{ detailError }}</p>
            </div>
          </section>

          <TableLoadingState
            v-else-if="detailLoading && selectedSkill.loading"
            class="detail-loading-state panel"
            variant="panel"
            title="正在加载资产详情"
            message="列表数据已就绪，正在补充版本、审核和运行信息"
            icon="mdi mdi-file-document-outline"
            :show-skeleton="false"
          />

          <AuditSpreadsheetRuleDetail
            v-else-if="selectedSkill.usesSpreadsheetRule"
            ref="spreadsheetUploadInput"
            :selected-skill="selectedSkill"
            :selected-spreadsheet-file-name="selectedSpreadsheetFileName"
            :selected-spreadsheet-change-records="selectedSpreadsheetChangeRecords"
            :spreadsheet-only-office-host-id="spreadsheetOnlyOfficeHostId"
            :spreadsheet-only-office-ready="spreadsheetOnlyOfficeReady"
            :spreadsheet-only-office-error="spreadsheetOnlyOfficeError"
            :spreadsheet-only-office-loading="spreadsheetOnlyOfficeLoading"
            :can-edit-spreadsheet-inline="canEditSpreadsheetInline"
            @file-change="handleSpreadsheetFileInput"
            @open-spreadsheet-change-detail="openSpreadsheetChangeDetail"
          />

          <AuditJsonRiskRuleDetail
            v-else-if="selectedSkill.usesJsonRiskRule"
            :selected-skill="selectedSkill"
            :risk-rule-test-passed="riskRuleTestPassed"
            :release-state="releaseState"
            :release-queue="releaseQueue"
            :release-loading="releaseLoading"
            :release-error="releaseError"
            :release-action="releaseAction"
            :can-review-release="canManageSelected"
            @refresh-release="loadReleaseMonitor"
            @label-release="submitReleaseLabel"
          />

          <div
            v-else
            class="detail-grid"
            :class="{
              'skill-md-detail-grid': selectedSkill.type === 'rules' && !selectedSkill.usesSpreadsheetRule,
              'spreadsheet-detail-grid': selectedSkill.usesSpreadsheetRule
            }"
          >
            <section class="detail-main">
              <article
                v-if="selectedSkill.type === 'rules' && !selectedSkill.usesSpreadsheetRule"
                class="detail-card panel markdown-card"
              >
                <div class="card-head">
                  <div>
                    <h3>Markdown 规则内容</h3>
                    <p>当前展示版本：{{ selectedSkill.displayVersion }}，规则说明与运行时 JSON 分开编辑，但保存时会一起进入版本快照。</p>
                  </div>
                  <button
                    class="mini-btn primary"
                    type="button"
                    :disabled="!canEditMarkdown || detailBusy"
                    @click="saveRuleMarkdown"
                  >
                    <i class="mdi mdi-content-save-outline"></i>
                    <span>{{ actionState === 'save-markdown' ? '保存中...' : '保存 Markdown' }}</span>
                  </button>
                </div>

                <TableLoadingState
                  v-if="detailLoading"
                  class="subtle-banner"
                  variant="banner"
                  tone="sky"
                  message="正在刷新规则详情"
                  icon="mdi mdi-refresh"
                  :show-skeleton="false"
                />

                <label class="field">
                  <span>{{ selectedSkill.code }}</span>
                  <textarea
                    v-model="selectedSkill.markdownContent"
                    class="markdown-editor"
                    :class="{ disabled: !canEditMarkdown }"
                    spellcheck="false"
                    :readonly="!canEditMarkdown || detailBusy"
                  ></textarea>
                </label>

                <div class="editor-foot">
                  <span>版本说明：{{ selectedSkill.displayVersionChangeNote }}</span>
                  <span>最近保存：{{ selectedSkill.updatedAt }}</span>
                </div>

                <div v-if="!canEditMarkdown" class="review-note-block muted">
                  <strong>只读模式</strong>
                  <p>当前账号没有规则编辑权限，Markdown 仅可查看。</p>
                </div>
              </article>

              <article
                v-if="selectedSkill.type === 'rules' && !selectedSkill.usesSpreadsheetRule"
                class="detail-card panel json-editor-card"
              >
                <div class="card-head">
                  <div>
                    <h3>运行时 JSON</h3>
                    <p>编辑规则中心实际消费的 `config_json.runtime_rule`，保存时会同步写入配置并追加到 Markdown 版本快照。</p>
                  </div>
                  <button
                    class="mini-btn"
                    type="button"
                    :disabled="!canEditMarkdown || detailBusy"
                    @click="saveRuleRuntimeJson"
                  >
                    <i class="mdi mdi-code-json"></i>
                    <span>{{ actionState === 'save-runtime-json' ? '保存中...' : '保存 JSON' }}</span>
                  </button>
                </div>

                <div class="json-template-meta">
                  <span>
                    <strong>模板</strong>
                    {{ selectedSkill.ruleTemplateLabel }}
                  </span>
                  <span>
                    <strong>模板键</strong>
                    {{ selectedSkill.ruleTemplateKey || '未指定' }}
                  </span>
                  <span>
                    <strong>运行时类型</strong>
                    {{ selectedSkill.runtimeKind || 'policy_rule_draft' }}
                  </span>
                </div>

                <label class="field">
                  <span>config_json.runtime_rule</span>
                  <textarea
                    v-model="selectedSkill.runtimeRuleText"
                    class="json-editor"
                    :class="{ disabled: !canEditMarkdown }"
                    spellcheck="false"
                    :readonly="!canEditMarkdown || detailBusy"
                  ></textarea>
                </label>

                <div class="editor-foot">
                  <span>JSON 必须是对象；保存后会同步写入资产配置，并以 `expense-rule` 代码块落到版本历史里。</span>
                  <span>当前展示版本：{{ selectedSkill.displayVersion }}</span>
                </div>

                <div v-if="!canEditMarkdown" class="review-note-block muted">
                  <strong>只读模式</strong>
                  <p>当前账号没有规则编辑权限，运行时 JSON 仅可查看。</p>
                </div>
              </article>

              <article class="detail-card panel">
                <div class="card-head">
                  <div>
                    <h3>{{ selectedSkill.configTitle }}</h3>
                    <p>{{ selectedSkill.configDesc }}</p>
                  </div>
                  <span class="edit-badge">{{ selectedSkill.version }}</span>
                </div>

                <div class="form-grid">
                  <label v-for="field in selectedSkill.fields" :key="field.label" class="field">
                    <span>{{ field.label }}</span>
                    <input :value="field.value" readonly />
                  </label>
                  <label class="field span-2">
                    <span>适用场景</span>
                    <textarea rows="3" :value="selectedSkill.scope" readonly></textarea>
                  </label>
                </div>
              </article>

              <article v-if="selectedSkill.type !== 'rules'" class="detail-card panel">
                <div class="card-head">
                  <div>
                    <h3>{{ selectedSkill.detailTitle }}</h3>
                    <p>{{ selectedSkill.detailDesc }}</p>
                  </div>
                  <span class="edit-badge">{{ selectedSkill.promptSections.length }} 段</span>
                </div>

                <div class="prompt-stack">
                  <section
                    v-for="section in selectedSkill.promptSections"
                    :key="section.title"
                    class="prompt-block"
                  >
                    <header>
                      <strong>{{ section.title }}</strong>
                      <span>{{ section.intent }}</span>
                    </header>
                    <textarea rows="5" :value="section.content" readonly></textarea>
                  </section>
                </div>
              </article>

              <article class="detail-card panel">
                <div class="card-head">
                  <div>
                    <h3>{{ selectedSkill.outputTitle }}</h3>
                    <p>{{ selectedSkill.outputDesc }}</p>
                  </div>
                  <span class="edit-badge">
                    {{ selectedSkill.type === 'rules' ? selectedSkill.reviewStatusLabel : selectedSkill.publishState }}
                  </span>
                </div>

                <div class="contract-grid">
                  <div class="contract-panel">
                    <h4>{{ selectedSkill.ruleListTitle }}</h4>
                    <ul>
                      <li v-for="rule in selectedSkill.outputRules" :key="rule">{{ rule }}</li>
                    </ul>
                  </div>

                  <div class="contract-panel">
                    <h4>{{ selectedSkill.checkListTitle }}</h4>
                    <div v-for="test in selectedSkill.tests" :key="test.name" class="test-row">
                      <div>
                        <strong>{{ test.name }}</strong>
                        <span>{{ test.input }}</span>
                      </div>
                      <b :class="['test-state', test.tone]">{{ test.result }}</b>
                    </div>
                  </div>
                </div>
              </article>
            </section>

            <aside v-if="selectedSkill.type === 'rules'" class="detail-side skill-review-side">
              <article class="side-card panel review-card">
                <div class="card-head">
                  <div>
                    <h3>版本信息</h3>
                    <p>最近 5 个规则版本，仅切换当前展示内容。</p>
                  </div>
                </div>

                <div v-if="selectedSkill.history.length" class="version-list">
                  <div
                    v-for="item in selectedSkill.history.slice(0, 5)"
                    :key="item.version + item.time"
                    class="version-row"
                    :class="{ active: item.version === selectedSkill.displayVersion }"
                  >
                    <button class="version-main" type="button" @click="openVersionSwitch(item)">
                      <div class="version-row-head">
                        <strong>{{ item.version }}</strong>
                        <span class="version-current-slot">
                          <b v-if="item.isPublished" class="current-version">线上</b>
                          <b v-else-if="item.isWorking" class="current-version working">工作</b>
                        </span>
                        <span>{{ item.time }}</span>
                      </div>
                      <p>{{ item.note }}</p>
                    </button>
                    <div class="version-row-foot">
                      <b :class="['version-state', item.lifecycleMeta.tone]">
                        {{ item.lifecycleMeta.label }}
                      </b>
                      <button
                        v-if="canManageSelected && !item.isWorking"
                        class="version-restore-btn"
                        type="button"
                        :disabled="detailBusy"
                        @click.stop="restoreSelectedVersion(item.version)"
                      >
                        {{ actionState === `restore-${item.version}` ? '恢复中...' : '恢复为工作稿' }}
                      </button>
                    </div>
                  </div>
                </div>

                <div v-else class="empty-side-note">
                  <i class="mdi mdi-history"></i>
                  <span>暂无版本历史</span>
                </div>
              </article>
            </aside>

            <aside v-else class="detail-side">

              <article class="side-card panel">
                <div class="card-head">
                  <div>
                    <h3>{{ selectedSkill.toolTitle }}</h3>
                    <p>{{ selectedSkill.toolDesc }}</p>
                  </div>
                </div>
                <div v-if="selectedSkill.tools.length" class="tool-list">
                  <div v-for="tool in selectedSkill.tools" :key="tool.name + tool.scope" class="tool-row">
                    <div>
                      <strong>{{ tool.name }}</strong>
                      <span>{{ tool.scope }}</span>
                    </div>
                    <b :class="['tool-state', tool.tone]">{{ tool.mode }}</b>
                  </div>
                </div>
                <div v-else class="empty-side-note">
                  <i class="mdi mdi-connection"></i>
                  <span>暂无依赖信息</span>
                </div>
              </article>

              <article class="side-card panel">
                <div class="card-head">
                  <div>
                    <h3>{{ selectedSkill.historyTitle }}</h3>
                    <p>{{ selectedSkill.historyDesc }}</p>
                  </div>
                </div>
                <div v-if="selectedSkill.history.length" class="history-list">
                  <div v-for="item in selectedSkill.history" :key="item.version + item.time" class="history-row">
                    <strong>{{ item.version }}</strong>
                    <span>{{ item.note }}</span>
                    <small>{{ item.time }}</small>
                  </div>
                </div>
                <div v-else class="empty-side-note">
                  <i class="mdi mdi-clock-outline"></i>
                  <span>暂无版本记录</span>
                </div>
              </article>

              <article class="side-card panel publish-card">
                <div>
                  <h3>{{ selectedSkill.publishTitle }}</h3>
                  <p>{{ selectedSkill.publishDesc }}</p>
                </div>
                <div class="publish-summary">
                  <span>{{ selectedSkill.publishMeta }}</span>
                  <strong>{{ selectedSkill.publishState }}</strong>
                </div>
              </article>
            </aside>
          </div>
        </div>

        <footer class="detail-actions">
          <button class="back-action" type="button" @click="closeDetail">
            <i class="mdi mdi-arrow-left"></i>
            <span>返回能力列表</span>
          </button>

          <div v-if="selectedSkillIsRule" class="detail-action-group">
            <template v-if="selectedSkillUsesJsonRisk">
              <button
                v-if="riskRuleHasPublishableRevision"
                class="minor-action primary-action"
                type="button"
                :disabled="!canPublishRiskRule || detailBusy"
                @click="openPublishRiskRuleDialog"
              >
                <i class="mdi mdi-rocket-launch-outline"></i>
                <span>发布修订</span>
              </button>
              <button
                v-if="canToggleRiskRuleEnabled"
                class="minor-action enable-action"
                :class="{ 'is-on': selectedSkill.isOnlineValue }"
                type="button"
                :disabled="detailBusy"
                @click="toggleSelectedRiskRuleEnabled"
              >
                <i :class="selectedSkill.isOnlineValue ? 'mdi mdi-toggle-switch' : 'mdi mdi-toggle-switch-off-outline'"></i>
                <span>{{ selectedSkill.isOnlineValue ? '已上线' : '已下线' }}</span>
              </button>
              <button
                v-if="canOpenRiskRuleTest"
                class="minor-action"
                type="button"
                :disabled="detailBusy"
                @click="openRiskRuleTestDialog"
              >
                <i class="mdi mdi-flask-outline"></i>
                <span>测试规则</span>
              </button>
              <button
                v-if="canEditRiskRuleDraft"
                class="minor-action"
                type="button"
                :disabled="detailBusy"
                @click="openRiskRuleEditDialog('draft')"
              >
                <i class="mdi mdi-square-edit-outline"></i>
                <span>编辑规则</span>
              </button>
              <button
                v-if="canCreateRiskRuleRevision"
                class="minor-action"
                type="button"
                :disabled="detailBusy"
                @click="openRiskRuleEditDialog('revision')"
              >
                <i class="mdi mdi-source-branch-plus"></i>
                <span>创建修订版本</span>
              </button>
              <button
                v-if="canDeleteRiskRule"
                class="minor-action danger-action"
                type="button"
                :disabled="detailBusy"
                @click="openDeleteRiskRuleDialog"
                title="删除未发布规则"
              >
                <i class="mdi mdi-delete-outline"></i>
                <span>删除规则</span>
              </button>
            </template>
            <button
              v-else-if="selectedSkill.usesSpreadsheetRule"
              class="minor-action"
              type="button"
              :disabled="!canDownloadSpreadsheet"
              @click="downloadSpreadsheetFile"
            >
              <i class="mdi mdi-file-download-outline"></i>
              <span>{{ actionState === 'download-spreadsheet' ? '下载中...' : '下载表格' }}</span>
            </button>
            <button
              v-if="selectedSkill.usesSpreadsheetRule"
              class="minor-action"
              type="button"
              :disabled="!canUploadSpreadsheet"
              @click="triggerSpreadsheetUpload"
            >
              <i class="mdi mdi-file-upload-outline"></i>
              <span>{{ actionState === 'upload-spreadsheet' ? '导入中...' : '上传表格' }}</span>
            </button>
            <button
              v-else-if="!selectedSkill.usesSpreadsheetRule && !selectedSkillUsesJsonRisk"
              class="minor-action"
              type="button"
              :disabled="!canEditMarkdown || detailBusy"
              @click="saveRuleMarkdown"
            >
              <i class="mdi mdi-content-save-outline"></i>
              <span>{{ actionState === 'save-markdown' ? '保存中...' : '保存 Markdown' }}</span>
            </button>
          </div>

          <div v-else class="detail-action-group detail-meta-actions">
            <span class="footer-note">{{ selectedSkill.publishMeta }}</span>
          </div>
        </footer>
      </article>

      <AuditAssetList
        v-else
        v-model:active-type="activeType"
        v-model:keyword="keyword"
        :tabs="tabs"
        :active-tab-label="activeTabLabel"
        :search-placeholder="searchPlaceholder"
        :create-button-label="createButtonLabel"
        :hint-text="hintText"
        :table-columns="tableColumns"
        :show-runtime-column="showRuntimeColumn"
        :show-version-column="showVersionColumn"
        :show-metric-column="showMetricColumn"
        :show-status-column="showStatusColumn"
        :show-online-column="showOnlineColumn"
        :show-enabled-column="showEnabledColumn"
        :visible-skills="visibleSkills"
        :audit-empty-state="auditEmptyState"
        :loading="loading"
        :error-message="errorMessage"
        :selected-domain="selectedDomain"
        :selected-owner="selectedOwner"
        :selected-risk-level="selectedRiskLevel"
        :selected-status="selectedStatus"
        :selected-risk-scenario="selectedRiskScenario"
        :selected-online-state="selectedOnlineState"
        :selected-enabled-state="selectedEnabledState"
        :selected-domain-label="selectedDomainLabel"
        :selected-owner-label="selectedOwnerLabel"
        :selected-risk-level-label="selectedRiskLevelLabel"
        :selected-status-label="selectedStatusLabel"
        :selected-risk-scenario-label="selectedRiskScenarioLabel"
        :selected-online-state-label="selectedOnlineStateLabel"
        :selected-enabled-state-label="selectedEnabledStateLabel"
        :show-risk-scenario-filter="showRiskScenarioFilter"
        :show-owner-filter="showOwnerFilter"
        :show-risk-level-filter="showRiskLevelFilter"
        :show-status-filter="showStatusFilter"
        :show-online-filter="showOnlineFilter"
        :show-enabled-filter="showEnabledFilter"
        :domain-options="domainOptions"
        :owner-options="ownerOptions"
        :risk-level-options="riskLevelOptions"
        :status-options="statusOptions"
        :risk-scenario-options="riskScenarioOptions"
        :online-state-options="onlineStateOptions"
        :enabled-state-options="enabledStateOptions"
        :active-filter-popover="activeFilterPopover"
        :active-filter-tokens="activeFilterTokens"
        :can-create-risk-rule="canCreateRiskRule"
        @toggle-filter-popover="toggleFilterPopover"
        @close-filter-popover="closeFilterPopover"
        @select-filter="selectFilter"
        @reset-filters="resetFilters"
        @create-risk-rule="openRiskRuleCreateDialog"
        @empty-action="handleAuditEmptyAction"
        @open-asset-detail="openAssetDetail"
      />
    </Transition>

    <AuditRuleDialogs
      v-model:risk-rule-return-note="riskRuleReturnNote"
      v-model:review-submit-version="reviewSubmitVersion"
      v-model:review-submit-reviewer="reviewSubmitReviewer"
      :selected-skill="selectedSkill"
      :version-switch-target="versionSwitchTarget"
      :action-state="actionState"
      :risk-rule-create-open="riskRuleCreateOpen"
      :risk-rule-create-busy="riskRuleCreateBusy"
      :risk-rule-create-form="riskRuleCreateForm"
      :risk-rule-business-stage-options="riskRuleBusinessStageOptions"
      :risk-rule-expense-category-options="riskRuleExpenseCategoryOptions"
      :risk-rule-attachment-options="riskRuleAttachmentOptions"
      :risk-rule-test-open="riskRuleTestOpen"
      :risk-rule-delete-open="riskRuleDeleteOpen"
      :risk-rule-return-open="riskRuleReturnOpen"
      :risk-rule-publish-open="riskRulePublishOpen"
      :risk-rule-edit-open="riskRuleEditOpen"
      :risk-rule-edit-mode="riskRuleEditMode"
      :risk-rule-edit-form="riskRuleEditForm"
      :risk-rule-edit-busy="actionState === 'save-risk-rule-edit'"
      :risk-rule-test-passed="riskRuleTestPassed"
      :review-submit-open="reviewSubmitOpen"
      :review-submit-reviewer-loading="reviewSubmitReviewerLoading"
      :review-submit-reviewer-options="reviewSubmitReviewerOptions"
      :has-review-submit-reviewers="hasReviewSubmitReviewers"
      :selected-skill-uses-json-risk="selectedSkillUsesJsonRisk"
      @close-risk-rule-create="closeRiskRuleCreateDialog"
      @submit-risk-rule-create="submitRiskRuleCreate"
      @close-risk-rule-test="closeRiskRuleTestDialog"
      @report-saved="handleRiskRuleReportSaved"
      @close-risk-rule-edit="closeRiskRuleEditDialog"
      @submit-risk-rule-edit="submitRiskRuleEdit"
      @close-delete-risk-rule="closeDeleteRiskRuleDialog"
      @delete-selected-risk-rule="deleteSelectedRiskRule"
      @close-return-risk-rule="closeReturnRiskRuleDialog"
      @return-selected-risk-rule="returnSelectedRiskRule"
      @close-publish-risk-rule="closePublishRiskRuleDialog"
      @publish-selected-risk-rule="publishSelectedRiskRule"
      @cancel-version-switch="cancelVersionSwitch"
      @confirm-version-switch="confirmVersionSwitch"
      @close-submit-review="closeSubmitReviewDialog"
      @submit-selected-rule-for-review="submitSelectedRuleForReview"
    />

    <AuditVersionTimelineDrawer
      :open="versionTimelineOpen"
      :loading="versionTimelineLoading"
      :error="versionTimelineError"
      :items="selectedVersionTimelineItems"
      @close="closeVersionTimeline"
    />

    <AuditSpreadsheetChangeDrawer
      :open="spreadsheetChangeDetailOpen"
      :record="selectedSpreadsheetChangeRecord"
      :sheet-rows="selectedSpreadsheetChangeSheetRows"
      :cell-rows="selectedSpreadsheetChangeCellRows"
      @close="closeSpreadsheetChangeDetail"
    />
  </section>
</template>

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

<style scoped src="../assets/styles/views/audit-view.css"></style>
<style scoped src="../assets/styles/views/audit-view-part2.css"></style>
