<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 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: "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 isAcceptSetting = ref<boolean>(false);
const isApproveSetting = ref<boolean>(false);
const isReasonSetting = ref<boolean>(false);

async function fetchLists() {
  showLoader();
  await http
    .get(config.API.workflow + `commander/${props.type}`)
    .then(async (res) => {
      rows.value = res.data.result;
    })
    .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;
}

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>
          <d-table
            ref="table"
            :columns="columns"
            :rows="rows"
            row-key="id"
            flat
            bordered
            :paging="true"
            dense
            :rows-per-page-options="[10, 25, 50, 100]"
            selection="single"
            v-model:selected="selected"
          >
            <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>
                    {{ 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>
