<template>
	<cl-page title="工作建议">
		<view class="p-4">
			<!-- 范围选择 -->
    <!-- 行1：范围 + 周/月 -->
    <view class="flex items-center gap-2 mb-2">
      <text class="label">范围：</text>
      <view class="chip" :class="{ active: scope==='week' }" @tap="setScope('week')">周</view>
      <view class="chip" :class="{ active: scope==='month' }" @tap="setScope('month')">月</view>
    </view>

    <!-- 行2：日期输入 + 刷新（左侧成组，右侧按钮） -->
    <view class="flex items-center justify-between mb-4">
      <view class="flex items-center gap-2 flex-1">
        <template v-if="scope === 'week'">
          <text class="text-gray-500">周起始（周一）：</text>
          <view class="flex-1">
            <cl-input v-model="weekStart" type="date" placeholder="选择本周周一" />
          </view>
        </template>
        <template v-else>
          <text class="text-gray-500">月份（YYYY-MM）：</text>
          <view class="flex-1">
            <cl-input v-model="month" placeholder="例如 2025-11" />
          </view>
        </template>
      </view>
      <cl-button type="primary" size="small" style="margin-left: 5px;" @tap="loadAdvice">刷新</cl-button>
    </view>

			<!-- 建议内容 -->
			<view v-if="loading" class="py-12 text-center text-gray-400">加载中...</view>
			<view v-else>
				<view v-if="adviceText" class="p-4 bg-white rounded-2xl whitespace-pre-wrap">{{ adviceText }}</view>
				<view v-else class="p-8 text-center text-gray-400">{{ emptyText }}</view>
			</view>
		</view>
	</cl-page>
</template>

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

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

const scope = ref<'week' | 'month'>('week');
const weekStart = ref(''); // yyyy-MM-dd（周一）
const month = ref('');     // yyyy-MM
const adviceText = ref('');
const emptyText = ref('暂无建议，请调整时间范围后重试');
const loading = ref(false);

onMounted(async () => {
  if (user.token) { try { await user.get(); } catch {} }
  // 默认周：设置为当前周周一；默认月：当前月
  const today = new Date();
  const monday = new Date(today);
  const day = monday.getDay();
  const diff = (day === 0 ? -6 : 1 - day); // 周一为 1，周日为 0
  monday.setDate(monday.getDate() + diff);
  weekStart.value = fmtYMD(monday);
  month.value = `${monday.getFullYear()}-${String(monday.getMonth() + 1).padStart(2,'0')}`;
  loadAdvice();
});

function setScope(s: 'week' | 'month') {
  scope.value = s;
}

function fmtYMD(d: Date) {
  const Y = d.getFullYear();
  const M = String(d.getMonth() + 1).padStart(2, '0');
  const D = String(d.getDate()).padStart(2, '0');
  return `${Y}-${M}-${D}`;
}

async function loadAdvice() {
  try {
    loading.value = true;
    adviceText.value = '';
    if (!user.info.value?.id) {
      return ui.showToast({ message: '请先登录', type: 'error' });
    }
    const params: any = { scope: scope.value, userId: user.info.value.id };
    if (scope.value === 'week') {
      if (!weekStart.value) return ui.showToast({ message: '请选择周一日期', type: 'error' });
      params.startDate = weekStart.value;
    } else {
      const m = (month.value || '').trim();
      if (!/^\d{4}-\d{2}$/.test(m)) return ui.showToast({ message: '请输入有效月份，如 2025-11', type: 'error' });
      params.startDate = `${m}-01`;
    }
    const res = await request({ url: '/app/useradvice/advice', method: 'GET', params });
    adviceText.value = res?.adviceText || '';
    if (!adviceText.value) {
      emptyText.value = scope.value === 'month'
        ? '未查询到该月份的月报/周报/日报内容，请核实后再尝试'
        : '未查询到该周的可用内容，请核实后再尝试';
    }
  } catch (e: any) {
    adviceText.value = '';
    emptyText.value = e?.message || (scope.value === 'month'
      ? '未查询到该月份的月报/周报/日报内容，请核实后再尝试'
      : '未查询到该周的可用内容，请核实后再尝试');
  } finally {
    loading.value = false;
  }
}
</script>

<style scoped>
.label { color: #6b7280; /* gray-500 */ margin-right: 8px; }
.chip {
  display: inline-flex;
  align-items: center;
  padding: 4px 12px;
  border-radius: 9999px;
  border: 1px solid #d1d5db; /* gray-300 */
  color: #374151; /* gray-700 */
}
.chip.active {
  background: #3b82f6; /* blue-500 */
  border-color: #3b82f6;
  color: #ffffff;
}
</style>
