<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-cell-group>
      <div style="margin: 16px;">
        <van-button round block type="primary" native-type="submit">保存</van-button>
      </div>
    </van-form>
  </div>
</template>

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

export default defineComponent({
  name: "course-package-add",
  components: {
    [Form.name]: Form,
    [Field.name]: Field,
    [CellGroup.name]: CellGroup,
    [Button.name]: Button,
    [Cell.name]: Cell,
    [Tag.name]: Tag,
  },
  setup() {
    const router = useRouter();
    const {store, create, syncPackageItems} = useCoursePackage();

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

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

    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 pickCourseGroups = () => {
      router.push("/course/group/pick?target=" + PickTargets.COURSE_PACKAGE);
    };

    const onSubmit = async () => {
      const data: any = {
        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: 'ACTIVE',
      };

      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 result = await create(data);
      if (result) {
        if (store.selectedGroups.length > 0) {
          await syncPackageItems(result.id, store.selectedGroups.map(g => g.id!));
        }
        router.go(-1);
      }
    };

    onMounted(() => {
      const saved = sessionStorage.getItem('cp-selected-groups');
      if (saved) {
        try { store.selectedGroups = JSON.parse(saved); } catch(e) {}
        sessionStorage.removeItem('cp-selected-groups');
      } else {
        store.selectedGroups = [];
      }
      (window as any).__cp_debug = {
        onMounted: true,
        saved: saved?.substring(0, 100),
        selectedGroupsLen: store.selectedGroups.length,
        selectedGroupsNames: store.selectedGroups.map((g: any) => g.group_name),
        ts: Date.now()
      };
    });

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

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