<script setup lang="ts">
import { ref, onMounted, defineProps, watch } from "vue";
import http from "@/plugins/http";
import config from "@/app.config";
import { useQuasar } from "quasar";

import type { QTableProps } from "quasar";
import type { Director } from "@/modules/11_discipline/interface/request/disciplinary";
import type {
  responseType,
  directorType,
} from "@/modules/11_discipline/interface/index/Main";

import DialogDirector from "@/modules/12_evaluatePersonal/components/Detail/viewTab2/DialogDirector.vue";

/** import store*/
import { useCounterMixin } from "@/stores/mixin";
import { useRouter, useRoute } from "vue-router";
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, success } = mixin;

const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: false,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "name",
    align: "left",
    label: "ชื่อ - นามสกุล",
    sortable: true,
    field: "name",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "position",
    align: "left",
    label: "ตำแหน่ง",
    sortable: true,
    field: "position",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "email",
    align: "left",
    label: "อีเมล",
    sortable: true,
    field: "email",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "phone",
    align: "left",
    label: "เบอร์โทรศัพท์",
    sortable: true,
    field: "phone",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);
const rows = ref<Director[]>([]);

const modalAddDirector = ref<boolean>(false);
const filter = ref<string>("");
const page = ref<number>(1);
const rowsPerPage = ref<number>(10);
const maxPage = ref<number>(1);
const listDirector = ref<any>([]);

async function onClickAdd() {
  modalAddDirector.value = true;
}

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

/** function เรียกรายชื่อกรรมการ*/
async function fetchDListDirector() {
  // showLoader();
  // await http
  //   .get(config.API.directorList(page.value, rowsPerPage.value, filter.value))
  //   .then((res) => {
  //     maxPage.value = Math.ceil(res.data.result.total / rowsPerPage.value);
  //     const data = res.data.result.data;
  //     let datalistDirector: responseType[] = data.map((e: directorType) => ({
  //       id: e.id,
  //       directorId: e.directorId,
  //       name: `${e.prefix}${e.firstName} ${e.lastName}`,
  //       prefix: e.prefix,
  //       firstName: e.firstName,
  //       lastName: e.lastName,
  //       position: e.position,
  //       email: e.email,
  //       phone: e.phone,
  //       total: e.total,
  //       duty: e.duty,
  //     }));
  //     // /** หารานชื่อกรรมการที่ไม่ซ้ำ*/
  //     listDirector.value = datalistDirector.filter(
  //       (i) => !rows.value.some((e) => e.directorId === i.id)
  //     );
  //   })
  //   .catch((err) => {
  //     messageError($q, err);
  //   })
  //   .finally(() => {
  //     hideLoader();
  //   });
}

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

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

function getList() {
  showLoader();
  http
    .get(config.API.evaluateDirectorMain())
    .then((res) => {
      // maxPage.value = Math.ceil(res.data.result.total / rowsPerPage.value);
      const data = res.data.result;

      listDirector.value = data.map((item: any) => ({
        id: item.id,
        name: `${item.prefix}${item.firstName} ${item.lastName}`,
        createdAt: item.createdAt,
        createdUserId: item.createdUserId,
        lastUpdatedAt: item.lastUpdatedAt,
        lastUpdateUserId: item.lastUpdateUserId,
        createdFullName: item.createdFullName,
        lastUpdateFullName: item.lastUpdateFullName,
        prefix: item.prefix,
        firstName: item.firstName,
        lastName: item.lastName,
        phone: item.phone,
        email: item.email,
        position: item.position,
      }));
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

watch(
  () => props.data,
  () => {
    if (props.data) {
      rows.value = props.data.map((item: any) => ({
        id:item.id,
        name:`${item.prefix}${item.firstName} ${item.lastName}`,
        prefix:item.prefix,
        firstName:item.firstName,
        lastName:item.lastName,
        position:item.position,
        positionName:item.positionName,
        email:item.email,
        phone:item.phone,
      }));
    }
  }
);

onMounted(() => {
  getList();
});
</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-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>

  <DialogDirector
    v-model:Modal="modalAddDirector"
    :clickClose="onClickClose"
    :rows2="listDirector"
    v-model:filterKeyword2="filter"
    :get-list="fetchDListDirector"
    :rowsPerPage="rowsPerPage"
    :page="page"
    :maxPage="maxPage"
    :selected-row="rows"
    @update:pagination="updatePaging"
    @returnDirector="returnDirector"
  />
</template>

<style scoped></style>
