<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import avatar from "@/assets/avatar_user.jpg";
import { useRoute, useRouter } from "vue-router";
import { useCounterMixin } from "@/stores/mixin";
import http from "@/plugins/http";
import config from "@/app.config";
import { useQuasar, type QTableProps } from "quasar";

interface ListMain {
  id: string;
  round_no: number;
  date_start: string;
  date_finish: string;
  mentors: string;
  commander: string;
  chairman: string;
}

const profileId = ref<string>("");
const $q = useQuasar();
const mixin = useCounterMixin();
const {
  messageError,
  findOrgNameHtml,
  showLoader,
  hideLoader,
  date2Thai,
  onSearchDataTable,
} = mixin;

const mode = ref<any>($q.screen.gt.xs);
const profileImg = ref<string>("");
const router = useRouter();
const route = useRoute();
const id = ref<string>(route.params.id as string);

const idEva = ref<string>(route.params.id as string);
const formData = reactive<any>({
  prefix: "",
  firstName: "",
  lastName: "",
  position: "",
  posExecutiveName: "",
  posTypeName: "",
  posLevelName: "",
  org: "",
});
const sizeImg = ref<string>("");

/** Table */
const rows = ref<ListMain[]>([]);
const rowsMain = ref<ListMain[]>([]);
const filter = ref<string>("");
const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: false,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "date_start",
    align: "left",
    label: "ตั้งแต่วันที่",
    sortable: true,
    field: "date_start",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (v) => date2Thai(v),
  },
  {
    name: "date_finish",
    align: "left",
    label: "ถึงวันที่",
    sortable: true,
    field: "date_finish",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (v) => date2Thai(v),
  },
  {
    name: "mentors",
    align: "left",
    label: "ผู้ดูแล",
    sortable: true,
    field: "mentors",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "commander",
    align: "left",
    label: "ผู้บังคับบัญชา",
    sortable: true,
    field: "commander",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);
const visibleColumns = ref<string[]>([
  "no",
  "date_start",
  "date_finish",
  "mentors",
  "commander",
]);

function onResize(size: any) {
  const width = size.width > 100 ? 100 : size.width;
  sizeImg.value = `${width}px`;
}

/**
 * fetch ข้แมูลส่วนตัว
 */

// เส้นเก่าที่เคยใช้     .get(config.API.kpiEvaluationUser + `/admin/${id.value}`)
async function getMain() {
  showLoader();
  await http
    .get(config.API.kpiEvaluationUser + `/admin/${id.value}`)
    .then(async (res) => {
      const data = await res.data.result;
      formData.prefix = data.prefix;
      formData.firstName = data.firstName;
      formData.lastName = data.lastName;
      formData.position = data.position;
      formData.posTypeName = data.posTypeName;
      formData.posExecutiveName = data.posExecutiveName;
      formData.posLevelName = data.posLevelName;
      formData.isProbation = data.isProbation;
      formData.org = findOrgNameHtml(data);
      profileId.value = data.profileId;
      const promises = [];
      promises.push(getList(data.profileId)); // fetch รายการทดลองงาน
      if (profileId.value) {
        promises.push(fetchProfilePhoto(profileId.value)); // fetch รูปโปรไฟล์
      } else {
        profileImg.value = avatar;
      }
      await Promise.all(promises);
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * fetch รายการทดลองงาน
 * @param id โปรไฟล์
 */
async function getList(id: string) {
  showLoader();
  await http
    .get(config.API.probationGetAssignList(id))
    .then(async (res) => {
      const data = await res.data.result;
      rows.value = data;
      rowsMain.value = data;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * chceck รูปโปรไฟล์
 * @param id  โปรไฟล์
 */
async function fetchProfilePhoto(id: string) {
  await http
    .get(config.API.orgCheckAvatar(id))
    .then(async (res) => {
      // ถ้ามีรูปให่ fetch รูป
      if (res.data.result.avatarName) {
        await http
          .get(
            config.API.fileByFile(
              "ทะเบียนประวัติ",
              "โปรไฟล์",
              id,
              res.data.result.avatarName
            )
          )
          .then(async (res) => {
            profileImg.value = await res.data.downloadUrl;
          })
          .catch((err) => {
            messageError($q, err);
          })
          .finally(() => {
            hideLoader();
          });
      } else {
        // ไม่มีรูปให่ set รูป เป็น default
        profileImg.value = avatar;
      }
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * redairect การทดลองปฏิบัติหน้าที่ราชการ
 * @param id ทดลองงาน
 */
function onDetail(id: string) {
  router.push(`/probation/detail/${profileId.value}/${id}`);
}

function serchDataTable() {
  rows.value = onSearchDataTable(
    filter.value,
    rowsMain.value,
    columns.value ? columns.value : []
  );
}

onMounted(async () => {
  await getMain();
});
</script>
<template>
  <div class="toptitle col-12 row items-center">
    <q-btn
      icon="mdi-arrow-left"
      unelevated
      round
      dense
      flat
      color="primary"
      class="q-mr-sm"
      @click="router.go(-1)"
    />
    รายละเอียดงานที่ได้รับมอบหมาย
    {{
      formData.firstName
        ? `${formData.prefix}${formData.firstName} ${formData.lastName}`
        : ""
    }}
  </div>
  <div class="row q-col-gutter-md">
    <div v-if="$q.screen.gt.xs" class="col-12">
      <q-card>
        <div class="bg-grey-1 row q-pa-sm items-center">
          <span class="text-teal text-weight-bold text-body2">{{
            formData.firstName
              ? `${formData.prefix}${formData.firstName} ${formData.lastName}`
              : "-"
          }}</span>
        </div>
        <q-separator />
        <q-resize-observer @resize="onResize" />
        <q-card-section class="q-pa-md">
          <div class="row">
            <div class="col-2 text-center self-center">
              <q-avatar :size="sizeImg" rounded>
                <q-img
                  :src="profileImg"
                  style="border-radius: 10px; object-fit: cover"
                />
              </q-avatar>
            </div>
            <div class="col-10 column justify-center no-wrap">
              <div class="row text-grey-6">
                <div class="col-4">ตำแหน่งในสายงาน</div>
                <div class="col-4">ตำแหน่งประเภท</div>
                <div class="col-4">สังกัด</div>
              </div>
              <div class="row">
                <div class="col-4 column">
                  <span>
                    {{ formData.position ? formData.position : "-" }}
                  </span>
                  <span>
                    {{
                      formData.isProbation ? `(ทดลองปฏิบัติหน้าที่ราชการฯ)` : ""
                    }}
                  </span>
                </div>
                <div class="col-4">
                  {{
                    formData.posTypeName
                      ? formData.posLevelName
                        ? `${formData.posTypeName}(${formData.posLevelName})`
                        : formData.posTypeName
                      : "-"
                  }}
                </div>
                <div class="col-4 text-html">
                  {{ formData.org ? formData.org.replace("\\n", "\n") : "-" }}
                </div>
              </div>
            </div>
          </div>
        </q-card-section>
      </q-card>
    </div>
    <div v-else class="col-12">
      <q-card bordered>
        <div class="bg-grey-1 row q-pa-sm items-center">
          <span class="text-teal text-weight-bold text-body2">{{
            formData.firstName
              ? `${formData.prefix}${formData.firstName} ${formData.lastName}`
              : "-"
          }}</span>
        </div>
        <q-resize-observer @resize="onResize" />
        <q-card-section>
          <div class="text-center q-mt-md">
            <q-avatar :size="sizeImg" rounded>
              <img
                :src="profileImg"
                style="border-radius: 10px; object-fit: cover"
              />
            </q-avatar>
          </div>
        </q-card-section>

        <q-list class="q-mt-md">
          <q-item>
            <q-item-section>
              <q-item-label class="text-grey-6">ตำแหน่งในสายงาน</q-item-label>
              <q-item-label>{{
                formData.position ? formData.position : "-"
              }}</q-item-label>
            </q-item-section>
          </q-item>
          <q-item>
            <q-item-section>
              <q-item-label class="text-grey-6">ระดับ</q-item-label>
              <q-item-label>{{
                formData.posLevelName ? formData.posLevelName : "-"
              }}</q-item-label>
            </q-item-section>
          </q-item>
          <q-item>
            <q-item-section>
              <q-item-label class="text-grey-6">สังกัด</q-item-label>
              <q-item-label>{{
                formData.org ? formData.org : "-"
              }}</q-item-label>
            </q-item-section>
          </q-item>
        </q-list>
      </q-card>
    </div>

    <div class="col-12 row">
      <q-card bordered class="col-12 q-pa-md">
        <div class="row">
          <q-space />
          <q-input
            outlined
            dense
            v-model="filter"
            label="ค้นหา"
            :style="mode ? `max-width: 200px` : `max-width: 150px`"
            @keydown.enter.prevent="serchDataTable"
          >
            <template v-slot:append>
              <q-icon name="search" />
            </template>
          </q-input>
          <q-select
            v-if="$q.screen.gt.xs"
            class="q-ml-sm"
            dense
            multiple
            outlined
            emit-value
            map-options
            options-dense
            option-value="name"
            style="min-width: 140px"
            v-model="visibleColumns"
            :options="columns"
            :display-value="$q.lang.table.columns"
          />
        </div>
        <div class="q-mt-sm">
          <d-table
            flat
            dense
            bordered
            ref="table"
            virtual-scroll
            :rows="rows"
            :columns="columns"
            :grid="!$q.screen.gt.xs"
            :rows-per-page-options="[10, 25, 50, 100]"
            :visible-columns="visibleColumns"
            :virtual-scroll-sticky-size-start="48"
          >
            <template v-slot:header="props">
              <q-tr :props="props">
                <q-th auto-width />
                <q-th v-for="col in props.cols" :key="col.name" :props="props">
                  <span class="text-weight-medium">{{ col.label }}</span>
                </q-th>
              </q-tr>
            </template>

            <template v-if="$q.screen.gt.xs" v-slot:body="props">
              <q-tr :props="props">
                <q-td auto-width>
                  <q-btn
                    flat
                    dense
                    color="info"
                    icon="mdi-eye"
                    round
                    @click="onDetail(props.row.id)"
                  >
                    <q-tooltip> ดูรายละเอียด </q-tooltip>
                  </q-btn>
                </q-td>
                <q-td v-for="col in props.cols" :key="col.name">
                  <div v-if="col.name == 'no'">
                    {{ props.rowIndex + 1 }}
                  </div>
                  <div v-else-if="col.name == 'status'">
                    {{ props.row.status ? props.row.status : "-" }}
                  </div>
                  <div v-else>
                    {{ col.value ? col.value : "-" }}
                  </div>
                </q-td>
              </q-tr>
            </template>
            <template v-else v-slot:item="props">
              <div class="q-mb-xs col-xs-12 col-sm-6 col-md-4 col-lg-3">
                <q-card bordered flat>
                  <q-list dense class="q-mt-lg relative-position">
                    <q-btn
                      icon="info"
                      color="info"
                      flat
                      dense
                      round
                      size="14px"
                      class="absolute_button"
                      @click="onDetail(props.row.id)"
                    >
                      <q-tooltip>ประวัติแก้ไขตำแหน่ง/เงินเดือน</q-tooltip>
                    </q-btn>
                    <q-item v-for="col in props.cols" :key="col.name">
                      <q-item-section class="fix_top">
                        <q-item-label class="text-grey-6 text-weight-medium">{{
                          col.label
                        }}</q-item-label>
                      </q-item-section>
                      <q-item-section class="fix_top">
                        <q-item-label class="text-dark text-weight-medium">{{
                          col.value ? col.value : "-"
                        }}</q-item-label>
                      </q-item-section>
                    </q-item>
                  </q-list>
                </q-card>
              </div>
            </template>
            <template v-slot:no-data>
              <div
                class="full-width row flex-center q-pa-sm rounded-borders text-weight-medium"
              >
                <span> ไม่พบข้อมูล </span>
              </div>
            </template>
          </d-table>
        </div>
      </q-card>
    </div>
  </div>
</template>
<style scoped>
.absolute_button {
  position: absolute;
  right: 5px;
  top: -20px;
}

.fix_top {
  justify-content: start !important;
}
</style>
