<template>
  <section class="flex flex-col gap-4">
    <Panel :header="$t('ویرایش اطلاعات دوره')">
      <div class="flex">
        <div class="basis-4/6">
          <div class="grid grid-cols-2 gap-7">
            <div class="flex flex-col gap-1">
              <FloatLabel>
                <InputText
                  @change="setSlug"
                  class="w-full"
                  v-model="course.name"
                />
                <label>{{ $t("title") }}</label>
              </FloatLabel>
            </div>

            <div class="flex flex-col gap-1">
              <FloatLabel>
                <Dropdown
                  v-model="course.language"
                  @change="selectLanguage"
                  :options="['انگلیسی', 'فارسی']"
                  class="w-full"
                />
                <label>{{ $t("زبان آموزش") }}</label>
              </FloatLabel>
            </div>
            <div class="flex flex-col gap-1">
              <FloatLabel>
                <InputText
                  v-model="course.duration"
                  class="w-full"
                  prefix="ساعت"
                />
                <label>{{ $t("مدت زمان دوره") }}</label>
              </FloatLabel>
            </div>

            <div class="flex flex-col gap-1">
              <FloatLabel>
                <Dropdown
                  v-model="course.level"
                  @change="selectLevel"
                  :options="['مبتدی', 'متوسط', 'پیشرفته']"
                  class="w-full"
                />
                <label>{{ $t("سطح دوره") }}</label>
              </FloatLabel>
            </div>

            <div class="flex flex-col gap-1">
              <FloatLabel>
                <InputText
                  class="w-full"
                  v-model="course.completionPercentage"
                />
                <label>{{ $t("درصد تکمیل دوره") }}</label>
              </FloatLabel>
            </div>

            <div class="flex flex-col gap-1">
              <FloatLabel>
                <InputText class="w-full" v-model="course.countOfVideos" />
                <label>{{ $t("تعداد ویدیو ها") }}</label>
              </FloatLabel>
            </div>

            <div class="flex flex-col gap-1">
              <FloatLabel>
                <InputText class="w-full" v-model="course.totalFileSize" />
                <label>{{ $t("حجم کل دوره") }}</label>
              </FloatLabel>
            </div>

            <div class="flex flex-col gap-1">
              <FloatLabel>
                <InputGroup>
                  <InputText class="pointer-events-none truncate" dir="ltr" />
                  <Button severity="secondary" :loading="saving">
                    <i class="pi pi-image ml-2"></i>
                    <span>{{ $t("chooseImage") }}</span>
                    <input
                      type="file"
                      :value="course.image"
                      class="opacity-0 absolute inset-0 cursor-pointer"
                      @input="chooseImage"
                    />
                  </Button>
                </InputGroup>
                <label>{{ $t("image") }}</label>
              </FloatLabel>
            </div>
          </div>
          <div class="w-full mt-7">
            <FloatLabel>
              <Editor
                v-model="course.description"
                placeholder="توضیحات"
                editorStyle="height: 315px"
              />
            </FloatLabel>
          </div>
        </div>

        <div class="basis-2/6 flex flex-col gap-7 ms-7">
          <div class="flex flex-col gap-1">
            <FloatLabel>
              <InputText class="w-full" v-model="course.price" />
              <label>{{ $t("قیمت دوره") }}</label>
            </FloatLabel>
          </div>
          <span class="hidden">{{ course.price }}</span>
          <Listbox
            listStyle="height:240px"
            emptyMessage="دسته بندی وجود ندارد"
            emptyFilterMessage="دسته بندی وجود ندارد"
            v-model="selectedCategory"
            @change="selectCategory"
            filterPlaceholder=" دسته بندی"
            :options="cities"
            filter
            optionLabel="name"
            class="w-full"
          />

          <Listbox
            listStyle="height:240px"
            emptyMessage="مدرس مورد نظر یافت نشد"
            emptyFilterMessage="مدرس وجود ندارد"
            v-model="selectedteacher"
            @change="selectTeacher"
            filterPlaceholder=" مدرس دوره"
            :options="teachers"
            filter
            optionLabel="name"
            class="w-full"
          />
        </div>
      </div>



      <div class="flex pt-4 justify-end">
        <Button
          :label="$t('edit')"
          icon="pi pi-save"
          severity="success"
          :loading="creating"
          @click="editCourse"
        />
      </div>
    </Panel>

    <Message
      v-if="saving"
      class="absolute right-12 bottom-8"
      icon="pi pi-spinner-dotted"
      severity="info"
      >درحال آپلود تصویر...</Message
    >
  </section>
</template>
<script setup>
import { useProductsStore } from "@/stores/products";
import { ref, watchEffect, reactive, inject } from "vue";
import { useUploaderStore } from "@/stores/uploader";
import { useCategoriesStore } from "@/stores/categoreis";
import { useUsersStore } from "../stores/users";
const categoriesStore = useCategoriesStore();
const courseStore = useProductsStore();
const uploadStore = useUploaderStore();
const userStore = useUsersStore();
import { useRouter, useRoute } from "vue-router";
const route = useRoute()
const selectedCategory = ref();
const selectedteacher = ref();
const saving = ref(false);
const teachers = ref();
const creating = ref(false);
const store = useProductsStore();
const data = ref(null);
const cities = ref();

const selectCategory = () => {
  course.categories = selectedCategory.value.id;
};
const selectTeacher = () => {
  course.teacher = selectedteacher.value.id;
};


const course = reactive({
  id: route.params.id,
  name: "",
  description: "",
  slug: "",
  duration: "",
  image: "",
  categories: "",
  price: "",
  teacher: "",
  completionPercentage: null,
  level: "",
  language: "",
  countOfVideos: null,
  totalFileSize: "",
});


watchEffect(async () => {
  const { page = 1, rows = 10 } = route.query;
  const categoriess = await categoriesStore.index(page, rows);
  cities.value = categoriess;
});
watchEffect(async () => {
  await userStore.index();
  teachers.value = userStore.items.user;
});
watchEffect(async () => {
  data.value = await store.edit(route.params.id);
  course.name = data.value.course.name;
  course.description = data.value.course.description;
  course.slug = data.value.course.slug;
  course.duration = data.value.course.duration;
  course.image = data.value.course.image;
  course.categories = data.value.course.categories;
  course.price = data.value.course.price;
  course.teacher = data.value.course.teacher;
  course.completionPercentage = data.value.course.completionPercentage;
  course.level = data.value.course.level;
  course.language = data.value.course.language;
  course.countOfVideos = data.value.course.countOfVideos;
  course.totalFileSize = data.value.course.totalFileSize;
});


const chooseImage = async (val) => {
  saving.value = true;
  const uploader = await uploadStore.uploader(val.target.files[0]);
  course.image = uploader.data.url;
  saving.value = false;
  if (uploader.status === 200 || uploader.status === 201) {
    toast.add({
      life: 2000,
      severity: "success",
      summary: t("successful"),
      detail: t("تصویر آپلود شد"),
    });
  } else {
    return toast.add({
      life: 2000,
      severity: "error",
      summary: t("error"),
      detail: t("خطا در بارگذاری تصویر، مجدد تلاش کنید"),
    });
  }
};
const { toast, t } = inject("service");
const router = useRouter()
const editCourse = async (data) => {
  creating.value = true;
  if (
    course.name === "" ||
    course.description === "" ||
    course.duration === "" ||
    course.categories === "" ||
    course.price === null ||
    course.teacher === "" ||
    course.completionPercentage === null ||
    course.level === "" ||
    course.language === "" ||
    course.countOfVideos === null ||
    course.totalFileSize === ""
  ) {
    return toast.add({
      life: 2000,
      severity: "error",
      summary: t("error"),
      detail: t("تمام فیلد ها را وارد کنید"),
    });
  }
  if (course.image === "" || course.image === null) {
    creating.value = false;
    return toast.add({
      life: 2000,
      severity: "error",
      summary: t("error"),
      detail: t("تصویر دوره را وارد کنید"),
    });
  }
  const update = await courseStore.update(course);
  creating.value = false
  toast.add({
      life: 2000,
      severity: "success",
      summary: t("successful"),
      detail: t("دوره با موفقیت ویرایش شد"),
    });
router.push('/courses')
};
</script>