<template>
  <div class="course-list">
    <div class="page-header">
      <a-row :gutter="16" align="middle">
        <a-col :span="16">
          <a-space>
            <a-select
              v-model:value="filters.grade"
              placeholder="年级"
              style="width: 120px"
              allow-clear
              @change="fetchCourses"
            >
              <a-select-option value="small">小班</a-select-option>
              <a-select-option value="middle">中班</a-select-option>
              <a-select-option value="big">大班</a-select-option>
            </a-select>

            <a-select
              v-model:value="filters.status"
              placeholder="状态"
              style="width: 120px"
              allow-clear
              @change="fetchCourses"
            >
              <a-select-option value="DRAFT">草稿</a-select-option>
              <a-select-option value="PENDING">审核中</a-select-option>
              <a-select-option value="REJECTED">已驳回</a-select-option>
              <a-select-option value="PUBLISHED">已发布</a-select-option>
              <a-select-option value="ARCHIVED">已下架</a-select-option>
            </a-select>

            <a-input-search
              v-model:value="filters.keyword"
              placeholder="搜索课程包名称"
              style="width: 250px"
              @search="fetchCourses"
              @blur="fetchCourses"
            />
          </a-space>
        </a-col>
        <a-col :span="8" style="text-align: right;">
          <a-space>
            <a-button @click="$router.push('/admin/courses/review')">
              <AuditOutlined /> 审核管理
              <a-badge v-if="pendingCount > 0" :count="pendingCount" :offset="[10, 0]" />
            </a-button>
            <a-button type="primary" @click="$router.push('/admin/courses/create')">
              <PlusOutlined /> 新建课程包
            </a-button>
          </a-space>
        </a-col>
      </a-row>
    </div>

    <a-table
      :columns="columns"
      :data-source="courses"
      :loading="loading"
      :pagination="pagination"
      @change="handleTableChange"
      row-key="id"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'name'">
          <div class="course-name">
            <a @click="viewCourse(record.id)">{{ record.name }}</a>
            <div class="course-tags">
              <a-tag
                v-for="grade in parseGradeTags(record.gradeTags)"
                :key="grade"
                size="small"
                :style="getGradeTagStyle(grade)"
              >
                {{ grade }}
              </a-tag>
            </div>
          </div>
        </template>

        <template v-else-if="column.key === 'pictureBook'">
          {{ record.pictureBookName }}
        </template>

        <template v-else-if="column.key === 'status'">
          <a-tag :style="getCourseStatusStyle(record.status)">
            {{ translateCourseStatus(record.status) }}
          </a-tag>
        </template>

        <template v-else-if="column.key === 'version'">
          v{{ record.version }}
        </template>

        <template v-else-if="column.key === 'stats'">
          <a-space direction="vertical" size="small">
            <span>使用：{{ record.usageCount }}次</span>
            <span>教师：{{ record.teacherCount }}人</span>
            <span>评分：⭐ {{ record.avgRating }}</span>
          </a-space>
        </template>

        <template v-else-if="column.key === 'updatedAt'">
          <span>{{ formatDate(record.updatedAt) }}</span>
        </template>

        <template v-else-if="column.key === 'actions'">
          <a-space>
            <!-- 草稿状态 -->
            <template v-if="record.status === 'DRAFT'">
              <a-button size="small" @click="editCourse(record.id)">编辑</a-button>
              <a-dropdown>
                <a-button type="primary" size="small">
                  发布 <DownOutlined />
                </a-button>
                <template #overlay>
                  <a-menu @click="({ key }) => handlePublishAction(String(key), record)">
                    <a-menu-item key="submit">提交审核</a-menu-item>
                    <a-menu-item key="direct">直接发布（跳过审核）</a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
              <a-popconfirm
                title="确定删除此课程包吗？"
                @confirm="deleteCourseHandler(record.id)"
              >
                <a-button size="small" danger>删除</a-button>
              </a-popconfirm>
            </template>

            <!-- 审核中状态 -->
            <template v-else-if="record.status === 'PENDING'">
              <a-button size="small" @click="viewCourse(record.id)">查看</a-button>
              <a-button type="primary" size="small" @click="approveCourseHandler(record.id)">通过</a-button>
              <a-button size="small" @click="withdrawReview(record.id)">撤销</a-button>
            </template>

            <!-- 已驳回状态 -->
            <template v-else-if="record.status === 'REJECTED'">
              <a-tooltip :title="record.reviewComment">
                <a-button size="small" danger>查看原因</a-button>
              </a-tooltip>
              <a-button size="small" @click="editCourse(record.id)">修改</a-button>
              <a-button type="primary" size="small" @click="submitForReview(record)">重新提交</a-button>
            </template>

            <!-- 已发布状态 -->
            <template v-else-if="record.status === 'PUBLISHED'">
              <a-button size="small" @click="viewCourse(record.id)">查看</a-button>
              <a-button size="small" @click="viewStats(record.id)">数据</a-button>
              <a-dropdown>
                <a-button size="small">
                  更多 <DownOutlined />
                </a-button>
                <template #overlay>
                  <a-menu @click="({ key }) => handleMoreAction(String(key), record)">
                    <a-menu-item key="unpublish">下架</a-menu-item>
                    <a-menu-item key="iterate">迭代版本</a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
            </template>

            <!-- 已下架状态 -->
            <template v-else-if="record.status === 'ARCHIVED'">
              <a-button size="small" @click="viewCourse(record.id)">查看</a-button>
              <a-button size="small" @click="viewStats(record.id)">数据</a-button>
              <a-button type="primary" size="small" @click="republishCourse(record.id)">重新发布</a-button>
              <a-popconfirm
                title="确定删除此课程包吗？删除后无法恢复"
                @confirm="deleteCourseHandler(record.id)"
              >
                <a-button size="small" danger>删除</a-button>
              </a-popconfirm>
            </template>
          </a-space>
        </template>
      </template>
    </a-table>

    <!-- 提交审核弹窗 -->
    <a-modal
      v-model:open="submitModalVisible"
      title="提交审核"
      :confirmLoading="submitting"
      @ok="confirmSubmit"
    >
      <a-alert
        v-if="validationResult && !validationResult.valid"
        type="error"
        :message="`发现 ${validationResult.errors.length} 个问题需要修复`"
        style="margin-bottom: 16px;"
      >
        <template #description>
          <ul style="margin: 0; padding-left: 20px;">
            <li v-for="error in validationResult?.errors" :key="error.code">
              {{ error.message }}
            </li>
          </ul>
        </template>
      </a-alert>

      <a-alert
        v-if="validationResult && validationResult.warnings.length > 0"
        type="warning"
        :message="`有 ${validationResult.warnings.length} 条建议`"
        style="margin-bottom: 16px;"
      >
        <template #description>
          <ul style="margin: 0; padding-left: 20px;">
            <li v-for="warning in validationResult?.warnings" :key="warning.code">
              {{ warning.message }}
            </li>
          </ul>
        </template>
      </a-alert>

      <a-form layout="vertical" v-if="validationResult?.valid">
        <a-form-item>
          <a-checkbox v-model:checked="copyrightConfirmed">
            我确认课程内容中的所有素材均有合法版权
          </a-checkbox>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { message, Modal } from 'ant-design-vue';
import { PlusOutlined, DownOutlined, AuditOutlined } from '@ant-design/icons-vue';
import * as courseApi from '@/api/course';
import {
  translateGradeTag,
  getGradeTagStyle,
  translateCourseStatus,
  getCourseStatusStyle,
} from '@/utils/tagMaps';

const router = useRouter();

const loading = ref(false);
const courses = ref<any[]>([]);
const pendingCount = ref(0);

const filters = reactive({
  grade: undefined,
  status: undefined,
  keyword: '',
});

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
});

const columns = [
  { title: '课程包名称', key: 'name', width: 250 },
  { title: '关联绘本', key: 'pictureBook', width: 120 },
  { title: '状态', key: 'status', width: 90 },
  { title: '版本', key: 'version', width: 70 },
  { title: '数据统计', key: 'stats', width: 130 },
  { title: '最近更新', key: 'updatedAt', width: 120 },
  { title: '操作', key: 'actions', width: 200, fixed: 'right' as const },
];

// 提交审核相关
const submitModalVisible = ref(false);
const submitting = ref(false);
const currentCourse = ref<any>(null);
const validationResult = ref<courseApi.ValidationResult | null>(null);
const copyrightConfirmed = ref(false);

onMounted(() => {
  fetchCourses();
  fetchPendingCount();
});

const fetchCourses = async () => {
  loading.value = true;
  try {
    const data = await courseApi.getCourses({
      page: pagination.current,
      pageSize: pagination.pageSize,
      ...filters,
    });

    courses.value = data.items || [];
    pagination.total = data.total || 0;
  } catch (error) {
    console.error('获取课程包列表失败:', error);
  } finally {
    loading.value = false;
  }
};

const fetchPendingCount = async () => {
  try {
    const data = await courseApi.getReviewList({ pageSize: 1 });
    pendingCount.value = data.total || 0;
  } catch (error) {
    console.error('获取待审核数量失败:', error);
  }
};

const handleTableChange = (pag: any) => {
  pagination.current = pag.current;
  pagination.pageSize = pag.pageSize;
  fetchCourses();
};

const viewCourse = (id: number) => {
  router.push(`/admin/courses/${id}`);
};

const editCourse = (id: number) => {
  router.push(`/admin/courses/${id}/edit`);
};

const viewStats = (id: number) => {
  router.push(`/admin/courses/${id}/stats`);
};

const deleteCourseHandler = async (id: number) => {
  try {
    await courseApi.deleteCourse(id);
    message.success('删除成功');
    fetchCourses();
  } catch (error) {
    message.error('删除失败');
  }
};

const handleMoreAction = (key: string, record: any) => {
  if (key === 'unpublish') {
    unpublishCourse(record.id);
  } else if (key === 'iterate') {
    iterateCourse(record.id);
  }
};

// 发布操作（提交审核或直接发布）
const handlePublishAction = (key: string, record: any) => {
  if (key === 'submit') {
    submitForReview(record);
  } else if (key === 'direct') {
    directPublishCourseHandler(record);
  }
};

// 直接发布（超管跳过审核）
const directPublishCourseHandler = (record: any) => {
  Modal.confirm({
    title: '直接发布',
    content: '直接发布将跳过审核流程，课程将立即对所有租户可见。确定继续？',
    okText: '确认发布',
    okType: 'primary',
    onOk: async () => {
      try {
        // 先验证课程完整性
        const validation = await courseApi.validateCourse(record.id);
        if (!validation.valid) {
          Modal.warning({
            title: '课程信息不完整',
            content: () => {
              const errors = validation.errors.map((e: any) => e.message).join('、');
              return `请先完善以下内容：${errors}`;
            },
          });
          return;
        }

        // 显示警告但允许继续
        if (validation.warnings.length > 0) {
          const warnings = validation.warnings.map((w: any) => w.message).join('、');
          const confirmed = await new Promise((resolve) => {
            Modal.confirm({
              title: '提示',
              content: `课程有以下建议但不影响发布：${warnings}。是否继续发布？`,
              onOk: () => resolve(true),
              onCancel: () => resolve(false),
            });
          });
          if (!confirmed) return;
        }

        await courseApi.directPublishCourse(record.id, false);
        message.success('发布成功');
        fetchCourses();
        fetchPendingCount();
      } catch (error: any) {
        message.error(error.response?.data?.message || '发布失败');
      }
    },
  });
};

// 审核通过
const approveCourseHandler = async (id: number) => {
  Modal.confirm({
    title: '确认通过',
    content: '确定通过此课程的审核？通过后将立即发布。',
    okText: '确认通过',
    okType: 'primary',
    onOk: async () => {
      try {
        await courseApi.approveCourse(id, {});
        message.success('审核通过，课程已发布');
        fetchCourses();
        fetchPendingCount();
      } catch (error: any) {
        message.error(error.response?.data?.message || '操作失败');
      }
    },
  });
};

// 提交审核
const submitForReview = async (record: any) => {
  currentCourse.value = record;
  copyrightConfirmed.value = false;
  validationResult.value = null;

  try {
    validationResult.value = await courseApi.validateCourse(record.id);
    submitModalVisible.value = true;
  } catch (error: any) {
    // 如果是验证失败，显示错误信息
    if (error.response?.data?.errors) {
      validationResult.value = {
        valid: false,
        errors: error.response.data.errors,
        warnings: error.response.data.warnings || [],
      };
      submitModalVisible.value = true;
    } else {
      message.error('验证失败，请稍后重试');
    }
  }
};

const confirmSubmit = async () => {
  if (!validationResult.value?.valid) {
    submitModalVisible.value = false;
    return;
  }

  if (!copyrightConfirmed.value) {
    message.warning('请确认版权合规');
    return;
  }

  submitting.value = true;
  try {
    await courseApi.submitCourse(currentCourse.value.id, copyrightConfirmed.value);
    message.success('已提交审核');
    submitModalVisible.value = false;
    fetchCourses();
    fetchPendingCount();
  } catch (error: any) {
    message.error(error.response?.data?.message || '提交失败');
  } finally {
    submitting.value = false;
  }
};

// 撤销审核
const withdrawReview = async (id: number) => {
  Modal.confirm({
    title: '确认撤销',
    content: '确定要撤销审核申请吗？',
    onOk: async () => {
      try {
        await courseApi.withdrawCourse(id);
        message.success('已撤销');
        fetchCourses();
        fetchPendingCount();
      } catch (error: any) {
        message.error(error.response?.data?.message || '撤销失败');
      }
    },
  });
};

// 下架
const unpublishCourse = async (id: number) => {
  Modal.confirm({
    title: '确认下架',
    content: '下架后教师端将无法看到此课程包，确认继续？',
    onOk: async () => {
      try {
        await courseApi.unpublishCourse(id);
        message.success('下架成功');
        fetchCourses();
      } catch (error) {
        message.error('下架失败');
      }
    },
  });
};

// 重新发布
const republishCourse = async (id: number) => {
  Modal.confirm({
    title: '确认重新发布',
    content: '重新发布后所有活跃租户将可以查看并使用此课程包，确认继续？',
    onOk: async () => {
      try {
        await courseApi.republishCourse(id);
        message.success('重新发布成功');
        fetchCourses();
      } catch (error) {
        message.error('重新发布失败');
      }
    },
  });
};

const iterateCourse = (id: number) => {
  router.push(`/admin/courses/${id}/iterate`);
};

const parseGradeTags = (gradeTags: string) => {
  if (!gradeTags) return [];
  try {
    const tags = JSON.parse(gradeTags);
    return tags.map((t: string) => translateGradeTag(t));
  } catch {
    return [];
  }
};

const formatDate = (dateStr: string) => {
  if (!dateStr) return '-';
  const date = new Date(dateStr);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}`;
};
</script>

<style scoped lang="scss">
.course-list {
  .page-header {
    margin-bottom: 16px;
  }

  .course-name {
    .course-tags {
      margin-top: 4px;
    }
  }
}
</style>
