<template>
  <div class="task-list-view">
    <div class="page-header">
      <div class="header-left">
        <h2>
          <CheckSquareOutlined /> 阅读任务
        </h2>
        <p class="page-desc">查看孩子的阅读任务并提交完成情况</p>
      </div>
      <a-select
        v-if="children.length > 1"
        v-model:value="selectedChildId"
        placeholder="选择孩子"
        style="width: 140px;"
        allow-clear
        @change="onChildChange"
      >
        <a-select-option :value="null">全部孩子</a-select-option>
        <a-select-option v-for="c in children" :key="c.id" :value="c.id">
          {{ c.name }}
        </a-select-option>
      </a-select>
    </div>

    <a-spin :spinning="loading">
      <div class="task-list" v-if="tasks.length > 0">
        <div v-for="task in tasks" :key="`${task.id}-${task.studentId ?? ''}`" class="task-card">
          <div class="card-header">
            <div class="task-info">
              <div class="task-title-row">
                <h3>{{ task.task.title }}</h3>
                <a-tag v-if="task.task.relatedBookName" color="purple" size="small">
                  <BookOutlined /> {{ task.task.relatedBookName }}
                </a-tag>
              </div>
              <div class="task-meta">
                <span v-if="task.task.course?.name">
                  <FolderOutlined /> {{ task.task.course.name }}
                </span>
                <span>
                  <ClockCircleOutlined />
                  截止: {{ formatDate(task.task.endDate) }}
                </span>
              </div>
            </div>
            <a-tag :color="getStatusColor(task.status)">
              {{ getStatusText(task.status) }}
            </a-tag>
          </div>

          <div class="card-body" v-if="task.task.description">
            <p>{{ task.task.description }}</p>
          </div>

          <!-- 已提交内容预览 -->
          <div class="submission-preview"
            v-if="task.status !== 'PENDING' && (task.photos?.length || task.videoUrl || task.audioUrl || task.content)">
            <div class="preview-title">已提交内容：</div>
            <div class="preview-items">
              <span v-if="task.photos?.length" class="preview-item">
                <PictureOutlined /> {{ task.photos.length }} 张照片
              </span>
              <span v-if="task.videoUrl" class="preview-item">
                <VideoCameraOutlined /> 有视频
              </span>
              <span v-if="task.audioUrl" class="preview-item">
                <SoundOutlined /> 有音频
              </span>
              <span v-if="task.content" class="preview-item">
                <FileTextOutlined /> {{ task.content.substring(0, 30) }}{{ task.content.length > 30 ? '...' : '' }}
              </span>
            </div>
            <div class="submission-time" v-if="task.submittedAt">
              提交于 {{ formatDateTime(task.submittedAt) }}
            </div>
          </div>

          <!-- 教师评价显示 -->
          <div class="teacher-feedback" v-if="task.teacherFeedback">
            <div class="feedback-header">
              <StarFilled style="color: #faad14;" />
              <span>教师评价</span>
              <a-tag :color="getFeedbackResultColor(task.teacherFeedback.result)" size="small">
                {{ getFeedbackResultText(task.teacherFeedback.result) }}
              </a-tag>
            </div>
            <div class="feedback-rating" v-if="task.teacherFeedback.rating">
              <a-rate :value="task.teacherFeedback.rating" disabled :count="5" />
            </div>
            <div class="feedback-comment" v-if="task.teacherFeedback.comment">
              {{ task.teacherFeedback.comment }}
            </div>
          </div>

          <div class="card-footer">
            <div class="action-buttons">
              <!-- 待提交状态 -->
              <template v-if="task.status === 'PENDING'">
                <a-button type="primary" @click="openSubmitModal(task)">
                  <EditOutlined /> 提交完成
                </a-button>
              </template>

              <!-- 已提交但未评价 -->
              <template v-else-if="task.status === 'SUBMITTED'">
                <a-button @click="openSubmitModal(task)">
                  <EditOutlined /> 修改提交
                </a-button>
              </template>

              <!-- 已评价 -->
              <template v-else-if="task.status === 'REVIEWED'">
                <a-button type="link" @click="openFeedbackDetail(task)">
                  <EyeOutlined /> 查看评价详情
                </a-button>
              </template>
            </div>
          </div>
        </div>
      </div>

      <div class="empty-state" v-else>
        <InboxOutlined class="empty-icon" />
        <p>暂无阅读任务</p>
      </div>
    </a-spin>

    <!-- 提交任务弹窗 -->
    <a-modal v-model:open="submitModalVisible" :title="isEditSubmit ? '修改提交' : '提交任务完成'" @ok="handleSubmit"
      :confirm-loading="submitting" width="600px" okText="提交" cancelText="取消">
      <div class="task-info-header" v-if="selectedTask">
        <h4>{{ selectedTask.task.title }}</h4>
        <p v-if="selectedTask.task.relatedBookName">
          <BookOutlined /> {{ selectedTask.task.relatedBookName }}
        </p>
      </div>

      <a-form layout="vertical">
        <a-form-item label="照片">
          <div class="photo-upload-area">
            <div class="photo-list">
              <div v-for="(photo, index) in submitForm.photos" :key="index" class="photo-item">
                <img :src="photo" alt="照片" />
                <div class="photo-remove" @click="removePhoto(index)">
                  <CloseCircleOutlined />
                </div>
              </div>
            </div>
            <a-upload :customRequest="handlePhotoUpload" :showUploadList="false" accept="image/*" multiple>
              <div class="upload-btn">
                <PlusOutlined />
                <span>添加照片</span>
              </div>
            </a-upload>
          </div>
          <div class="form-tip">最多上传9张照片</div>
        </a-form-item>

        <a-form-item label="视频链接">
          <a-input v-model:value="submitForm.videoUrl" placeholder="请输入视频链接（可选，如腾讯视频、优酷等分享链接）" allow-clear />
        </a-form-item>

        <a-form-item label="音频链接">
          <a-input v-model:value="submitForm.audioUrl" placeholder="请输入音频链接（可选）" allow-clear />
        </a-form-item>

        <a-form-item label="阅读心得">
          <a-textarea v-model:value="submitForm.content" placeholder="请描述孩子的阅读情况、感受等（可选）" :rows="4" :maxlength="500"
            show-count />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 评价详情弹窗 -->
    <a-modal v-model:open="feedbackModalVisible" title="教师评价详情" :footer="null" width="500px">
      <div class="feedback-detail" v-if="selectedTask?.teacherFeedback">
        <div class="feedback-result-section">
          <div class="result-label">评价结果</div>
          <a-tag :color="getFeedbackResultColor(selectedTask.teacherFeedback.result)" size="large">
            {{ getFeedbackResultText(selectedTask.teacherFeedback.result) }}
          </a-tag>
        </div>

        <div class="feedback-rating-section" v-if="selectedTask.teacherFeedback.rating">
          <div class="rating-label">评分</div>
          <a-rate :value="selectedTask.teacherFeedback.rating" disabled :count="5" />
          <span class="rating-text">{{ selectedTask.teacherFeedback.rating }} 分</span>
        </div>

        <div class="feedback-comment-section" v-if="selectedTask.teacherFeedback.comment">
          <div class="comment-label">教师评语</div>
          <div class="comment-content">{{ selectedTask.teacherFeedback.comment }}</div>
        </div>

        <div class="feedback-time">
          评价时间: {{ formatDateTime(selectedTask.teacherFeedback.createdAt) }}
        </div>
      </div>

      <!-- 提交内容回顾 -->
      <div class="submission-review" v-if="selectedTask">
        <a-divider>提交内容</a-divider>
        <div class="review-photos" v-if="selectedTask.photos?.length">
          <div class="photos-grid">
            <img v-for="(photo, idx) in selectedTask.photos" :key="idx" :src="photo" alt="照片"
              @click="previewImage(photo)" />
          </div>
        </div>
        <div class="review-links" v-if="selectedTask.videoUrl || selectedTask.audioUrl">
          <a v-if="selectedTask.videoUrl" :href="selectedTask.videoUrl" target="_blank">
            <VideoCameraOutlined /> 查看视频
          </a>
          <a v-if="selectedTask.audioUrl" :href="selectedTask.audioUrl" target="_blank">
            <SoundOutlined /> 收听音频
          </a>
        </div>
        <div class="review-content" v-if="selectedTask.content">
          <div class="content-label">阅读心得</div>
          <p>{{ selectedTask.content }}</p>
        </div>
      </div>
    </a-modal>

    <!-- 图片预览 -->
    <a-image :style="{ display: 'none' }" :preview="{
      visible: imagePreviewVisible,
      onVisibleChange: (visible: boolean) => { imagePreviewVisible = visible; },
    }" :src="previewImageUrl" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { message, Upload } from 'ant-design-vue';
import type { UploadRequestOption } from 'ant-design-vue/es/vc-upload/interface';
import {
  CheckSquareOutlined,
  BookOutlined,
  ClockCircleOutlined,
  EditOutlined,
  InboxOutlined,
  EyeOutlined,
  PlusOutlined,
  CloseCircleOutlined,
  PictureOutlined,
  VideoCameraOutlined,
  SoundOutlined,
  FileTextOutlined,
  FolderOutlined,
  StarFilled,
} from '@ant-design/icons-vue';
import {
  getChildTasks,
  getMyTasks,
  getChildren,
  submitTaskCompletion,
  updateTaskCompletion,
  type TaskWithCompletion,
  type TaskSubmitRequest,
  type ChildInfo,
} from '@/api/parent';
import { uploadFile } from '@/api/file';
import dayjs from 'dayjs';
import { translateTaskCompletionStatus, getTaskCompletionStatusStyle } from '@/utils/tagMaps';

const route = useRoute();
const router = useRouter();
const loading = ref(false);
const tasks = ref<TaskWithCompletion[]>([]);
const children = ref<ChildInfo[]>([]);
const currentChildId = ref<number | null>(null);
const selectedChildId = ref<number | null>(null);  // null = 全部孩子，使用 getMyTasks

// 提交弹窗
const submitModalVisible = ref(false);
const submitting = ref(false);
const selectedTask = ref<TaskWithCompletion | null>(null);
const isEditSubmit = ref(false);
const submitForm = reactive({
  photos: [] as string[],
  videoUrl: '',
  audioUrl: '',
  content: '',
});

// 评价详情弹窗
const feedbackModalVisible = ref(false);

// 图片预览
const imagePreviewVisible = ref(false);
const previewImageUrl = ref('');

// 状态映射 - 使用统一工具函数
const getStatusText = (status: string) => translateTaskCompletionStatus(status);
const getStatusColor = (status: string) => {
  const style = getTaskCompletionStatusStyle(status);
  // 返回 ant-design-vue tag 颜色名称
  const colorMap: Record<string, string> = {
    '待提交': 'orange',
    '已提交': 'blue',
    '已评价': 'green',
  };
  return colorMap[translateTaskCompletionStatus(status)] || 'default';
};

// 评价结果映射 - 保持本地定义（因为这是特定的评价结果，不是通用枚举）
const feedbackResultMap: Record<string, { text: string; color: string }> = {
  EXCELLENT: { text: '优秀', color: 'gold' },
  PASSED: { text: '通过', color: 'green' },
  NEEDS_WORK: { text: '需改进', color: 'orange' },
};
const getFeedbackResultText = (result: string) => feedbackResultMap[result]?.text || result;
const getFeedbackResultColor = (result: string) => feedbackResultMap[result]?.color || 'default';

const formatDate = (date?: string) => date ? dayjs(date).format('YYYY-MM-DD') : '-';
const formatDateTime = (date?: string) => date ? dayjs(date).format('YYYY-MM-DD HH:mm') : '-';

// 打开提交弹窗
const openSubmitModal = (task: TaskWithCompletion) => {
  selectedTask.value = task;
  isEditSubmit.value = task.status !== 'PENDING';

  // 填充已有数据
  submitForm.photos = task.photos || [];
  submitForm.videoUrl = task.videoUrl || '';
  submitForm.audioUrl = task.audioUrl || '';
  submitForm.content = task.content || '';

  submitModalVisible.value = true;
};

// 处理照片上传（符合 API：photos 为 URL 字符串数组）
const handlePhotoUpload = async (options: UploadRequestOption) => {
  const { file } = options;
  try {
    if (submitForm.photos.length >= 9) {
      message.warning('最多上传9张照片');
      return;
    }
    const result = await uploadFile(file as File, 'poster');
    const url = result.filePath;
    if (url) {
      submitForm.photos.push(url);
    }
  } catch (error: any) {
    message.error(error?.message || '上传失败');
  }
};

// 移除照片
const removePhoto = (index: number) => {
  submitForm.photos.splice(index, 1);
};

// 提交任务
const handleSubmit = async () => {
  if (!selectedTask.value) return;

  // 优先使用任务自带的 studentId（聚合视图），否则用当前选中的孩子
  const childId = selectedTask.value?.studentId ?? currentChildId.value ?? (route.query.childId ? Number(route.query.childId) : null);
  if (!childId) {
    message.warning('请先选择孩子');
    return;
  }

  submitting.value = true;
  try {
    const data: TaskSubmitRequest = {
      studentId: childId,
      photos: submitForm.photos.length > 0 ? submitForm.photos : undefined,
      videoUrl: submitForm.videoUrl || undefined,
      audioUrl: submitForm.audioUrl || undefined,
      content: submitForm.content || undefined,
    };

    if (isEditSubmit.value) {
      await updateTaskCompletion(selectedTask.value.task.id, data);
      message.success('修改成功');
    } else {
      await submitTaskCompletion(selectedTask.value.task.id, data);
      message.success('提交成功');
    }

    submitModalVisible.value = false;
    loadTasks();
  } catch (error: any) {
    message.error(error.response?.data?.message || '提交失败');
  } finally {
    submitting.value = false;
  }
};

// 打开评价详情
const openFeedbackDetail = (task: TaskWithCompletion) => {
  selectedTask.value = task;
  feedbackModalVisible.value = true;
};

// 预览图片
const previewImage = (url: string) => {
  previewImageUrl.value = url;
  imagePreviewVisible.value = true;
};

// 孩子切换
const onChildChange = (val: number | null) => {
  if (val) {
    router.replace({ query: { childId: String(val) } });
  } else {
    router.replace({ query: {} });
  }
  loadTasks();
};

// 加载任务列表：有 childId 用 getChildTasks，无 childId 用 getMyTasks（聚合多孩子）
const loadTasks = async () => {
  loading.value = true;
  try {
    let childId = route.query.childId ? Number(route.query.childId) : null;

    // 加载孩子列表（用于选择器）
    children.value = await getChildren();
    if (children.value.length === 0) {
      tasks.value = [];
      loading.value = false;
      return;
    }

    selectedChildId.value = childId;

    if (childId) {
      // 指定孩子：调用 getChildTasks
      currentChildId.value = childId;
      const data = await getChildTasks(childId);
      tasks.value = data.items;
    } else {
      // 未指定：调用 getMyTasks 聚合多孩子任务
      currentChildId.value = children.value[0]?.id ?? null;
      const data = await getMyTasks();
      tasks.value = data.items;
    }
  } catch (error: any) {
    message.error(error.response?.data?.message || '加载数据失败');
  } finally {
    loading.value = false;
  }
};

// 监听路由变化（如从孩子详情页跳转带 childId）
watch(() => route.query.childId, () => loadTasks());

onMounted(() => {
  loadTasks();
});
</script>

<style scoped lang="scss">
$primary-color: #52c41a;
$primary-light: #f6ffed;

.task-list-view {
  .page-header {
    margin-bottom: 24px;
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    flex-wrap: wrap;
    gap: 16px;

    .header-left {
      flex: 1;
    }

    h2 {
      margin: 0 0 8px;
      display: flex;
      align-items: center;
      gap: 8px;
    }

    .page-desc {
      margin: 0;
      color: #999;
    }
  }

  .task-list {
    display: flex;
    flex-direction: column;
    gap: 16px;
  }

  .task-card {
    background: white;
    border: 1px solid #f0f0f0;
    border-radius: 12px;
    padding: 20px;
    transition: all 0.3s;

    &:active {
      transform: scale(0.98);
    }

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      margin-bottom: 12px;

      .task-title-row {
        display: flex;
        align-items: center;
        gap: 8px;
        flex-wrap: wrap;
      }

      h3 {
        margin: 0;
        font-size: 16px;
      }

      .task-meta {
        display: flex;
        gap: 16px;
        margin-top: 8px;
        font-size: 13px;
        color: #666;

        span {
          display: flex;
          align-items: center;
          gap: 4px;
        }
      }
    }

    .card-body {
      margin-bottom: 12px;

      p {
        margin: 0;
        font-size: 14px;
        color: #666;
        line-height: 1.6;
      }
    }

    .submission-preview {
      background: #f6ffed;
      border-radius: 8px;
      padding: 12px;
      margin-bottom: 12px;

      .preview-title {
        font-size: 13px;
        color: #999;
        margin-bottom: 8px;
      }

      .preview-items {
        display: flex;
        flex-wrap: wrap;
        gap: 12px;

        .preview-item {
          font-size: 13px;
          color: #666;
          display: flex;
          align-items: center;
          gap: 4px;
        }
      }

      .submission-time {
        font-size: 12px;
        color: #999;
        margin-top: 8px;
      }
    }

    .teacher-feedback {
      background: #fffbe6;
      border-radius: 8px;
      padding: 12px;
      margin-bottom: 12px;

      .feedback-header {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-bottom: 8px;

        span {
          font-weight: 500;
        }
      }

      .feedback-rating {
        margin-bottom: 8px;
      }

      .feedback-comment {
        font-size: 14px;
        color: #666;
        line-height: 1.6;
      }
    }

    .card-footer {
      padding-top: 12px;
      border-top: 1px solid #f0f0f0;

      .action-buttons {
        display: flex;
        gap: 8px;
      }
    }
  }

  .empty-state {
    text-align: center;
    padding: 60px 20px;
    color: #999;

    .empty-icon {
      font-size: 64px;
      color: #d9d9d9;
    }
  }
}

// 提交弹窗样式
.task-info-header {
  padding-bottom: 16px;
  margin-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;

  h4 {
    margin: 0 0 8px;
  }

  p {
    margin: 0;
    color: #999;
    font-size: 13px;
  }
}

.photo-upload-area {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;

  .photo-list {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
  }

  .photo-item {
    position: relative;
    width: 80px;
    height: 80px;
    border-radius: 8px;
    overflow: hidden;

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .photo-remove {
      position: absolute;
      top: -6px;
      right: -6px;
      width: 20px;
      height: 20px;
      background: white;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      color: #ff4d4f;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }
  }

  .upload-btn {
    width: 80px;
    height: 80px;
    border: 1px dashed #d9d9d9;
    border-radius: 8px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    color: #999;
    transition: all 0.3s;

    &:hover {
      border-color: #1890ff;
      color: #1890ff;
    }

    span {
      font-size: 12px;
      margin-top: 4px;
    }
  }
}

.form-tip {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

// 评价详情弹窗样式
.feedback-detail {

  .feedback-result-section,
  .feedback-rating-section {
    margin-bottom: 16px;

    .result-label,
    .rating-label {
      font-size: 13px;
      color: #999;
      margin-bottom: 8px;
    }

    .rating-text {
      margin-left: 8px;
      color: #faad14;
    }
  }

  .feedback-comment-section {
    margin-bottom: 16px;

    .comment-label {
      font-size: 13px;
      color: #999;
      margin-bottom: 8px;
    }

    .comment-content {
      background: #fafafa;
      padding: 12px;
      border-radius: 8px;
      line-height: 1.6;
    }
  }

  .feedback-time {
    font-size: 12px;
    color: #999;
  }
}

.submission-review {
  .review-photos {
    .photos-grid {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;

      img {
        width: 100px;
        height: 100px;
        object-fit: cover;
        border-radius: 8px;
        cursor: pointer;
      }
    }
  }

  .review-links {
    display: flex;
    gap: 16px;
    margin: 12px 0;

    a {
      display: flex;
      align-items: center;
      gap: 4px;
    }
  }

  .review-content {
    .content-label {
      font-size: 13px;
      color: #999;
      margin-bottom: 8px;
    }

    p {
      margin: 0;
      line-height: 1.6;
      white-space: pre-wrap;
    }
  }
}

// =============== 移动端响应式 ===============
@media screen and (max-width: 768px) {
  .task-list-view {
    .page-header {
      margin-bottom: 16px;

      h2 {
        font-size: 18px;
      }

      .page-desc {
        font-size: 13px;
      }
    }

    .task-list {
      gap: 12px;
    }

    .task-card {
      padding: 14px;
      border-radius: 10px;

      .card-header {
        flex-direction: column;
        gap: 8px;
        margin-bottom: 10px;

        h3 {
          font-size: 15px;
        }

        .task-meta {
          flex-direction: column;
          gap: 6px;
          margin-top: 6px;
          font-size: 12px;
        }
      }

      .card-body {
        margin-bottom: 10px;

        p {
          font-size: 13px;
        }
      }

      .submission-preview,
      .teacher-feedback {
        padding: 10px;
      }

      .card-footer {
        padding-top: 10px;

        .action-buttons {
          flex-wrap: wrap;
        }
      }
    }

    .empty-state {
      padding: 40px 16px;

      .empty-icon {
        font-size: 48px;
      }
    }
  }

  .photo-upload-area {

    .photo-item,
    .upload-btn {
      width: 60px;
      height: 60px;
    }
  }
}
</style>
