<template>
	<cl-page title="我的月报">
		<view class="p-4">
			<!-- 筛选 -->
			<view class="flex items-center gap-3 mb-4">
				<cl-segmented
					v-model="filterType"
					:list="[
						{ label: '全部', value: 'all' },
						{ label: '草稿', value: 'draft' },
						{ label: '已提交', value: 'submitted' }
					]"
				/>
				<cl-button size="small" @tap="refresh">刷新</cl-button>
			</view>

			<!-- 列表 -->
			<scroll-view scroll-y style="height: calc(100vh - 160px)" @scrolltolower="loadMore">
				<view v-if="list.length > 0">
					<view v-for="item in list" :key="item.id" class="p-4 mb-3 bg-white rounded-2xl" @tap="toDetail(item)">
						<view class="flex items-center justify-between mb-1">
							<text class="text-base font-bold">{{ item.month }}</text>
							<view
								:class="[
									'px-2 py-1 rounded text-xs',
									item.status === 1 ? 'bg-green-100 text-green-700' : 'bg-yellow-100 text-yellow-700'
								]"
							>
								{{ item.status === 1 ? "已提交" : "草稿" }}
							</view>
						</view>
						<text class="text-gray-500 text-sm">{{ brief(item.userEditedContent || item.aiFormattedContent || item.originalText) }}</text>
						<view class="text-xs text-gray-400 mt-2">
							<text v-if="item.submitTime">提交于 {{ formatTime(item.submitTime) }}</text>
							<text v-else-if="item.createTime">创建于 {{ formatTime(item.createTime) }}</text>
						</view>
					</view>
					<view v-if="loading" class="flex items-center justify-center py-3">
						<text class="text-gray-400">加载中...</text>
					</view>
					<view v-else-if="finished" class="flex items-center justify-center py-3">
						<text class="text-gray-400">没有更多了</text>
					</view>
				</view>
				<view v-else class="flex flex-col items-center justify-center py-20">
					<text class="text-6xl mb-3">📅</text>
					<text class="text-gray-400">暂无月报</text>
					<view class="mt-4 px-4 py-2 bg-blue-500 text-white rounded" @tap="toSubmit">
						<text>去提交月报</text>
					</view>
				</view>
			</scroll-view>

			<!-- 悬浮提交按钮 -->
			<view class="fixed bottom-20 right-4">
				<cl-button type="primary" size="large" round @tap="toSubmit">
					<text class="text-2xl">✏️</text>
				</cl-button>
			</view>
		</view>
	</cl-page>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { request, router, useStore } from '@/cool';
import { useUi } from '@/uni_modules/cool-ui';

const ui = useUi();
const { user } = useStore();

const list = ref<any[]>([]);
const loading = ref(false);
const finished = ref(false);
const page = ref(1);
const pageSize = ref(20);
const filterType = ref<'all' | 'draft' | 'submitted'>('all');
const userId = ref(0);

onMounted(async () => {
  if (user.token) {
    try { await user.get(); } catch {}
  }
  if (user.info.value?.id) {
    userId.value = user.info.value.id;
    loadReports();
  } else {
    ui.showToast({ message: '请先登录', type: 'error' });
    setTimeout(() => router.to('/pages/user/login'), 1000);
  }
});

function brief(s: string = '') {
  const t = s.replace(/\n/g, ' ');
  return t.length > 60 ? t.slice(0, 60) + '…' : t;
}

function statusClass(status: number) {
  return status === 1 ? 'text-green-600' : 'text-orange-500';
}

function statusText(status: number) {
  return status === 1 ? '已提交' : '草稿';
}

function formatTime(v: string) {
  try {
    const d = new Date(v);
    const Y = d.getFullYear();
    const M = String(d.getMonth() + 1).padStart(2, '0');
    const D = String(d.getDate()).padStart(2, '0');
    const h = String(d.getHours()).padStart(2, '0');
    const m = String(d.getMinutes()).padStart(2, '0');
    const s = String(d.getSeconds()).padStart(2, '0');
    return `${Y}-${M}-${D} ${h}:${m}:${s}`;
  } catch (e) { return v; }
}

async function loadReports() {
  if (loading.value || finished.value) return;
  loading.value = true;
  try {
    const params: any = { userId: userId.value, page: page.value, size: pageSize.value };
    if (filterType.value === 'draft') params.status = 0;
    if (filterType.value === 'submitted') params.status = 1;
    const res = await request({ url: '/app/monthlyreport/report/myReports', method: 'GET', params });
    if (res && res.length > 0) {
      if (page.value === 1) list.value = res; else list.value.push(...res);
      if (res.length < pageSize.value) finished.value = true;
      page.value++;
    } else {
      if (page.value === 1) list.value = [];
      finished.value = true;
    }
  } catch (e: any) {
    ui.showToast({ message: e.message || '加载失败', type: 'error' });
  } finally {
    loading.value = false;
  }
}

function loadMore() { loadReports(); }

function refresh() {
  page.value = 1; finished.value = false; list.value = []; loadReports();
}

function toSubmit() { router.to('/pages/monthlyreport/submit'); }
function toDetail(item: any) { router.to(`/pages/monthlyreport/detail?id=${item.id}`); }
</script>

<style scoped></style>
