<script setup lang="ts">
import { onMounted, ref, watch } from "vue";

import { reviewApi, type ReviewNote } from "../../shared/api/review";
import { useMarketStore } from "../../shared/stores/market";
import { useUiStore } from "../../shared/stores/ui";

const props = defineProps<{ code: string; name: string }>();
const market = useMarketStore();
const ui = useUiStore();
const rows = ref<ReviewNote[]>([]);
const content = ref("");
const plan = ref("");
async function load(): Promise<void> { rows.value = await reviewApi.stockNotes(props.code); }
async function save(): Promise<void> {
  try {
    await reviewApi.saveNote({ trade_date: market.selectedDate, code: props.code, stock_name: props.name, summary: "", content: content.value, plan: plan.value });
    ui.showToast("个股复盘笔记已保存"); await load();
  } catch (reason) { ui.showToast(reason instanceof Error ? reason.message : "保存失败"); }
}
async function remove(id: number): Promise<void> { await reviewApi.deleteNote(id); await load(); }
watch(() => props.code, load);
onMounted(load);
</script>

<template>
  <section class="card stock-notes-card"><header class="card-header"><h2>个股复盘笔记</h2><span class="tag">当前账号私有</span></header><form class="stock-note-form" @submit.prevent="save"><label class="field"><span class="field-label">复盘内容</span><textarea v-model="content" class="textarea" maxlength="5000"></textarea></label><label class="field"><span class="field-label">明日计划</span><textarea v-model="plan" class="textarea" maxlength="2000"></textarea></label><div class="form-actions"><button class="btn btn-primary" type="submit">保存笔记</button></div></form><div v-if="rows.length" class="stock-note-history"><article v-for="row in rows" :key="row.id"><time>{{ row.trade_date }}</time><p>{{ row.content }}</p><small>{{ row.plan }}</small><button class="btn btn-small" type="button" @click="remove(row.id)">删除</button></article></div></section>
</template>
