<template>
  <div class="main">
    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field v-model="form.package_name" name="package_name" label="课包名称" placeholder="请输入课包名称"
                   :rules="[{required: true, message: '请输入课包名称'}]" />
        <van-field v-model="form.description" name="description" label="描述" placeholder="请输入课包描述"
                   type="textarea" rows="3" autosize />
        <van-field v-model.number="form.total_lessons" name="total_lessons" label="课次数量" placeholder="请输入课次数量"
                   type="digit" />
        <van-field v-model="originalPriceStr" name="original_price" label="原价（元）" placeholder="请输入原价"
                   type="digit" @blur="formatPrice('original')" />
        <van-field v-model="sellingPriceStr" name="selling_price" label="售价（元）" placeholder="请输入售价"
                   type="digit" @blur="formatPrice('selling')" />
        <van-field v-model.number="form.validity_days" name="validity_days" label="有效期（天）" placeholder="请输入有效期天数"
                   type="digit" />
        <van-field v-model.number="form.sort_order" name="sort_order" label="排序" placeholder="请输入排序号"
                   type="digit" />
        <van-cell is-link @click="pickCourseGroups" title="包含课节"
                  title-class="van-field__label" colon>
          <template #value>
            <div v-if="store.selectedGroups.length === 0" style="color: #c8c9cc;">选择课节</div>
            <van-tag v-for="g in store.selectedGroups" :key="g.id" type="primary" size="medium" style="margin: 2px;">
              {{ g.group_name }}
            </van-tag>
          </template>
        </van-cell>
        <van-field v-model="form.package_status" name="package_status" label="状态" placeholder="选择状态"
                   is-link readonly @click="showStatusPicker = true" />
      </van-cell-group>
      <div style="margin: 16px;">
        <van-button round block type="primary" native-type="submit">保存</van-button>
      </div>
    </van-form>
    <van-action-sheet v-model:show="showStatusPicker" :actions="statusOptions"
                      @select="onStatusSelect" cancel-text="取消" />
  </div>
</template>

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

const statusOptions = [
  {name: '上架中', value: 'ACTIVE'},
  {name: '已下架', value: 'INACTIVE'},
];

export default defineComponent({
  name: "course-package-edit",
  components: {
    [Form.name]: Form,
    [Field.name]: Field,
    [CellGroup.name]: CellGroup,
    [Button.name]: Button,
    [ActionSheet.name]: ActionSheet,
    [Cell.name]: Cell,
    [Tag.name]: Tag,
  },
  setup() {
    const route = useRoute();
    const router = useRouter();
    const {store, findById, update, syncPackageItems, listPackageItems} = useCoursePackage();

    const form = reactive({
      id: '',
      package_name: '',
      description: '',
      total_lessons: undefined as number | undefined,
      validity_days: undefined as number | undefined,
      sort_order: undefined as number | undefined,
      package_status: 'ACTIVE',
    });

    const originalPriceStr = ref('');
    const sellingPriceStr = ref('');
    const showStatusPicker = ref(false);

    const formatPrice = (type: 'original' | 'selling') => {
      const str = type === 'original' ? originalPriceStr.value : sellingPriceStr.value;
      const num = parseFloat(str);
      if (isNaN(num)) return;
      const formatted = num.toFixed(2);
      if (type === 'original') originalPriceStr.value = formatted;
      else sellingPriceStr.value = formatted;
    };

    const onStatusSelect = (action: any) => {
      form.package_status = action.value;
      showStatusPicker.value = false;
    };

    const loadPackage = async () => {
      const id = route.query.id as string;
      if (!id) {
        showFailToast('缺少课包 ID');
        router.go(-1);
        return;
      }
      const pkg = await findById(id);
      if (!pkg) {
        showFailToast('未找到课包');
        router.go(-1);
        return;
      }
      form.id = pkg.id!;
      form.package_name = pkg.package_name;
      form.description = pkg.description || '';
      form.total_lessons = pkg.total_lessons;
      form.validity_days = pkg.validity_days;
      form.sort_order = pkg.sort_order;
      form.package_status = pkg.package_status || 'ACTIVE';
      if (pkg.published_at) {
        showFailToast('已发布的课包不可编辑，请先下架再修改');
        router.go(-1);
        return;
      }
      if (pkg.original_price != null) {
        originalPriceStr.value = (pkg.original_price / 100).toFixed(2);
      }
      if (pkg.selling_price != null) {
        sellingPriceStr.value = (pkg.selling_price / 100).toFixed(2);
      }
    };

    const pickCourseGroups = () => {
      router.push("/course/group/pick?target=" + PickTargets.COURSE_PACKAGE);
    };

    const onSubmit = async () => {
      const data: any = {
        id: form.id,
        package_name: form.package_name,
        description: form.description || undefined,
        total_lessons: form.total_lessons || undefined,
        validity_days: form.validity_days || undefined,
        sort_order: form.sort_order || undefined,
        package_status: form.package_status,
      };

      const origVal = parseFloat(originalPriceStr.value);
      if (!isNaN(origVal) && origVal > 0) {
        data.original_price = Math.round(origVal * 100);
      }

      const sellVal = parseFloat(sellingPriceStr.value);
      if (!isNaN(sellVal) && sellVal > 0) {
        data.selling_price = Math.round(sellVal * 100);
      }

      const ok = await update(data);
      if (ok) {
        if (store.selectedGroups.length > 0) {
          await syncPackageItems(form.id, store.selectedGroups.map(g => g.id!));
        }
        router.go(-1);
      }
    };

    const loadPackageAndItems = async () => {
      await loadPackage();
      const groups = await listPackageItems(form.id);
      if (groups) {
        store.selectedGroups = groups;
      }
    };

    onMounted(() => {
      const saved = sessionStorage.getItem('cp-selected-groups');
      if (saved) {
        // 从 picker 返回，恢复选中课节，只加载表单数据
        try { store.selectedGroups = JSON.parse(saved); } catch(e) {}
        sessionStorage.removeItem('cp-selected-groups');
        loadPackage();
      } else {
        loadPackageAndItems();
      }
    });

    return {
      form, store, originalPriceStr, sellingPriceStr, formatPrice,
      showStatusPicker, statusOptions, onStatusSelect,
      pickCourseGroups, onSubmit,
    };
  },
});
</script>

<style scoped lang="less">
.main {
  padding: 0.32rem 0;
}
</style>
