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

const router = useRouter();
const route = useRoute();
const id = ref<string>(route.params.id as string);
const mixin = useCounterMixin();
const $q = useQuasar();
const props = defineProps({
  data: {
    type: Array,
    default: [],
  },
  fetchdata: {
    type: Function,
    default: () => "",
  }
});
const { showLoader, hideLoader, messageError, dialogConfirm, date2Thai } =
  mixin;
import DialogMeet from "@/modules/12_evaluatePersonal/components/Detail/viewTab2/DialogMeet.vue";

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: "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 rows = ref<any[]>([]);

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<any>([]);

function onClickAdd() {
  modalAdd.value = true;
}

function onClickClose() {
  modalAdd.value = false;
}

async function fetchListMeet() {}

/**
 * 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: any) {
  const dataList = data.map((item: any) => item.id);
  dialogConfirm($q, () => {
    showLoader();
    http
      .put(config.API.evaluationChooseMeeting(id.value), {
        meetings: dataList,
      })
      .then((res) => {
        console.log(res);
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(() => {
        hideLoader();
        props.fetchdata()
        onClickClose();
      });
  });
}

async function getList() {
  showLoader();
  await http
    .get(
      config.API
        .meeting
        // currentPage.value,
        // rowsPerPage.value,
        // filterKeyword.value
        ()
    )
    .then((res) => {
      // maxPage.value = Math.ceil(res.data.result.total / rowsPerPage.value);
      const data = res.data.result;
      listMeet.value = data.map((item: any) => ({
        id: item.id,
        createdAt: item.createdAt,
        createdUserId: item.createdUserId,
        lastUpdatedAt: item.lastUpdatedAt,
        lastUpdateUserId: item.lastUpdateUserId,
        createdFullName: item.createdFullName,
        lastUpdateFullName: item.lastUpdateFullName,
        title: item.tittle,
        round: item.round,
        date: `${date2Thai(item.dateStart as Date, false, true)} - ${date2Thai(
          item.dateEnd as Date,
          false,
          true
        )}`,
        result: item.result,
        timePeriod: item.duration,
      }));
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}
onMounted(() => {
  getList();
});

watch(
  () => props.data,
  () => {
    if (props.data) {
      console.log(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,
        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
        size="12px"
        flat
        round
        dense
        color="add"
        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 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" class="cursor-pointer">
            <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"
    :rows2="listMeet"
    v-model:filterKeyword2="filter"
    :get-list="fetchListMeet"
    :rowsPerPage="rowsPerPage"
    :page="page"
    :maxPage="maxPage"
    :selected-row="rows"
    @update:pagination="updatePaging"
    @returnDirector="returnData"
  />
</template>

<style scoped></style>
