<template>
  <q-page-sticky
    position="top"
    expand
    class="bg-grey-2 text-white"
    style="z-index: 99; padding: 0% 1% 0% 1%"
  >
    <div class="row col-12 q-gutter-sm q-pb-sm text-dark no-wrap items-center">
      <q-btn
        flat
        round
        class="bg-teal-1 full-height"
        color="primary"
        icon="mdi-chevron-left"
        dense
        @click="router.go(-1)"
      >
      </q-btn>
      <q-avatar
        v-if="imageUrl == null"
        size="65px"
        rounded
        class="containerimage"
      >
        <img
          src="@/assets/avatar_user.jpg"
          class="bg-grey-3"
          style="object-fit: cover"
        />
        <div
          class="overlay absolute-bottom text-subtitle2 text-center cursor-pointer"
          @click="clickImage()"
        >
          <q-icon name="mdi-camera" size="18px" color="blue">
            <q-tooltip>อัปเดตรูปภาพ</q-tooltip>
          </q-icon>

          <input
            type="file"
            style="display: none"
            ref="inputImage"
            accept="image/*"
            @change="uploadImage"
          />
        </div>
      </q-avatar>
      <q-avatar v-else size="65px" rounded class="containerimage">
        <img :src="imageUrl" class="bg-grey-3" style="object-fit: cover" />
        <div
          class="overlay absolute-bottom text-subtitle2 text-center cursor-pointer"
          @click="clickImage()"
        >
          <q-icon name="mdi-camera" size="18px" color="blue">
            <q-tooltip>อัปเดตรูปภาพ</q-tooltip>
          </q-icon>

          <input
            type="file"
            style="display: none"
            ref="inputImage"
            accept="image/*"
            @change="uploadImage"
          />
        </div>
      </q-avatar>
      <div class="row items-center text-dark q-ml-md">
        <div class="column">
          <div class="text-bold q-pb-xs text-name">
            {{ props.fullName }}
          </div>
          <div>{{ props.position }}</div>
        </div>
      </div>
      <q-space />

      <slot name="button-right" />
    </div>
  </q-page-sticky>
  <!---------------------------------------- Dialog เลือก Image ---------------------------------------->
  <q-dialog v-model="dialogImage" persistent>
    <q-card style="width: 100vw; max-width: 60vw">
      <q-card-section class="q-py-sm row">
        <div class="text-h6">เลือกรูปภาพ</div>
        <q-space />
        <q-btn
          icon="close"
          unelevated
          round
          dense
          @click="closeImage"
          style="color: #ff8080; background-color: #ffdede"
        >
          <q-tooltip>ปิดหน้านี้</q-tooltip>
        </q-btn>
      </q-card-section>
      <q-separator />
      <q-card-section class="col-12 row">
        <div
          class="row wrap items-start col-12 q-col-gutter-sm"
          style="height: 320px; overflow: auto"
        >
          <div class="col-3" @click="addNewImage">
            <div
              style="
                height: 160px;
                max-width: 15vw;
                display: flex !important;
                justify-content: center;
                align-items: center;
              "
              class="column rounded-borders cursor-pointer bg-active-image text-white"
            >
              <q-icon name="add" size="60px" color="white" />
              <strong>อัปโหลดรูปภาพ</strong>
            </div>
          </div>
          <div
            v-for="n in images"
            :key="n"
            class="col-3"
            @click="imageActive(n)"
          >
            <div :class="getClass(n)">
              <q-img
                v-if="n.avatar != null"
                :src="n.avatar"
                :class="imageClass(n)"
              >
                <div
                  class="absolute-bottom col-12 cursor-pointer flex justify-between items-center"
                  style="padding: 5px"
                >
                  {{ date2Thai(n.createdDate) }}

                  <q-btn
                    v-if="!n.isActive"
                    icon="delete"
                    unelevated
                    dense
                    @click="deletePhoto(n.id)"
                    class="bg-white"
                    style="color: #ff8080"
                  />
                </div>
              </q-img>
            </div>
          </div>
        </div>
      </q-card-section>
      <q-separator />
      <q-card-actions align="right">
        <q-btn
          icon="check"
          dense
          flat
          round
          @click="selectAvatarHistory"
          color="positive"
        >
          <q-tooltip>เลือกรูปภาพ</q-tooltip>
        </q-btn>
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>
<script setup lang="ts">
import { ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useCounterMixin } from "@/stores/mixin";
import { useQuasar } from "quasar";

const props = defineProps({
  fullName: {
    type: String,
    default: "ชื่อ สกุล",
    required: true,
  },
  position: {
    type: String,
    default: "ตำแหน่ง",
    required: true,
  },
  fetchData: {
    type: Function,
    default: () => console.log("not function"),
  },
  fetchSave: {
    type: Function,
    default: () => console.log("not function"),
  },
  fetchDelete: {
    type: Function,
    default: () => console.log("not function"),
  },
  fetchUpload: {
    type: Function,
    default: () => console.log("not function"),
  },
});

const $q = useQuasar();
const mixin = useCounterMixin();
const { date2Thai, dateToISO, messageError, dialogMessage, success } = mixin;

const router = useRouter();
const imageUrl = ref<any>(null);
const inputImage = ref<any>(null);
const dialogImage = ref<boolean>(false);
const images = ref<any>([]);
const activeImage = ref<any | null>(null);
const profileId = ref<string>("");

const closeImage = () => {
  dialogImage.value = false;
};

const clickImage = async () => {
  // ***************************************************************************************************
  //                  ****************** fetch data รูปภาพทั้งหมด ******************
  // ***************************************************************************************************

  dialogImage.value = true;
};

const uploadImage = async (e: any) => {
  let input = e.target.files;
  if (input.length > 0) {
    const formData = new FormData();
    formData.append("FileData", input[0]);
    await props.fetchUpload(profileId.value, formData).then(async () => {
      await props.fetchData();
      closeImage();
    });
    // ***************************************************************************************************
    //          ****************** ต้องทำ function props รับ formData กลับ ******************
    //     ****************** finally ทำการ fetch data,dialogImage.value = false ******************
    // ***************************************************************************************************
  }
};

const selectAvatarHistory = async () => {
  if (activeImage.value == null) {
    dialogMessage(
      $q,
      "ไม่สามารถเปลี่ยนรูปได้",
      "กรุณาเลือกรูปที่ต้องการเปลี่ยน",
      "warning",
      undefined,
      "orange",
      undefined,
      undefined,
      true
    );
    return;
  }
  await props.fetchSave(profileId.value);
  // ***************************************************************************************************
  //                 ****************** fetch data เปลี่ยนรูปภาพ ส่ง ID กลับ******************
  // ***************************************************************************************************
};

const imageActive = (n: any) => {
  activeImage.value = n;
};

const addNewImage = () => {
  inputImage.value.click();
  imageActive(null);
};

const deletePhoto = async (id: string) => {
  dialogMessage(
    $q,
    "ลบข้อมูล",
    "ต้องการทำการลบข้อมูลนี้ใช่หรือไม่",
    "delete",
    undefined,
    "red",
    async () => await fetchDataDelete(id),
    undefined,
    false
  );
};

const fetchDataDelete = async (id: string) => {
  await props.fetchDelete(id).then(async () => {
    await props.fetchData();
    await clickImage();
  });
  // ***************************************************************************************************
  //                  ****************** fetch delete รูปภาพ ******************
  //          ****************** finally ทำการ fetch data,clickImage() ******************
  // ***************************************************************************************************
};

const imageClass = (n: any) => {
  const val = n == activeImage.value;
  return {
    "rounded-borders bg-grey-2 image-size-default": val,
    "rounded-borders bg-grey-2 image-size-full": !val,
  };
};

const getClass = (n: any) => {
  const val = n == activeImage.value;
  return {
    "rounded-borders border-green shadow-1": val,
    "rounded-borders shadow-1": !val,
  };
};
</script>
<style lang="scss" scoped>
.image-size-default {
  height: 150px;
  max-width: 15vw;
}

.image-size-full {
  height: 160px;
  max-width: 15vw;
}

.border-green {
  border: 5px solid #52c688;
}

.area-div {
  background-color: transparent;
}

.text-header {
  font-size: 1.2em;
}

.containerimage {
  position: relative;
}

.containerimage:hover .overlay {
  opacity: 1;
}

.overlay {
  background-color: #e4f2ffd2 !important;
  opacity: 0;
  padding: 2px !important;
}

.information:target {
  padding-top: 84px;
}

.border-custom {
  border: 0.5px solid #c3c3c3;
}

.bg-active-image {
  background-color: #52c688;
}

.text-name {
  font-size: 1.25em;
  overflow: hidden;
}
</style>
