<template>
  <div class="package-view">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-title">
          <div class="title-icon-wrapper">
            <GiftOutlined class="title-icon" />
          </div>
          <div class="title-text">
            <h2>套餐管理</h2>
            <p>查看学校已授权的课程套餐</p>
          </div>
        </div>
        <a-button type="primary" @click="showApplyModal">
          <PlusOutlined /> 申请新套餐
        </a-button>
      </div>
    </div>

    <!-- 统计概览 -->
    <div class="stats-row" v-if="!loading">
      <div class="stat-card">
        <div class="stat-icon package">
          <GiftOutlined />
        </div>
        <div class="stat-info">
          <div class="stat-value">{{ tenantPackages.length }}</div>
          <div class="stat-label">已授权套餐</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon course">
          <BookOutlined />
        </div>
        <div class="stat-info">
          <div class="stat-value">{{ totalCourseCount }}</div>
          <div class="stat-label">可用课程包</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon expiring" v-if="expiringCount > 0">
          <WarningOutlined />
        </div>
        <div class="stat-icon normal" v-else>
          <CheckCircleOutlined />
        </div>
        <div class="stat-info">
          <div class="stat-value" :class="{ warning: expiringCount > 0 }">{{ expiringCount }}</div>
          <div class="stat-label">即将到期</div>
        </div>
      </div>
    </div>

    <!-- 加载状态 -->
    <div class="loading-state" v-if="loading">
      <a-spin size="large" />
      <p>加载套餐信息...</p>
    </div>

    <!-- 套餐列表 -->
    <div class="package-list" v-if="!loading">
      <a-alert
        v-if="tenantPackages.length === 0"
        type="info"
        show-icon
        message="暂无已授权的套餐"
        description="请联系管理员申请课程套餐，以获取课程包的使用权限。"
        style="margin-bottom: 24px;"
      />

      <div class="package-grid">
        <div
          v-for="item in tenantPackages"
          :key="item.id"
          class="package-card"
          :class="{ 'expiring': isExpiring(item.endDate), 'expired': isExpired(item.endDate) }"
        >
          <div class="package-header">
            <div class="package-name">{{ item.package.name }}</div>
            <a-tag :color="getStatusColor(item.endDate)">
              {{ getStatusText(item.endDate) }}
            </a-tag>
          </div>

          <div class="package-body">
            <div class="package-info">
              <div class="info-item">
                <span class="info-label">包含课程包</span>
                <span class="info-value">{{ item.package.courseCount }} 个</span>
              </div>
              <div class="info-item">
                <span class="info-label">授权时间</span>
                <span class="info-value">{{ formatDate(item.startDate) }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">到期时间</span>
                <span class="info-value" :class="{ warning: isExpiring(item.endDate) }">
                  {{ formatDate(item.endDate) }}
                  <span v-if="!isExpired(item.endDate)" class="days-left">
                    ({{ getDaysLeft(item.endDate) }}天)
                  </span>
                </span>
              </div>
            </div>

            <!-- 课程包预览 -->
            <div class="course-preview" v-if="item.package.courses && item.package.courses.length > 0">
              <div class="preview-title">包含课程包：</div>
              <div class="preview-tags">
                <a-tag v-for="course in item.package.courses.slice(0, 5)" :key="course.id" color="blue">
                  {{ course.course.name }}
                </a-tag>
                <a-tag v-if="item.package.courses.length > 5" color="default">
                  +{{ item.package.courses.length - 5 }} 更多
                </a-tag>
              </div>
            </div>
          </div>

          <div class="package-footer">
            <a-button type="link" @click="viewPackageDetail(item)">
              <EyeOutlined /> 查看详情
            </a-button>
            <a-button
              type="link"
              :class="{ 'renew-btn': isExpiring(item.endDate) || isExpired(item.endDate) }"
              @click="showRenewModal(item)"
            >
              <SyncOutlined /> 续订
            </a-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 套餐详情弹窗 -->
    <a-modal
      v-model:open="detailModalVisible"
      :title="selectedPackage?.package?.name || '套餐详情'"
      width="800px"
      :footer="null"
    >
      <div class="detail-modal" v-if="selectedPackage">
        <div class="detail-section">
          <div class="section-title">
            <InfoCircleOutlined /> 套餐信息
          </div>
          <div class="section-content">
            <div class="detail-row">
              <span class="detail-label">套餐名称</span>
              <span class="detail-value">{{ selectedPackage.package.name }}</span>
            </div>
            <div class="detail-row" v-if="selectedPackage.package.description">
              <span class="detail-label">套餐描述</span>
              <span class="detail-value">{{ selectedPackage.package.description }}</span>
            </div>
            <div class="detail-row">
              <span class="detail-label">授权时间</span>
              <span class="detail-value">{{ formatDate(selectedPackage.startDate) }}</span>
            </div>
            <div class="detail-row">
              <span class="detail-label">到期时间</span>
              <span class="detail-value">
                {{ formatDate(selectedPackage.endDate) }}
                <a-tag v-if="!isExpired(selectedPackage.endDate)" :color="getStatusColor(selectedPackage.endDate)" style="margin-left: 8px;">
                  {{ getDaysLeft(selectedPackage.endDate) }}天后到期
                </a-tag>
                <a-tag v-else color="red" style="margin-left: 8px;">已过期</a-tag>
              </span>
            </div>
          </div>
        </div>

        <div class="detail-section">
          <div class="section-title">
            <BookOutlined /> 包含课程包 ({{ selectedPackage.package.courses?.length || 0 }}个)
          </div>
          <div class="section-content">
            <a-table
              v-if="selectedPackage.package.courses && selectedPackage.package.courses.length > 0"
              :dataSource="selectedPackage.package.courses"
              :columns="courseColumns"
              :pagination="false"
              size="small"
              row-key="id"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.dataIndex === 'gradeLevel'">
                  <a-tag>{{ record.gradeLevel }}</a-tag>
                </template>
              </template>
            </a-table>
            <div v-else class="empty-courses">暂无课程包</div>
          </div>
        </div>
      </div>
    </a-modal>

    <!-- 续订弹窗 -->
    <a-modal
      v-model:open="renewModalVisible"
      title="续订套餐"
      width="500px"
      @ok="handleRenew"
      :confirmLoading="renewLoading"
    >
      <div class="renew-modal" v-if="selectedPackage">
        <div class="renew-info">
          <div class="info-row">
            <span class="info-label">套餐名称</span>
            <span class="info-value">{{ selectedPackage.package.name }}</span>
          </div>
          <div class="info-row">
            <span class="info-label">包含课程包</span>
            <span class="info-value">{{ selectedPackage.package.courseCount }}个</span>
          </div>
          <div class="info-row">
            <span class="info-label">当前到期</span>
            <span class="info-value">{{ formatDate(selectedPackage.endDate) }}</span>
          </div>
        </div>

        <a-divider />

        <a-form layout="vertical">
          <a-form-item label="续订时长" required>
            <a-radio-group v-model:value="renewDuration">
              <a-radio value="6">1学期（6个月）</a-radio>
              <a-radio value="12">1学年（12个月）</a-radio>
              <a-radio value="24">2学年（24个月）</a-radio>
            </a-radio-group>
          </a-form-item>

          <a-form-item label="续订后到期时间">
            <a-input :value="calculatedEndDate" disabled />
          </a-form-item>
        </a-form>

        <a-alert
          type="info"
          show-icon
          message="续订说明"
          description="请选择续订时长后，联系客服完成续订支付。"
        />
      </div>
    </a-modal>

    <!-- 申请套餐弹窗 -->
    <a-modal
      v-model:open="applyModalVisible"
      title="申请新套餐"
      width="500px"
      :footer="null"
    >
      <div class="apply-modal">
        <a-alert
          type="info"
          show-icon
          message="申请说明"
          description="如需申请新的课程套餐，请联系平台管理员或客服进行咨询和办理。"
          style="margin-bottom: 16px;"
        />
        <div class="contact-info">
          <p><PhoneOutlined /> 客服电话：400-XXX-XXXX</p>
          <p><MailOutlined /> 客服邮箱：service@example.com</p>
        </div>
        <a-button type="primary" block @click="applyModalVisible = false">
          我知道了
        </a-button>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import {
  GiftOutlined,
  PlusOutlined,
  BookOutlined,
  WarningOutlined,
  CheckCircleOutlined,
  EyeOutlined,
  SyncOutlined,
  InfoCircleOutlined,
  PhoneOutlined,
  MailOutlined,
} from '@ant-design/icons-vue';
import { getTenantPackages, renewPackage, type TenantPackage } from '@/api/school';

const loading = ref(false);
const tenantPackages = ref<TenantPackage[]>([]);

// 详情弹窗
const detailModalVisible = ref(false);
const selectedPackage = ref<TenantPackage | null>(null);

// 续订弹窗
const renewModalVisible = ref(false);
const renewDuration = ref('12');
const renewLoading = ref(false);

// 申请弹窗
const applyModalVisible = ref(false);

// 课程表格列定义
const courseColumns = [
  { title: '序号', dataIndex: 'sortOrder', key: 'sortOrder', width: 60 },
  { title: '课程包名称', dataIndex: ['course', 'name'], key: 'courseName' },
  { title: '适用年级', dataIndex: 'gradeLevel', key: 'gradeLevel', width: 100 },
];

// 计算属性
const totalCourseCount = computed(() => {
  return tenantPackages.value.reduce((sum, item) => sum + (item.package?.courseCount || 0), 0);
});

const expiringCount = computed(() => {
  return tenantPackages.value.filter(item => isExpiring(item.endDate)).length;
});

const calculatedEndDate = computed(() => {
  if (!selectedPackage.value) return '';
  const baseDate = new Date(selectedPackage.value.endDate);
  const months = parseInt(renewDuration.value);
  baseDate.setMonth(baseDate.getMonth() + months);
  return formatDate(baseDate.toISOString());
});

// 日期格式化
const formatDate = (dateStr: string) => {
  if (!dateStr) return '-';
  const date = new Date(dateStr);
  return date.toLocaleDateString('zh-CN');
};

// 获取剩余天数
const getDaysLeft = (endDate: string) => {
  const end = new Date(endDate);
  const now = new Date();
  const diff = end.getTime() - now.getTime();
  return Math.ceil(diff / (1000 * 60 * 60 * 24));
};

// 是否即将到期（30天内）
const isExpiring = (endDate: string) => {
  const days = getDaysLeft(endDate);
  return days > 0 && days <= 30;
};

// 是否已过期
const isExpired = (endDate: string) => {
  return getDaysLeft(endDate) <= 0;
};

// 获取状态颜色
const getStatusColor = (endDate: string) => {
  if (isExpired(endDate)) return 'red';
  if (isExpiring(endDate)) return 'orange';
  return 'green';
};

// 获取状态文本
const getStatusText = (endDate: string) => {
  if (isExpired(endDate)) return '已过期';
  if (isExpiring(endDate)) return '即将到期';
  return '有效';
};

// 查看套餐详情
const viewPackageDetail = (item: TenantPackage) => {
  selectedPackage.value = item;
  detailModalVisible.value = true;
};

// 显示续订弹窗
const showRenewModal = (item: TenantPackage) => {
  selectedPackage.value = item;
  renewDuration.value = '12';
  renewModalVisible.value = true;
};

// 处理续订
const handleRenew = async () => {
  if (!selectedPackage.value) return;

  renewLoading.value = true;
  try {
    const baseDate = new Date(selectedPackage.value.endDate);
    const months = parseInt(renewDuration.value);
    baseDate.setMonth(baseDate.getMonth() + months);
    const newEndDate = baseDate.toISOString().split('T')[0];

    await renewPackage(selectedPackage.value.packageId, { endDate: newEndDate });
    message.success('续订成功');
    renewModalVisible.value = false;
    await loadPackages();
  } catch (error) {
    console.error('续订失败:', error);
    message.error('续订失败，请稍后重试');
  } finally {
    renewLoading.value = false;
  }
};

// 显示申请弹窗
const showApplyModal = () => {
  applyModalVisible.value = true;
};

// 加载套餐列表
const loadPackages = async () => {
  loading.value = true;
  try {
    const data = await getTenantPackages();
    tenantPackages.value = data || [];
  } catch (error) {
    console.error('加载套餐失败:', error);
    message.error('加载套餐失败');
  } finally {
    loading.value = false;
  }
};

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

<style scoped lang="scss">
.package-view {
  min-height: 100vh;
  background: linear-gradient(180deg, #F0FFF4 0%, #FFFFFF 100%);
  padding: 24px;
}

/* 页面头部 */
.page-header {
  margin-bottom: 24px;

  .header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .header-title {
    display: flex;
    align-items: center;
    gap: 16px;
  }

  .title-icon-wrapper {
    width: 56px;
    height: 56px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
    border-radius: 14px;
    box-shadow: 0 4px 12px rgba(67, 233, 123, 0.3);
  }

  .title-icon {
    font-size: 28px;
    color: white;
  }

  .title-text h2 {
    color: #333;
    font-size: 24px;
    font-weight: 700;
    margin: 0;
  }

  .title-text p {
    color: #666;
    font-size: 14px;
    margin: 4px 0 0 0;
  }
}

/* 统计概览 */
.stats-row {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
  margin-bottom: 24px;

  @media (max-width: 768px) {
    grid-template-columns: 1fr;
  }
}

.stat-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  display: flex;
  align-items: center;
  gap: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);

  .stat-icon {
    width: 48px;
    height: 48px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24px;

    &.package {
      background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
      color: white;
    }

    &.course {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
    }

    &.expiring {
      background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
      color: white;
    }

    &.normal {
      background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
      color: white;
    }
  }

  .stat-info {
    .stat-value {
      font-size: 28px;
      font-weight: 700;
      color: #333;

      &.warning {
        color: #f5222d;
      }
    }

    .stat-label {
      font-size: 13px;
      color: #666;
    }
  }
}

/* 加载状态 */
.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80px 0;

  p {
    color: #666;
    margin-top: 16px;
  }
}

/* 套餐网格 */
.package-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(360px, 1fr));
  gap: 20px;
}

/* 套餐卡片 */
.package-card {
  background: white;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  transition: all 0.3s ease;
  border: 1px solid #e8e8e8;

  &:hover {
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
    transform: translateY(-2px);
  }

  &.expiring {
    border-color: #faad14;
    background: linear-gradient(to bottom, #fffbe6, white);
  }

  &.expired {
    border-color: #ff4d4f;
    opacity: 0.8;
  }

  .package-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 20px;
    border-bottom: 1px solid #f0f0f0;
    background: #fafafa;

    .package-name {
      font-size: 16px;
      font-weight: 600;
      color: #333;
    }
  }

  .package-body {
    padding: 16px 20px;

    .package-info {
      .info-item {
        display: flex;
        justify-content: space-between;
        padding: 8px 0;
        border-bottom: 1px dashed #f0f0f0;

        &:last-child {
          border-bottom: none;
        }

        .info-label {
          color: #666;
          font-size: 13px;
        }

        .info-value {
          color: #333;
          font-size: 13px;

          &.warning {
            color: #faad14;
            font-weight: 500;
          }

          .days-left {
            color: #999;
            font-size: 12px;
            margin-left: 4px;
          }
        }
      }
    }

    .course-preview {
      margin-top: 12px;
      padding-top: 12px;
      border-top: 1px solid #f0f0f0;

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

      .preview-tags {
        display: flex;
        flex-wrap: wrap;
        gap: 4px;
      }
    }
  }

  .package-footer {
    display: flex;
    justify-content: flex-end;
    gap: 8px;
    padding: 12px 20px;
    border-top: 1px solid #f0f0f0;
    background: #fafafa;

    .renew-btn {
      color: #faad14;

      &:hover {
        color: #ff7a2a;
      }
    }
  }
}

/* 详情弹窗 */
.detail-modal {
  .detail-section {
    margin-bottom: 24px;

    &:last-child {
      margin-bottom: 0;
    }

    .section-title {
      font-size: 15px;
      font-weight: 600;
      color: #333;
      margin-bottom: 12px;
      display: flex;
      align-items: center;
      gap: 8px;
      padding-bottom: 8px;
      border-bottom: 1px solid #f0f0f0;
    }

    .section-content {
      .detail-row {
        display: flex;
        padding: 8px 0;

        .detail-label {
          width: 100px;
          color: #666;
          font-size: 13px;
        }

        .detail-value {
          flex: 1;
          color: #333;
          font-size: 13px;
        }
      }
    }
  }

  .empty-courses {
    text-align: center;
    padding: 24px;
    color: #999;
  }
}

/* 续订弹窗 */
.renew-modal {
  .renew-info {
    background: #f9f9f9;
    border-radius: 8px;
    padding: 16px;

    .info-row {
      display: flex;
      justify-content: space-between;
      padding: 8px 0;
      border-bottom: 1px dashed #e8e8e8;

      &:last-child {
        border-bottom: none;
      }

      .info-label {
        color: #666;
      }

      .info-value {
        color: #333;
        font-weight: 500;
      }
    }
  }
}

/* 申请弹窗 */
.apply-modal {
  .contact-info {
    background: #f9f9f9;
    border-radius: 8px;
    padding: 16px;
    margin-bottom: 16px;

    p {
      margin: 8px 0;
      color: #333;
      display: flex;
      align-items: center;
      gap: 8px;
    }
  }
}
</style>
