<template>
  <div class="main">
    <div class="body">
      <div class="header">
        <h1 class="title">{{ pkg?.package_name }}</h1>
        <van-tag :type="pkg?.package_status === 'ACTIVE' ? 'success' : 'warning'" size="medium">
          {{ pkg?.package_status === 'ACTIVE' ? '上架中' : '已下架' }}
        </van-tag>
        <van-tag v-if="isPublished" type="info" size="medium" style="margin-left: 0.08rem;">已发布快照</van-tag>
      </div>

      <div class="section">
        <h2>基本信息</h2>
        <van-cell-group inset>
          <van-cell title="描述" :value="pkg?.description || '无'" />
          <van-cell title="课次数量" :value="pkg?.total_lessons?.toString() || '无'" />
          <van-cell title="原价" :value="pkg?.original_price ? '¥' + (pkg.original_price / 100).toFixed(2) : '无'" />
          <van-cell title="售价" :value="pkg?.selling_price ? '¥' + (pkg.selling_price / 100).toFixed(2) : '无'" />
          <van-cell title="有效期" :value="pkg?.validity_days ? pkg.validity_days + ' 天' : '无'" />
          <van-cell title="排序" :value="pkg?.sort_order?.toString() || '无'" />
        </van-cell-group>
      </div>

      <div class="section">
        <h2>包含课节</h2>
        <div v-if="courseGroups.length === 0" class="empty">暂无课节</div>
        <van-cell v-for="g in courseGroups" :key="g.id" :title="g.group_name">
          <template #label>
            <div v-if="g.course_sections?.length">
              {{ g.course_sections.map((s: any) => (s.course_name || '') + '(' + s.section_name + ')').join('、') }}
            </div>
            <div v-else style="color: #999;">无课程</div>
          </template>
        </van-cell>
      </div>
    </div>
    <div class="footer">
      <van-button v-if="!isPublished" type="primary" @click="onEdit">编辑</van-button>
      <van-button v-if="!isPublished" type="danger" @click="onDelete">删除</van-button>
      <van-button v-if="!isPublished" type="success" @click="onPublish">发布上架</van-button>
      <van-button v-if="isPublished" type="warning" @click="onUnpublish">下架</van-button>
    </div>
  </div>
</template>

<script lang="ts">
import {computed, defineComponent, onMounted, ref} from 'vue';
import {Button, Cell, CellGroup, Tag, showConfirmDialog, showFailToast} from 'vant';
import {useRoute, useRouter} from 'vue-router';
import useCoursePackage from '~/store/course-package';
import {CourseGroup} from '~/types';

export default defineComponent({
  name: 'course-package-detail',
  components: {
    [Button.name]: Button,
    [Cell.name]: Cell,
    [CellGroup.name]: CellGroup,
    [Tag.name]: Tag,
  },
  setup() {
    const route = useRoute();
    const router = useRouter();
    const {store, findById, remove, listPackageItems, publish, unpublish} = useCoursePackage();

    const pkg = ref<any>(null);
    const courseGroups = ref<CourseGroup[]>([]);
    const loading = ref(false);

    const isPublished = computed(() => !!pkg.value?.published_at);

    const loadData = async () => {
      const id = route.query.id as string;
      if (!id) {
        showFailToast('缺少课包 ID');
        router.go(-1);
        return;
      }
      loading.value = true;
      const data = await findById(id);
      if (!data) {
        router.go(-1);
        return;
      }
      pkg.value = data;

      if (data.published_snapshot?.course_groups) {
        // 从快照读取课节数据
        courseGroups.value = data.published_snapshot.course_groups;
      } else {
        // 实时获取课节数据
        const groups = await listPackageItems(id);
        courseGroups.value = groups || [];
      }
      loading.value = false;
    };

    const onEdit = () => {
      router.push(`/course/course-package/edit?id=${pkg.value?.id}`);
    };

    const onDelete = async () => {
      try {
        await showConfirmDialog({message: `确认删除课包【${pkg.value?.package_name}】？`});
        const ok = await remove(pkg.value?.id!);
        if (ok) router.go(-1);
      } catch { /* cancelled */ }
    };

    const onPublish = async () => {
      try {
        await showConfirmDialog({
          title: '发布课包',
          message: '发布后将锁定课包内容，生成快照，不可再编辑。确认发布？',
        });
        const id = pkg.value?.id!;
        // 获取完整课节数据作为快照
        let groups = courseGroups.value;
        if (groups.length === 0) {
          groups = (await listPackageItems(id)) || [];
        }
        const snapshot = { course_groups: groups };
        const ok = await publish(id, snapshot);
        if (ok) await loadData();
      } catch { /* cancelled */ }
    };

    const onUnpublish = async () => {
      try {
        await showConfirmDialog({
          title: '下架课包',
          message: '下架后课包内容可编辑，确认下架？',
        });
        const ok = await unpublish(pkg.value?.id!);
        if (ok) await loadData();
      } catch { /* cancelled */ }
    };

    onMounted(loadData);

    return {
      pkg, courseGroups, loading, isPublished,
      onEdit, onDelete, onPublish, onUnpublish,
    };
  },
});
</script>

<style scoped lang="less">
.main {
  .body {
    height: calc(100% - 1.06rem);
    padding: 0.32rem 0;
    overflow: auto;
  }

  .header {
    text-align: center;
    margin-bottom: 0.32rem;
  }

  .title {
    font-size: 0.48rem;
    margin-block-start: 0;
    margin-block-end: 0.16rem;
  }

  h2 {
    font-size: 0.32rem;
    padding: 0 0.32rem;
  }

  .section {
    margin-bottom: 0.32rem;
  }

  .empty {
    text-align: center;
    color: #999;
    font-size: 0.26rem;
    padding: 0.32rem;
  }

  .footer {
    position: absolute;
    bottom: 0.16rem;
    width: 100%;
    padding: 0.01rem 0.32rem;
    display: flex;
    gap: 0.16rem;

    button {
      flex: 1;
    }
  }
}
</style>
