<script setup lang="ts">
import { ref, onMounted, watch } from "vue";
import { checkPermission } from "@/utils/permissions";
import type { QTableProps } from "quasar";
import { useQuasar } from "quasar";
import { useRoute } from "vue-router";
import http from "@/plugins/http";
import config from "@/app.config";

/** importComponents*/
import DialogMeet from "@/modules/12_evaluatePersonal/components/Detail/viewTab2/DialogMeet.vue";

import type { Meeting } from "@/modules/12_evaluatePersonal/interface/index/Main";
import type { Meetings } from "@/modules/12_evaluatePersonal/interface/response/Main";

/** importStore*/
import { useCounterMixin } from "@/stores/mixin";

/** use*/
const $q = useQuasar();
const route = useRoute();
const mixin = useCounterMixin();
const {
  showLoader,
  hideLoader,
  messageError,
  dialogConfirm,
  date2Thai,
  success,
  dialogRemove,
} = mixin;

/** props*/
const props = defineProps({
  data: {
    type: Array,
    default: [],
  },
  fetchData: {
    type: Function,
    default: () => "",
  },
});

const id = ref<string>(route.params.id as string);

const rows = ref<Meeting[]>([]); //รายการประชุม
const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: false,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "date",
    align: "left",
    label: "วันเวลาในการประชุม",
    sortable: true,
    field: "date",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "title",
    align: "left",
    label: "หัวข้อการประชุม",
    sortable: true,
    field: "title",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "round",
    align: "left",
    label: "ครั้งที่",
    sortable: true,
    field: "round",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "result",
    align: "left",
    label: "ผลการพิจารณาของคณะกรรมการประเมินผลงานแต่ละคณะ",
    sortable: true,
    field: "result",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },

  {
    name: "timePeriod",
    align: "left",
    label: "ระยะเวลาในการแก้ไขผลงาน",
    sortable: true,
    field: "timePeriod",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);

const modalAdd = ref<boolean>(false); //เพิ่มรายการประชุม
const filter = ref<string>(""); //ค้นหารายการประชุม
const page = ref<number>(1); //หน้า
const rowsPerPage = ref<number>(10); //จำนวนต่อหน้า
const maxPage = ref<number>(1); //จำนนวนหน้าทั้งหมด
const listMeet = ref<Meetings[]>([]); //รายชื่อประชุม
const listMeetData = ref<Meetings[]>([]); //รายชื่อประชุม

/**
 * ฟังก์เปิด popup เพิ่มการประชุม
 */
function onClickAdd() {
  modalAdd.value = true;
  getList();
}
/**
 * ฟังก์ปิด popup เพิ่มการประชุม
 */
function onClickClose() {
  modalAdd.value = false;
}

/**
 * function อัดเดท Paging การประชุม
 * @param rpp ต่อหน้า
 * @param p หน้า
 */
async function updatePaging(rpp: number, p: number) {
  page.value = p;
  rowsPerPage.value = rpp;
}

/**
 * function return รายชื่อกรรมการที่เลือก
 * @param data รายชื่อกรรมการที่เลือก
 */
function returnData(data: Meetings[]) {
  const dataList = data.map((item: Meetings) => item.id);
  dialogConfirm($q, () => {
    showLoader();
    http
      .put(config.API.evaluationChooseMeeting(id.value), {
        meetings: dataList,
      })
      .then(async () => {
        await props.fetchData();
        await success($q, "บันทึกสำเร็จ");
        onClickClose();
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

/** function เรียกข้อมูลการประชุม*/
async function getList() {
  showLoader();
  await http
    .get(config.API.meeting() + `/admin`)
    .then((res) => {
      const data = res.data.result;
      const listData = data.map((item: Meetings) => ({
        id: item.id,
        createdAt: item.createdAt,
        createdUserId: item.createdUserId,
        lastUpdatedAt: item.lastUpdatedAt,
        lastUpdateUserId: item.lastUpdateUserId,
        createdFullName: item.createdFullName,
        lastUpdateFullName: item.lastUpdateFullName,
        title: item.title ? item.title : "-",
        round: item.round ? item.round : "-",
        date: `${date2Thai(item.dateStart as Date, false, true)} - ${date2Thai(
          item.dateEnd as Date,
          false,
          true
        )}`,
        result: item.result,
        timePeriod: item.duration,
      }));
      listMeet.value = listData;
      listMeetData.value = listData;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

function handleDelete(meetingId: string) {
  dialogRemove($q, async () => {
    showLoader();
    try {
      await http.delete(
        config.API.evaluationMain() + `/del-meeting/${id.value}/${meetingId}`
      );
      await props.fetchData();
      await success($q, "ลบสำเร็จ");
    } catch (error) {
      messageError($q, error);
    } finally {
      hideLoader();
    }
  });
}

watch(
  () => props.data,
  () => {
    if (props.data) {
      rows.value = props.data.map((item: any) => ({
        id: item.id,
        date: `${date2Thai(item.dateStart as Date, false, true)} - ${date2Thai(
          item.dateEnd as Date,
          false,
          true
        )}`,
        dateStart: item.dateStart,
        title: item.title ? item.title : "-",
        round: item.round ? item.round : "-",
        dateEnd: item.dateEnd,
        result: item.result,
        timePeriod: item.duration,
      }));
    }
  }
);
</script>
<template>
  <q-card bordered class="row col-12" style="border: 1px solid #d6dee1">
    <div
      class="col-xs-12 col-sm-12 text-weight-medium bg-grey-1 q-py-xs q-px-md"
    >
      การประชุม
      <q-btn
        v-if="checkPermission($route)?.attrIsUpdate"
        size="12px"
        flat
        round
        dense
        color="primary"
        class="q-ml-sm"
        icon="mdi-plus"
        @click="onClickAdd"
      >
        <q-tooltip>เพิ่มการประชุม </q-tooltip>
      </q-btn>
    </div>
    <div class="col-12"><q-separator /></div>
    <div class="col-xs-12 q-pa-sm row">
      <d-table
        ref="table"
        flat
        bordered
        dense
        class="col-12"
        :columns="columns"
        :rows="rows"
        row-key="id"
        :paging="true"
      >
        <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-slot:body="props">
          <q-tr :props="props">
            <q-td auto-width>
              <q-btn
                v-if="checkPermission($route)?.attrIsUpdate"
                flat
                round
                dense
                icon="delete"
                color="red"
                @click="handleDelete(props.row.id)"
              >
                <q-tooltip>ลบ</q-tooltip>
              </q-btn>
            </q-td>
            <q-td v-for="col in props.cols" :key="col.name" :props="props">
              <div v-if="col.name == 'no'">
                {{ props.rowIndex + 1 }}
              </div>
              <div>
                {{ col.value }}
              </div>
            </q-td>
          </q-tr>
        </template>
      </d-table>
    </div>
  </q-card>

  <DialogMeet
    v-model:Modal="modalAdd"
    :clickClose="onClickClose"
    v-model:filterKeyword="filter"
    v-model:rows="listMeet"
    v-model:rowsData="listMeetData"
    :rowsPerPage="rowsPerPage"
    :page="page"
    :maxPage="maxPage"
    :selected-row="rows"
    @update:pagination="updatePaging"
    @returnDirector="returnData"
  />
</template>

<style scoped></style>
