<template>
  <section class="flex flex-col gap-4">
    <Panel :header="$t('createCourse')">
      <div class="grid grid-cols-3 gap-7">
        <div class="flex flex-col gap-1">
          <FloatLabel>
            <InputText class="w-full" v-model="newCourse.name" />
            <label>{{ $t("title") }}</label>
          </FloatLabel>
        </div>

        <div class="flex flex-col gap-1">
          <FloatLabel>
            <InputText class="w-full" v-model="newCourse.language" />
            <label>{{ $t("زبان آموزش") }}</label>
          </FloatLabel>
        </div>
        <div class="flex flex-col gap-1">
          <FloatLabel>
            <InputText v-model="newCourse.duration" class="w-full" />
            <label>{{ $t("مدت زمان دوره") }}</label>
          </FloatLabel>
        </div>

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

        <!-- <div class="flex flex-col gap-1">
          <FloatLabel>
            <InputText class="w-full" v-model="newCourse.categories" />
            <label>{{ $t("دسته بندی") }}</label>
          </FloatLabel>
        </div> -->

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

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

        <div class="flex flex-col gap-1">
          <FloatLabel>
            <InputText class="w-full" v-model="newCourse.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">
                <i class="pi pi-image ml-2"></i>
                <span>{{ $t("chooseImage") }}</span>
                <input
                  type="file"
                  class="opacity-0 absolute inset-0 cursor-pointer"
                  accept="image/*"
                  @input="chooseImage"
                />
              </Button>
            </InputGroup>
            <label>{{ $t("image") }}</label>
          </FloatLabel>
        </div>
      </div>

      <div class="flex w-full mt-7">
        <div class="basis-4/6">
          <FloatLabel>
            <Editor
              v-model="newCourse.description"
              placeholder="توضیحات"
              editorStyle="height: 320px"
            />
          </FloatLabel>
        </div>

        <div class="basis-2/6 ms-8">
          <div class="card flex flex-col gap-2 justify-center">
            <Listbox
              listStyle="height:240px"
              emptyMessage="دسته بندی وجود ندارد"
              emptyFilterMessage="دسته بندی وجود ندارد"
              v-model="selectedCity"
              filterPlaceholder=" دسته بندی"
              :options="cities"
              filter
              optionLabel="name"
              class="w-full"
            />
          </div>
          <div></div>
        </div>
      </div>

      <!-- 
      <div class="flex flex-col gap-1">
        <InputGroup>
          <FloatLabel>
            <Dropdown
              :options="cities"
              :optionLabel="cities.name"
              :optionValue="cities.name"
              class="w-full"
            >
            </Dropdown>
            <label>{{ $t("brand") }}</label>
          </FloatLabel>
        </InputGroup>
   
      </div> -->

      <div class="flex pt-4 justify-end">
        <Button
          :label="$t('create')"
          icon="pi pi-save"
          severity="success"
          :loading="saving"
          @click="create(newCourse)"
        />
      </div>
    </Panel>
  </section>
</template>

<script setup>
import Listbox from "primevue/listbox";
import { jDate } from "@/utils/jDate";
import { treeTogglerRTL } from "@/utils/tree-toggler-rtl";

import {
  inject,
  defineAsyncComponent,
  watchEffect,
  ref,
  watch,
  nextTick,
  reactive,
} from "vue";

import { useStaticsStore } from "@/stores/statics";
import { useUploaderStore } from "@/stores/uploader";
import { useProductsStore } from "@/stores/products";
import { useCategoriesStore } from "@/stores/categoreis";
const categoriesStore = useCategoriesStore();
const courseStore = useProductsStore();
const uploadStore = useUploaderStore();
import { useRoute } from "vue-router";
const route = useRoute();
const level = ref(null)
watchEffect(async () => {
  const { page = 1, rows = 10 } = route.query;
  const categoriess = await categoriesStore.index(page, rows);
  console.log("cat", categoriess);
  cities.value = categoriess;
});
const selectedCity = ref();
const cities = ref();
const levels = reactive(["آسان", "متوسط", "سخت"]);
const newCourse = reactive({
  name: "",
  description: "",
  slug: "",
  duration: "",
  image: "",
  categories: "",
  price: 0,
  teacher: "",
  completionPercentage: 0,
  level: "",
  language: "",
  countOfVideos: 0,
  totalFileSize: "",
});
const chooseImage = async (el) => {
  const uploader = await uploadStore.uploader(el.target.value);
  //console.log('uploader', uploader.data.url);
  newCourse.image = uploader.data.url;
  console.log("تصویر آپلود شد");
  console.log("upldr", uploader);
};
const create = async (data) => {
  if (newCourse.image === "") {
    return console.log("تصویر دوره وارد نشده است");
  }
  if (
    newCourse.name === "" ||
    newCourse.description === "" ||
    // newCourse.slug === "" ||
    newCourse.duration === "" ||
    // newCourse.categories === "" ||
    // newCourse.teacher === "" ||
    newCourse.completionPercentage === 0 ||
    // newCourse.level === "" ||
    // newCourse.language === "" ||
    newCourse.countOfVideos === "" ||
    newCourse.totalFileSize === ""
  ) {
    return console.log("تمام مقادیر را وارد کنید");
  }
  newCourse.name = data.name;
  newCourse.description = data.description;
  newCourse.slug = data.name;
  newCourse.duration = data.duration;
  // newCourse.categories = data.categories;
  newCourse.categories = "66587ae698d0a0db14693a5e";
  // newCourse.teacher = data.teacher;
  newCourse.teacher = "66530b0480ef484e2bd19220";
  // newCourse.completionPercentage = data.completionPercentage;
  newCourse.completionPercentage = 20;
  // newCourse.level = data.level;
  newCourse.level = "متوسط";
  // newCourse.language = data.language;
  newCourse.language = "فارسی";
  newCourse.countOfVideos = data.countOfVideos;
  newCourse.totalFileSize = data.totalFileSize;
  // console.log("newCourse: ", newCourse);
  const creat = await courseStore.create(newCourse);
  console.log("created", creat);
};
//   console.log("form", data);
//   console.log("json", JSON.stringify(data));
//   const { result } = await store.edit(data);
//   console.log("res", result);
// };
const expandedKeys = ref({});

const CategoryForm = defineAsyncComponent(() =>
  import("../components/CategoryForm.vue")
);

const { dialog, confirm, toast, t } = inject("service");

const store = useStaticsStore();

watchEffect(async () => {
  await store.index();
  // console.log(store.items);

  //data.videosCount = store.items.hours;
});
</script>

<!-- 
<script setup>
import { useUploaderStore } from "@/stores/uploader";
import FirstStep from "../components/ProductFormSteps/FirstStep.vue";
import SecondStep from "../components/ProductFormSteps/SecondStep.vue";
import ThirdStep from "../components/ProductFormSteps/ThirdStep.vue";

import { inject, provide, reactive, ref } from "vue";
import { useProductsStore } from "@/stores/products";

const dialog = inject("dialogRef");
const { toast, t } = inject("service");
// const { product } = dialog.data

 //const form = reactive(Object.assign({}, product || {}));
//console.log(form);
const errors = reactive({});

const saving = ref(false);

provide("data", { errors, saving });

const store = useProductsStore();

const uploader = useUploaderStore();

const save = async () => {
  saving.value = true;

  console.log(form);

  //Upload File
  if (typeof form.coverImage === "object") {
    const { status, data } = await uploader.single(form.coverImage);

    if (status === 201) form.coverImage = data.url;
    else
      return toast.add({
        life: 2000,
        severity: "error",
        summary: t("error"),
        detail: data.msg,
      });
  }

  //upload images
  const files = form.images.filter((image) => typeof image === "object");
  if (files.length > 0) {
    const { status, data } = await uploader.bulk(files);

    if (status === 201)
      form.images = form.images.map((image) => {
        if (typeof image === "object") return data.urls.shift();
        return image;
      });
    else
      return toast.add({
        life: 2000,
        severity: "error",
        summary: t("error"),
        detail: data.msg,
      });
  }

  //Create or Update
//   const { status, data } = !!product
//     ? await store.update(product._id, form)
//     : await store.store(form);

//   saving.value = false;

//   if (status === 200 || status === 201) {
//     toast.add({
//       life: 2000,
//       severity: "success",
//       summary: t("successful"),
//       detail: t(!!category ? "updateSuccessfully" : "storeSuccessfully"),
//     });
//     dialog.value.close();
//   } else if (status === 422) Object.assign(errors, data);
//   else
//     toast.add({
//       severity: "error",
//       life: 2000,
//       detail: data.msg,
//       summary: t("error"),
//     });
};
</script>

<style lang="scss" scoped></style> -->