<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">
            {{ fullname }}
          </div>
          <div>{{ 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, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useCounterMixin } from "@/stores/mixin";
import { useQuasar } from "quasar";
import http from "@/plugins/http";
import config from "@/app.config";

const props = defineProps({
  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,
  showLoader,
  hideLoader,
} = mixin;

const route = useRoute();
const router = useRouter();

const fullname = ref<string>("");
const position = ref<string>("");

const imageUrl = ref<any>(null);
const inputImage = ref<any>(null);
const activeImage = ref<any | null>(null);

const dialogImage = ref<boolean>(false);

const images = ref<any>([]);

onMounted(async () => {
  await fetchData();
});

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

const clickImage = async () => {
  // ***************************************************************************************************
  //                  ****************** fetch data รูปภาพทั้งหมด ******************
  // ***************************************************************************************************
  await fetchAvatarHistory();
  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]);
    showLoader();
    await http
      .post(config.API.profileAvatarId(route.params.id.toString()), formData)
      .then((res) => {})
      .catch((e) => {
        messageError($q, e);
      })
      .finally(async () => {
        await fetchData();
        dialogImage.value = false;
      });
    return;
  }
};

const selectAvatarHistory = async () => {
  if (activeImage.value == null) {
    dialogMessage(
      $q,
      "ไม่สามารถเปลี่ยนรูปได้",
      "กรุณาเลือกรูปที่ต้องการเปลี่ยน",
      "warning",
      undefined,
      "orange",
      undefined,
      undefined,
      true
    );
    return;
  }
  showLoader();
  await http
    .put(config.API.profileAvatarId(route.params.id.toString()), {
      avatar: activeImage.value.avatarId,
    })
    .then((res) => {
      dialogImage.value = false;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      await fetchData();
    });
  // ***************************************************************************************************
  //                 ****************** 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) => {
  showLoader();
  await http
    .delete(config.API.profileAvatarHistoryId(id))
    .then((res) => {
      success($q, "ลบรูปภาพสำเร็จ");
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      await fetchData();
      await clickImage();
      //   dialogImage.value = false;
    });
};

const fetchData = async () => {
  showLoader();
  await http
    .get(config.API.profileAvatarId(route.params.id.toString()))
    .then((res) => {
      const data = res.data.result;
      fullname.value = data.fullname;
      imageUrl.value = data.avatar;
      position.value = data.position;
      //   profileType.value = data.profileType;
      //   employeeClass.value =
      //     data.employeeClass == null ? "" : data.employeeClass;
      //   const reason = reasonOptions.value.filter(
      //     (r: DataOption) => r.id == data.leaveReason
      //   );
      //   if (reason.length > 0) {
      //     leaveReason.value = ` (พ้นจากราชการด้วยสาเหตุ: ${reason[0].name})`;
      //   } else {
      //     leaveReason.value = "";
      //   }
      //   reasonStatus.value = reason.length > 0 ? true : false;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
};

const fetchAvatarHistory = async () => {
  showLoader();
  await http
    .get(config.API.profileAvatarHistoryId(route.params.id.toString()))
    .then((res) => {
      const data = res.data.result;
      images.value = [];
      data.map((e: any) => {
        images.value.push({
          id: e.id,
          avatar: e.avatar,
          avatarId: e.avatarId,
          createdDate: new Date(e.createdDate),
          isActive: e.isActive,
        });
      });
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
};

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>
