<template>
  <div class="p-6">
    <!-- 页面标题 -->
    <div class="mb-6">
      <h1 class="text-2xl font-bold text-gray-900">生成周报</h1>
      <p class="text-gray-600 mt-2">生成上周的工作周报</p>
    </div>

    <!-- 周报生成区域 -->
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
      <h2 class="text-xl font-semibold text-gray-700 mb-4">生成上周周报</h2>
      
      <div class="flex flex-wrap gap-4 mb-4">
        <div class="flex-1 min-w-64">
          <label class="block text-sm font-medium text-gray-700 mb-2">用户名</label>
          <input 
            type="text" 
            v-model="weeklyReport.username"
            class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            placeholder="输入 JIRA 用户名"
          >
        </div>
        <div class="flex items-end">
          <button 
            @click="generateWeeklyReport"
            :disabled="weeklyReport.loading"
            class="px-6 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <span v-if="weeklyReport.loading">生成中...</span>
            <span v-else>生成周报</span>
          </button>
        </div>
      </div>

      <!-- 周报结果 -->
      <div v-if="weeklyReport.result" class="mt-6">
        <div class="flex justify-between items-center mb-4">
          <h3 class="text-lg font-medium text-gray-700">周报内容</h3>
          <div class="flex gap-2">
            <button
              @click="copyMarkdown"
              class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700"
            >
              复制 Markdown
            </button>
            <button
              @click="downloadWeeklyReport"
              class="px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700"
            >
              下载 Markdown
            </button>
          </div>
        </div>
        <div class="bg-gray-50 p-4 rounded-md">
          <pre class="whitespace-pre-wrap text-sm">{{ weeklyReport.result }}</pre>
        </div>
      </div>

      <!-- 错误信息 -->
      <div v-if="weeklyReport.error" class="mt-4 p-4 bg-red-50 border border-red-200 rounded-md">
        <p class="text-red-700">{{ weeklyReport.error }}</p>
      </div>
    </div>
  </div>
</template>

<script>
import { resolveJiraDefaultQueryUser } from '../../utils/jiraQueryUser';

export default {
  name: 'WeeklyReport',
  data() {
    return {
      weeklyReport: {
        username: '',
        loading: false,
        result: '',
        error: ''
      }
    }
  },

  async mounted() {
    // 获取默认用户名
    await this.loadDefaultUser();
  },
  methods: {
    async loadDefaultUser() {
      this.weeklyReport.username = resolveJiraDefaultQueryUser('');

      try {
        const response = await fetch('/api/jira/config');
        const data = await response.json();

        if (data.success) {
          this.weeklyReport.username = resolveJiraDefaultQueryUser(data.data.default_user);
        }
      } catch (error) {
        console.error('获取默认用户失败:', error);
      }
    },

    async generateWeeklyReport() {
      if (!this.weeklyReport.username.trim()) {
        this.weeklyReport.error = '请输入用户名';
        return;
      }

      this.weeklyReport.loading = true;
      this.weeklyReport.error = '';
      this.weeklyReport.result = '';

      try {
        const response = await fetch('/api/jira/weekly-report', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
          },
          body: JSON.stringify({
            username: this.weeklyReport.username
          })
        });

        const data = await response.json();

        if (data.success) {
          this.weeklyReport.result = data.data.report;
        } else {
          this.weeklyReport.error = data.message;
        }
      } catch (error) {
        this.weeklyReport.error = '网络请求失败: ' + error.message;
      } finally {
        this.weeklyReport.loading = false;
      }
    },

    async copyMarkdown() {
      if (!this.weeklyReport.result) {
        return;
      }

      try {
        await navigator.clipboard.writeText(this.weeklyReport.result);
        // 可以添加一个成功提示
        alert('Markdown 内容已复制到剪贴板');
      } catch (error) {
        // 如果浏览器不支持 clipboard API，使用传统方法
        const textArea = document.createElement('textarea');
        textArea.value = this.weeklyReport.result;
        document.body.appendChild(textArea);
        textArea.select();
        document.execCommand('copy');
        document.body.removeChild(textArea);
        alert('Markdown 内容已复制到剪贴板');
      }
    },

    downloadWeeklyReport() {
      if (!this.weeklyReport.username.trim()) {
        return;
      }

      const params = new URLSearchParams({
        username: this.weeklyReport.username
      });

      window.open(`/api/jira/weekly-report/download?${params}`, '_blank');
    }
  }
}
</script>
