<!-- 研究计划展示/编辑/确认卡片 -->
<template>
  <a-card v-if="plan" class="plan-card" :bordered="false">
    <template v-if="!hideTitle" #title>
      <div class="card-title-row">
        <span>研究计划确认</span>
        <slot
          name="actions"
          :editing="editing"
          :saving="saving"
          :start-edit="startEdit"
          :cancel-edit="cancelEdit"
          :save-edit="saveEdit"
        />
      </div>
    </template>

    <!-- ── Summary ─────────────────────────────────────────────── -->
    <div
      v-if="!editing"
      class="plan-summary"
    >{{ plan.summary }}</div>
    <textarea
      v-else
      v-model="draft.summary"
      class="plan-edit-textarea plan-summary plan-summary--editing"
      rows="3"
      placeholder="计划概述..."
    />

    <!-- ── Grid blocks ──────────────────────────────────────────── -->
    <div class="plan-grid">
      <div class="plan-block">
        <div class="plan-block__title">目标拆解</div>
        <template v-if="!editing">
          <ul><li v-for="item in plan.objectives" :key="item">{{ item }}</li></ul>
        </template>
        <textarea v-else v-model="drafts.objectives" class="plan-edit-textarea" :rows="Math.max(3, draft.objectives.length + 1)" placeholder="每行一条目标..." />
      </div>

      <div class="plan-block">
        <div class="plan-block__title">子问题</div>
        <template v-if="!editing">
          <ul><li v-for="item in plan.subQuestions" :key="item">{{ item }}</li></ul>
        </template>
        <textarea v-else v-model="drafts.subQuestions" class="plan-edit-textarea" :rows="Math.max(3, draft.subQuestions.length + 1)" placeholder="每行一个子问题..." />
      </div>

      <div class="plan-block">
        <div class="plan-block__title">检索重点</div>
        <template v-if="!editing">
          <div class="tag-list">
            <a-tag v-for="item in plan.retrievalFocus" :key="item" color="blue">{{ item }}</a-tag>
          </div>
        </template>
        <textarea v-else v-model="drafts.retrievalFocus" class="plan-edit-textarea" :rows="Math.max(3, draft.retrievalFocus.length + 1)" placeholder="每行一个检索关键词..." />
      </div>

      <div class="plan-block">
        <div class="plan-block__title">章节结构</div>
        <template v-if="!editing">
          <ol><li v-for="item in plan.sectionOutline" :key="item">{{ item }}</li></ol>
        </template>
        <textarea v-else v-model="drafts.sectionOutline" class="plan-edit-textarea" :rows="Math.max(3, draft.sectionOutline.length + 1)" placeholder="每行一个章节标题..." />
      </div>
    </div>

    <!-- ── Footer ───────────────────────────────────────────────── -->
    <div class="plan-footer">
      <div class="plan-block">
        <div class="plan-block__title">交付物</div>
        <template v-if="!editing">
          <div class="tag-list">
            <a-tag v-for="item in plan.expectedDeliverables" :key="item">{{ item }}</a-tag>
          </div>
        </template>
        <textarea v-else v-model="drafts.expectedDeliverables" class="plan-edit-textarea" :rows="Math.max(2, draft.expectedDeliverables.length + 1)" placeholder="每行一项交付物..." />
      </div>

      <div class="plan-block" v-if="plan.notes.length || editing">
        <div class="plan-block__title">风险提示</div>
        <template v-if="!editing">
          <ul><li v-for="item in plan.notes" :key="item">{{ item }}</li></ul>
        </template>
        <textarea v-else v-model="drafts.notes" class="plan-edit-textarea" :rows="Math.max(2, draft.notes.length + 1)" placeholder="每行一条风险提示（可留空）..." />
      </div>
    </div>

    <div v-if="editing" class="plan-edit-hint">
      每个文本框中，每行对应一个条目；空行会被自动忽略。
    </div>
  </a-card>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import { message } from 'ant-design-vue'
import { SaveOutlined } from '@ant-design/icons-vue'
import type { ResearchPlan } from '@/types/research'

const props = defineProps<{
  plan: ResearchPlan | undefined
  /** Record ID — required for saving edits */
  recordId?: string
  /** Hide the card title row (when parent provides its own header, e.g. collapse panel) */
  hideTitle?: boolean
}>()

const emit = defineEmits<{
  (e: 'plan-saved', plan: ResearchPlan): void
}>()

// ── Edit state ────────────────────────────────────────────────────────────────

const editing = ref(false)
const saving = ref(false)

/** Deep clone of the plan being edited */
const draft = reactive<ResearchPlan>({
  summary: '',
  objectives: [],
  subQuestions: [],
  retrievalFocus: [],
  sectionOutline: [],
  expectedDeliverables: [],
  notes: [],
  includedDocIds: [],
  includedMatterIds: [],
})

/**
 * Textarea-bound strings (newline-separated arrays).
 * Two-way: changes to these strings update draft arrays via watchers.
 */
const drafts = reactive({
  objectives: '',
  subQuestions: '',
  retrievalFocus: '',
  sectionOutline: '',
  expectedDeliverables: '',
  notes: '',
})

function arrToText(arr: string[]): string {
  return arr.join('\n')
}

function textToArr(text: string): string[] {
  return text.split('\n').map((s) => s.trim()).filter(Boolean)
}

// Sync drafts → draft arrays
watch(() => drafts.objectives, (v) => { draft.objectives = textToArr(v) })
watch(() => drafts.subQuestions, (v) => { draft.subQuestions = textToArr(v) })
watch(() => drafts.retrievalFocus, (v) => { draft.retrievalFocus = textToArr(v) })
watch(() => drafts.sectionOutline, (v) => { draft.sectionOutline = textToArr(v) })
watch(() => drafts.expectedDeliverables, (v) => { draft.expectedDeliverables = textToArr(v) })
watch(() => drafts.notes, (v) => { draft.notes = textToArr(v) })

function startEdit() {
  if (!props.plan) return
  // Deep copy plan → draft
  draft.summary = props.plan.summary
  draft.objectives = [...props.plan.objectives]
  draft.subQuestions = [...props.plan.subQuestions]
  draft.retrievalFocus = [...props.plan.retrievalFocus]
  draft.sectionOutline = [...props.plan.sectionOutline]
  draft.expectedDeliverables = [...props.plan.expectedDeliverables]
  draft.notes = [...props.plan.notes]
  draft.includedDocIds = [...props.plan.includedDocIds]
  draft.includedMatterIds = [...props.plan.includedMatterIds]
  // Sync to textarea strings
  drafts.objectives = arrToText(draft.objectives)
  drafts.subQuestions = arrToText(draft.subQuestions)
  drafts.retrievalFocus = arrToText(draft.retrievalFocus)
  drafts.sectionOutline = arrToText(draft.sectionOutline)
  drafts.expectedDeliverables = arrToText(draft.expectedDeliverables)
  drafts.notes = arrToText(draft.notes)
  editing.value = true
}

function cancelEdit() {
  editing.value = false
}


async function saveEdit() {
  if (!props.recordId) {
    message.error('缺少记录 ID，无法保存')
    return
  }
  saving.value = true
  try {
    const { updateRecordPlan } = await import('@/api/researchRecords')
    const updated: ResearchPlan = {
      summary: draft.summary.trim(),
      objectives: draft.objectives,
      subQuestions: draft.subQuestions,
      retrievalFocus: draft.retrievalFocus,
      sectionOutline: draft.sectionOutline,
      expectedDeliverables: draft.expectedDeliverables,
      notes: draft.notes,
      includedDocIds: draft.includedDocIds,
      includedMatterIds: draft.includedMatterIds,
    }
    await updateRecordPlan(props.recordId, updated)
    emit('plan-saved', updated)
    editing.value = false
    message.success('研究计划已保存')
  } catch (err: any) {
    message.error(err?.response?.data?.detail || '保存失败，请重试')
  } finally {
    saving.value = false
  }
}
</script>

<style scoped lang="less">
.plan-card {
  border-radius: 18px;
  box-shadow: 0 10px 40px rgba(14, 30, 62, 0.06);
}

.card-title-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
}

.plan-summary {
  margin-bottom: 16px;
  padding: 14px 16px;
  border-radius: 14px;
  background: #f7fbff;
  color: #1f1f1f;
  line-height: 1.7;

  &--editing {
    background: #fff;
    border: 1.5px solid #4096ff;
    outline: none;
    width: 100%;
    box-sizing: border-box;
    resize: vertical;
  }
}

.plan-grid {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 16px;
}

.plan-block {
  padding: 14px;
  border-radius: 14px;
  background: #fafbfc;
}

.plan-block__title {
  margin-bottom: 10px;
  font-size: 13px;
  font-weight: 600;
  color: #1f1f1f;
}

.plan-block ul,
.plan-block ol {
  margin: 0;
  padding-left: 20px;
}

.plan-block li { margin-bottom: 6px; line-height: 1.6; }

.plan-footer {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 16px;
  margin-top: 16px;
}

.tag-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

/* Shared textarea style for all editable array/text fields */
.plan-edit-textarea {
  width: 100%;
  box-sizing: border-box;
  padding: 8px 10px;
  font-size: 13px;
  line-height: 1.65;
  color: rgba(0, 0, 0, 0.88);
  border: 1.5px solid #d9d9d9;
  border-radius: 8px;
  background: #fff;
  resize: vertical;
  outline: none;
  font-family: inherit;
  transition: border-color 0.2s;

  &:focus {
    border-color: #4096ff;
    box-shadow: 0 0 0 2px rgba(5, 145, 255, 0.1);
  }
}

.plan-edit-hint {
  margin-top: 12px;
  font-size: 12px;
  color: rgba(0, 0, 0, 0.35);
  text-align: center;
}

@media (max-width: 1200px) {
  .plan-grid, .plan-footer { grid-template-columns: 1fr; }
}
</style>
