<script setup lang="ts">
import { ref, watch } from "vue";
import { useQuasar } from "quasar";

import { useCounterMixin } from "@/stores/mixin";
import http from "@/plugins/http";
import config from "@/app.config";

import type { QTableProps } from "quasar";

import DialogHeader from "@/components/DialogHeader.vue";

const $q = useQuasar();
const { dialogConfirm, showLoader, hideLoader, messageError } =
  useCounterMixin();

const isAct = ref<boolean>(false);
const search = ref<string>("");
const modal = defineModel<boolean>("modal", { required: true });
const props = defineProps({
  stateId: { type: String, require: true },
  fetchData: { type: Function, require: true },
  type: { type: String, require: true },
});

/** table*/
const selected = ref<any[]>([]);
const rows = ref<any[]>([]);
const columns = ref<QTableProps["columns"]>([
  {
    name: "posNo",
    align: "left",
    label: "เลขที่ตำแหน่ง",
    sortable: true,
    field: "posNo",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "fullName",
    align: "left",
    label: "ชื่อ-นามสกุล",
    sortable: true,
    field: "fullName",
    format(val, row) {
      return `${row.prefix}${row.firstName} ${row.lastName}`;
    },
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "posExecutiveName",
    align: "left",
    label: "ตำแหน่งทางการบริหาร",
    sortable: true,
    field: "posExecutiveName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "actFullName",
    align: "left",
    label: "รักษาการแทน",
    field: "actFullName",
    sortable: true,
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);

const total = ref<number>(0);
const totalList = ref<number>(1);
const pagination = ref({
  sortBy: "createdAt",
  descending: true,
  page: 1,
  rowsPerPage: 10,
});
const isAcceptSetting = ref<boolean>(false);
const isApproveSetting = ref<boolean>(false);
const isReasonSetting = ref<boolean>(false);

async function fetchLists() {
  showLoader();
  await http
    .put(config.API.workflow + `commander/${props.type}`, {
      isAct: isAct.value,
      keyword: search.value,
      page: pagination.value.page,
      pageSize: pagination.value.rowsPerPage,
    })
    .then(async (res) => {
      totalList.value = Math.ceil(
        res.data.result.total / pagination.value.rowsPerPage
      );
      total.value = res.data.result.total;
      rows.value = res.data.result.data;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

function onSubmit() {
  dialogConfirm($q, async () => {
    showLoader();
    await http
      .post(config.API.workflow + `add-step`, {
        stateId: props.stateId,
        profileId: selected.value[0].id,
        isAcceptSetting: isAcceptSetting.value,
        isApproveSetting: isApproveSetting.value,
        isReasonSetting: isReasonSetting.value,
      })
      .then(async () => {
        await props.fetchData?.();
        onCloseModal();
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

function onCloseModal() {
  modal.value = false;
  selected.value = [];
  rows.value = [];
  isAcceptSetting.value = false;
  isApproveSetting.value = false;
  isReasonSetting.value = false;

  search.value = ''
  isAct.value = false
}

function onSearchData() {
  getSearch();
}

function updatePagination(newPagination: any) {
  pagination.value.page = 1;
  pagination.value.rowsPerPage = newPagination.rowsPerPage;
}

function getSearch() {
  pagination.value.page = 1;
  fetchLists();
}

watch(
  () => pagination.value.rowsPerPage,
  async () => {
    getSearch();
  }
);

watch(modal, (val) => {
  if (val) {
    fetchLists();
  }
});
</script>

<template>
  <q-dialog v-model="modal" persistent>
    <q-card style="min-width: 700px">
      <q-form q-form greedy @submit.prevent @validation-success="onSubmit">
        <DialogHeader :tittle="`เลือกรายชื่อ`" :close="onCloseModal" />
        <q-separator />

        <q-card-section>
          <div class="row q-col-gutter-sm items-start q-mb-sm">
            <div class="col-12 col-sm-4 col-md-4">
              <q-input
                v-model="search"
                outlined
                clearable
                hide-bottom-space
                dense
                label="คำค้น"
                @clear="search = ''"
              />
            </div>
            <q-checkbox
              keep-color
              v-model="isAct"
              label="แสดงเฉพาะรักษาการแทน"
              color="primary"
            >
              <q-tooltip>แสดงเฉพาะรักษาการแทน </q-tooltip>
            </q-checkbox>
            <q-space />

            <div class="col-12 col-sm-6 col-md-3">
              <q-btn
                color="primary"
                icon="search"
                label="ค้นหา"
                class="full-width q-pa-sm"
                @click.prevent="onSearchData"
              >
              </q-btn>
            </div>
          </div>
          <d-table
            ref="table"
            :columns="columns"
            :rows="rows"
            row-key="key"
            flat
            bordered
            :paging="true"
            dense
            :rows-per-page-options="[10, 25, 50, 100]"
            selection="single"
            v-model:selected="selected"
            @update:pagination="updatePagination"
          >
            <template v-slot:pagination="scope">
              ทั้งหมด {{ total }} รายการ
              <q-pagination
                v-model="pagination.page"
                active-color="primary"
                color="dark"
                :max="Number(totalList)"
                size="sm"
                boundary-links
                direction-links
                :max-pages="5"
                @update:model-value="fetchLists()"
              ></q-pagination>
            </template>

            <template v-slot:header-selection="scope">
              <q-checkbox
                keep-color
                color="primary"
                dense
                v-model="scope.checkBox"
              />
            </template>
            <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" class="cursor-pointer">
                <q-td>
                  <q-checkbox
                    keep-color
                    color="primary"
                    dense
                    v-model="props.selected"
                  />
                </q-td>
                <q-td v-for="col in props.cols" :key="col.name" :props="props">
                  <div v-if="col.name == 'no'">
                    {{
                      (pagination.page - 1) * pagination.rowsPerPage +
                      props.rowIndex +
                      1
                    }}
                  </div v-else>
                  <div>
                    {{ col.value ? col.value : "-" }}
                  </div>
                </q-td>
              </q-tr>
            </template>
          </d-table>
          <div class="q-gutter-xs q-pt-sm">
            <div>
              <q-checkbox
                keep-color
                color="primary"
                dense
                v-model="isAcceptSetting"
                label="ให้เลือกรับทราบ"
                @update:model-value="
                  (isApproveSetting = false), (isReasonSetting = false)
                "
              />
            </div>
            <div v-if="!isAcceptSetting">
              <q-checkbox
                dense
                keep-color
                color="primary"
                v-model="isApproveSetting"
                label="ให้เลือกพิจารณา (อนุมัติ/ไม่อนุมัติ)"
              />
            </div>
            <div v-if="!isAcceptSetting">
              <q-checkbox
                dense
                keep-color
                color="primary"
                v-model="isReasonSetting"
                label="ให้แสดงความเห็นในเอกสาร"
              />
            </div>
          </div>
        </q-card-section>

        <q-separator />

        <q-card-actions align="right">
          <q-btn
            :label="
              props.type === 'operate'
                ? 'ส่งไปยังผู้บังคับบัญชา'
                : 'ส่งไปยังผู้มีอำนาจ'
            "
            color="public"
            type="submit"
            :disable="
              selected.length === 0 ||
              (!isAcceptSetting && !isApproveSetting && !isReasonSetting)
            "
          >
          </q-btn>
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>

<style scoped></style>
