<template>
	<cl-page :title="'\u5468\u62a5\u8BE6\u60C5'">
		<view v-if="loading" class="flex justify-center items-center py-20">
			<cl-loading />
		</view>

		<view v-else-if="report" class="p-4">
			<!-- header -->
			<view class="mb-6">
				<view class="flex justify-between items-center mb-2">
					<text class="text-2xl font-bold">{{ formatWeekRange(report.weekStartDate, report.weekEndDate) }}</text>
					<cl-tag :type="report.status === 1 ? 'success' : 'warning'">{{ report.status === 1 ? '\u5DF2\u63D0\u4EA4' : '\u8349\u7A3F' }}</cl-tag>
				</view>
				<text class="text-sm text-gray-500">{{ report.submitTime ? ('\u63D0\u4EA4\u4E8E ' + formatDateTime(report.submitTime)) : ('\u521B\u5EFA\u4E8E ' + formatDateTime(report.createTime)) }}</text>
			</view>

			<!-- body content -->
			<view class="mb-6">
				<text class="text-base font-bold mb-3 block">{{ '\u5468\u62A5\u5185\u5BB9' }}</text>
				<view class="p-4 bg-white rounded-lg shadow-sm">
					<text class="text-sm text-gray-800">{{ report.userEditedContent || '\u6682\u65E0\u5185\u5BB9' }}</text>
				</view>
			</view>

			<!-- original and ai sections (no cl-collapse) -->
			<view v-if="report.originalText" class="mb-4">
				<text class="text-base font-bold mb-2">{{ '\u539F\u59CB\u8F93\u5165\u5185\u5BB9' }}</text>
				<view class="p-3 bg-gray-50 rounded">
					<text class="text-sm text-gray-700">{{ report.originalText }}</text>
				</view>
			</view>

			<view v-if="report.aiFormattedContent" class="mb-4">
				<text class="text-base font-bold mb-2">{{ 'AI\u751F\u6210\u5185\u5BB9' }}</text>
				<view class="p-3 bg-blue-50 rounded">
					<text class="text-sm text-gray-800">{{ report.aiFormattedContent }}</text>
				</view>
			</view>

			<!-- actions -->
			<view class="flex gap-3 mt-6">
				<cl-button type="primary" size="large" :flex="1" @tap="editReport">{{ '\u7F16\u8F91\u5468\u62A5' }}</cl-button>
				<cl-button v-if="report.status === 0" type="success" size="large" :flex="1" @tap="submitReport" :loading="isSubmitting">{{ isSubmitting ? '\u63D0\u4EA4\u4E2D...' : '\u63D0\u4EA4\u5468\u62A5' }}</cl-button>
			</view>
		</view>

		<view v-else class="flex flex-col items-center justify-center py-20">
			<text class="text-6xl mb-4">{{ '\u270F\uFE0F' }}</text>
			<text class="text-gray-400 text-base">{{ '\u5468\u62A5\u4E0D\u5B58\u5728' }}</text>
			<cl-button type="primary" size="small" class="mt-4" @tap="router.back()">{{ '\u8FD4\u56DE\u5217\u8868' }}</cl-button>
		</view>
	</cl-page>
</template>

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

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

const report = ref<any>(null);
const loading = ref(true);
const isSubmitting = ref(false);
const userId = ref(0);
const reportId = ref('');

onLoad(async (options: any) => {
  reportId.value = (options?.id ?? '').toString();
  if (user.token) {
    try { await user.get(); } catch {}
  }
  if (user.info.value && user.info.value.id) {
    userId.value = user.info.value.id;
  } else {
    ui.showToast({ message: '\u8BF7\u5148\u767B\u5F55', type: 'error' });
    setTimeout(() => router.to('/pages/user/login'), 800);
    loading.value = false;
    return;
  }
  if (reportId.value) {
    await loadReportDetail();
  } else {
    loading.value = false;
  }
});

async function loadReportDetail() {
  loading.value = true;
  try {
    const res = await request({ url: '/app/weeklyreport/report/detail', method: 'GET', params: { id: reportId.value, userId: userId.value } });
    if (res) report.value = res;
  } catch (e: any) {
    ui.showToast({ message: '\u52A0\u8F7D\u5931\u8D25: ' + (e.message || '\u672A\u77E5\u9519\u8BEF'), type: 'error' });
  } finally {
    loading.value = false;
  }
}

function editReport() {
  router.to(`/pages/weeklyreport/submit?id=${reportId.value}`);
}

async function submitReport() {
  if (!report.value) return;
  isSubmitting.value = true;
  try {
    await request({
      url: '/app/weeklyreport/report/submit',
      method: 'POST',
      data: {
        userId: userId.value,
        weekStartDate: report.value.weekStartDate,
        weekEndDate: report.value.weekEndDate,
        originalText: report.value.originalText,
        aiFormattedContent: report.value.aiFormattedContent,
        userEditedContent: report.value.userEditedContent,
        inputType: report.value.inputType
      }
    });
    ui.showToast({ message: '\u5468\u62A5\u63D0\u4EA4\u6210\u529F', type: 'success' });
    setTimeout(() => { loadReportDetail(); }, 700);
  } catch (e: any) {
    ui.showToast({ message: '\u63D0\u4EA4\u5931\u8D25: ' + (e.message || '\u672A\u77E5\u9519\u8BEF'), type: 'error' });
  } finally {
    isSubmitting.value = false;
  }
}

function formatWeekRange(startDate: string, endDate: string) {
  if (!startDate || !endDate) return '';
  const start = new Date(startDate);
  const end = new Date(endDate);
  const sy = start.getFullYear();
  const sm = String(start.getMonth() + 1).padStart(2, '0');
  const sd = String(start.getDate()).padStart(2, '0');
  const ey = end.getFullYear();
  const em = String(end.getMonth() + 1).padStart(2, '0');
  const ed = String(end.getDate()).padStart(2, '0');
  return sy === ey ? `${sy}-${sm}-${sd} ~ ${em}-${ed}` : `${sy}-${sm}-${sd} ~ ${ey}-${em}-${ed}`;
}

function formatDateTime(timeStr: string) {
  if (!timeStr) return '';
  const d = new Date(timeStr);
  const y = d.getFullYear();
  const m = String(d.getMonth() + 1).padStart(2, '0');
  const dd = String(d.getDate()).padStart(2, '0');
  const hh = String(d.getHours()).padStart(2, '0');
  const mm = String(d.getMinutes()).padStart(2, '0');
  return `${y}-${m}-${dd} ${hh}:${mm}`;
}
</script>

<style scoped>
.gap-3 { gap: 0.75rem; }
</style>
