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

import { useRoute } from "vue-router";
import { checkPermission } from "@/utils/permissions";
import { useCounterMixin } from "@/stores/mixin";
import http from "@/plugins/http";
import config from "@/app.config";

import type { QTableColumn } from "quasar";
import type { DataActing } from "@/modules/04_registryPerson/interface/request/Government";
import type { ResActingPosData } from "@/modules/04_registryPerson/interface/response/Government";

import DialogHeader from "@/components/DialogHeader.vue";
import DialogHistory from "@/modules/04_registryPerson/components/detail/DialogHistory.vue";
import DialogPreviewCommand from "@/modules/18_command/components/DialogPreviewCommand.vue";

const route = useRoute();
const $q = useQuasar();
const mixin = useCounterMixin();
const {
  date2Thai,
  dialogConfirm,
  showLoader,
  hideLoader,
  messageError,
  success,
  pathRegistryEmp,
  onSearchDataTable,
  convertDateToAPI,
  dialogRemove,
} = mixin;

const profileId = ref<string>(
  route.params.id ? route.params.id.toString() : ""
);
const empType = ref<string>(pathRegistryEmp(route.name?.toString() ?? ""));

/** props*/
const isLeave = defineModel<boolean>("isLeave", {
  required: true,
});
const citizenId = defineModel<string>("citizenId", {
  required: true,
});

const baseColumns = ref<QTableColumn[]>([
  {
    name: "dateStart",
    align: "left",
    label: "วันที่เริ่มต้น",
    sortable: true,
    field: "dateStart",
    format: (v) => date2Thai(v),
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "dateEnd",
    align: "left",
    label: "วันที่สิ้นสุด",
    sortable: true,
    field: "dateEnd",
    format: (v) => date2Thai(v),
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "posNo",
    align: "left",
    label: empType.value === "" ? "เลขที่ตำแหน่ง" : "ตำแหน่งเลขที่",
    sortable: true,
    field: "posNo",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "position",
    align: "left",
    label: "ตำแหน่ง",
    sortable: true,
    field: "position",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "refCommandNo",
    align: "left",
    label: "เลขที่คำสั่ง",
    sortable: true,
    field: "refCommandNo",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "status",
    align: "left",
    label: "สถานะ",
    sortable: true,
    field: "status",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format(val, row) {
      return row.status ? "ใช้งาน" : "-";
    },
    sort: (a: string, b: string) =>
      a
        .toString()
        .localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "lastUpdateFullName",
    align: "left",
    label: "ผู้ดำเนินการ",
    sortable: true,
    field: "lastUpdateFullName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "lastUpdatedAt",
    align: "left",
    label: "วันที่แก้ไข",
    sortable: true,
    field: "lastUpdatedAt",
    format: (v) => date2Thai(v, false, true),
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);
const baseVisibleColumns = ref<string[]>([
  "dateStart",
  "dateEnd",
  "posNo",
  "position",
  "refCommandNo",
  "status",
  "lastUpdateFullName",
  "lastUpdatedAt",
]);

/** Table*/
const rows = ref<ResActingPosData[]>([]); //รายการวินัย
const rowsMain = ref<ResActingPosData[]>([]); //รายการวินัย
const mode = ref<string>("table"); //การแสดงผล Table card
const filterKeyword = ref<string>(""); //คำค้นหา
const columns = ref<QTableColumn[]>(
  baseColumns.value.filter((e: QTableColumn) => e.name !== "lastUpdateFullName")
);
const visibleColumns = ref<String[]>(
  baseVisibleColumns.value.filter((e: string) => e !== "lastUpdateFullName")
);
const pagination = ref({
  sortBy: "lastUpdatedAt",
});

const columnsHistory = ref<QTableColumn[]>(baseColumns.value);
const visibleColumnsHistory = ref<string[]>(baseVisibleColumns.value);

/** Dialog*/
const isStatusEdit = ref<boolean>(false);
const modal = ref<boolean>(false);
const modalHistory = ref<boolean>(false);
const rowId = ref<string>("");

const modalCommand = ref<boolean>(false);
const command = ref<string>("");
const commandId = ref<string>("");

const formData = reactive<DataActing>({
  dateStart: null,
  dateEnd: null,
  posNo: "",
  position: "",
  status: false,
});

async function fetchData() {
  showLoader();
  await http
    .get(config.API.profileActposition(empType.value, profileId.value))
    .then((res) => {
      const data = res.data.result;
      rows.value = data;
      rowsMain.value = data;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/** function fetch ข้อมูลประวติการแก้ไขข้อมูล*/
async function fetchDataHistory() {
  showLoader();
  try {
    const res = await http.get(
      config.API.profileActpositionHistory(rowId.value, empType.value)
    );
    return res.data.result;
  } catch (err) {
    messageError($q, err);
  } finally {
    hideLoader();
  }
}

function onSubmit() {
  dialogConfirm($q, async () => {
    showLoader();
    const body = {
      ...formData,
      dateStart: convertDateToAPI(formData.dateStart),
      dateEnd: convertDateToAPI(formData.dateEnd),
      profileId: isStatusEdit.value ? undefined : profileId.value,
    };
    const method = isStatusEdit.value ? "patch" : "post";
    await http[method](
      config.API.profileActposition(
        empType.value,
        isStatusEdit.value ? rowId.value : ""
      ),
      body
    )
      .then(async () => {
        await fetchData();
        success($q, "บันทึกข้อมูลสำเร็จ");
        closeDialogForm();
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

function openEditDialog(data: ResActingPosData) {
  modal.value = true;
  isStatusEdit.value = true;
  rowId.value = data.id;
  formData.dateStart = data.dateStart;
  formData.dateEnd = data.dateEnd;
  formData.posNo = data.posNo;
  formData.position = data.position;
  formData.status = data.status;
}

function showHistoryDialog(id: string) {
  modalHistory.value = true;
  rowId.value = id;
}

function openViewCommand(data: ResActingPosData) {
  command.value = data.refCommandNo;
  commandId.value = data.commandId;
  modalCommand.value = true;
}

function closeDialogForm() {
  modal.value = false;
  isStatusEdit.value = false;
  rowId.value = "";
  formData.dateStart = null;
  formData.dateEnd = null;
  formData.posNo = "";
  formData.position = "";
  formData.status = false;
}

/** ฟังก์ค้นหาข้อมูลรายการ */
function serchDataTable() {
  rows.value = onSearchDataTable(
    filterKeyword.value,
    rowsMain.value,
    columns.value ? columns.value : []
  );
}

function onDelete(rowId: string) {
  dialogRemove($q, async () => {
    showLoader();
    try {
      await http.patch(
        config.API.profileActpositionUpdateDelete(empType.value) + `${rowId}`
      );
      await fetchData();
      await success($q, "ลบข้อมูลสำเร็จ");
    } catch (err) {
      messageError($q, err);
    } finally {
      hideLoader();
    }
  });
}

onMounted(() => {
  fetchData();
});
</script>

<template>
  <div class="row items-center q-gutter-x-sm q-pb-sm">
    <q-btn
      v-if="!isLeave && checkPermission($route)?.attrIsUpdate"
      dense
      color="primary"
      icon="add"
      flat
      round
      @click.stop.prevent="modal = true"
    >
      <q-tooltip>เพิ่มข้อมูล</q-tooltip>
    </q-btn>

    <q-space />
    <q-input
      standout
      dense
      v-model="filterKeyword"
      ref="filterRef"
      outlined
      placeholder="ค้นหา"
      @keydown.enter.prevent="serchDataTable"
    >
      <template v-slot:append>
        <q-icon name="search" />
      </template>
    </q-input>
    <q-select
      v-model="visibleColumns"
      multiple
      outlined
      dense
      options-dense
      :display-value="$q.lang.table.columns"
      emit-value
      map-options
      :options="columns"
      option-value="name"
      style="min-width: 140px"
    />
    <q-btn-toggle
      v-model="mode"
      dense
      class="no-shadow toggle-borderd"
      toggle-color="grey-4"
      :options="[
        { value: 'table', slot: 'table' },
        { value: 'card', slot: 'card' },
      ]"
    >
      <template v-slot:table>
        <q-icon
          name="format_list_bulleted"
          size="24px"
          :style="{
            color: mode === 'table' ? '#787B7C' : '#C9D3DB',
          }"
        />
      </template>

      <template v-slot:card>
        <q-icon
          name="mdi-view-grid-outline"
          size="24px"
          :style="{
            color: mode === 'card' ? '#787B7C' : '#C9D3DB',
          }"
        />
      </template>
    </q-btn-toggle>
  </div>

  <d-table
    :grid="mode === 'card'"
    ref="table"
    row-key="id"
    flat
    bordered
    dense
    :columns="columns"
    :rows="rows"
    :visible-columns="visibleColumns"
    v-model:pagination="pagination"
  >
    >
    <template v-slot:header="props">
      <q-tr :props="props">
        <q-th auto-width></q-th>
        <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" v-if="mode === 'table'">
      <q-tr :props="props">
        <q-td auto-width>
          <q-btn
            flat
            dense
            round
            color="deep-purple"
            icon="mdi-history"
            @click.stop.prevent="showHistoryDialog(props.row.id)"
          >
            <q-tooltip>ประวัติแก้ไขรักษาการในตำแหน่ง</q-tooltip>
          </q-btn>
          <q-btn
            v-if="!isLeave && checkPermission($route)?.attrIsUpdate"
            flat
            dense
            round
            :color="props.row.commandId ? 'grey-5' : 'edit'"
            :disable="props.row.commandId !== null"
            icon="edit"
            @click.stop.prevent="openEditDialog(props.row)"
          >
            <q-tooltip>แก้ไขข้อมูล</q-tooltip>
          </q-btn>

          <q-btn
            v-if="!isLeave && checkPermission($route)?.attrIsDelete"
            flat
            dense
            round
            color="red"
            icon="delete"
            @click.stop.prevent="onDelete(props.row.id)"
          >
            <q-tooltip>ลบข้อมูล</q-tooltip>
          </q-btn>
        </q-td>
        <q-td v-for="col in props.cols" :key="col.id">
          <div
            v-if="col.name == 'refCommandNo' && props.row.commandId"
            @click="col.value ? openViewCommand(props.row) : null"
            :class="
              col.value
                ? 'table_ellipsis text-blue cursor-pointer'
                : 'table_ellipsis'
            "
          >
            {{ col.value ? col.value : "-" }}
            <q-tooltip v-if="col.value">ดูคำสั่ง</q-tooltip>
          </div>
          <div v-else>
            {{ col.value ? col.value : "-" }}
          </div>
        </q-td>
      </q-tr>
    </template>
    <template v-slot:item="props" v-else>
      <div class="q-pa-xs col-xs-12 col-sm-4 col-md-3">
        <q-card flat bordered>
          <q-card-actions align="right" class="bg-grey-3">
            <q-btn
              color="deep-purple"
              icon="mdi-history"
              flat
              round
              @click.stop.prevent="showHistoryDialog(props.row.id)"
            >
              <q-tooltip>ประวัติแก้ไขรักษาการในตำแหน่ง</q-tooltip>
            </q-btn>

            <q-btn
              v-if="isLeave === false && checkPermission($route)?.attrIsUpdate"
              :color="props.row.commandId ? 'grey-5' : 'edit'"
              :disable="props.row.commandId !== null"
              icon="edit"
              flat
              round
              @click.stop.prevent="openEditDialog(props.row)"
            >
              <q-tooltip>แก้ไขข้อมูล</q-tooltip>
            </q-btn>

            <q-btn
              v-if="isLeave === false && checkPermission($route)?.attrIsDelete"
              color="red"
              icon="delete"
              flat
              round
              @click.stop.prevent="onDelete(props.row.id)"
            >
              <q-tooltip>ลบข้อมูล</q-tooltip>
            </q-btn>
          </q-card-actions>
          <q-separator />

          <q-list>
            <div
              :class="`row q-pa-sm`"
              :style="`background-color: ${index % 2 !== 0 ? '#FAFAFA' : ''}`"
              v-for="(col, index) in props.cols"
              :key="col.name"
            >
              <div class="col text-grey-6">
                <div>{{ col.label }}</div>
              </div>
              <div class="col">
                <div
                  v-if="col.name == 'refCommandNo' && props.row.commandId"
                  @click="col.value ? openViewCommand(props.row) : null"
                  :class="
                    col.value
                      ? 'table_ellipsis text-blue cursor-pointer'
                      : 'table_ellipsis'
                  "
                >
                  {{ col.value ? col.value : "-" }}
                  <q-tooltip v-if="col.value">ดูคำสั่ง</q-tooltip>
                </div>
                <div v-else>{{ col.value ? col.value : "-" }}</div>
              </div>
            </div>
          </q-list>
        </q-card>
      </div>
    </template>
  </d-table>

  <q-dialog v-model="modal" persistent>
    <q-card style="width: 700px; max-width: 80vw">
      <q-form @submit.prevent greedy @validation-success="onSubmit()">
        <DialogHeader
          :tittle="
            isStatusEdit
              ? 'แก้ไขข้อมูลรายการรักษาการในตำแหน่ง'
              : 'เพิ่มข้อมูลรายการรักษาการในตำแหน่ง'
          "
          :close="closeDialogForm"
        />
        <q-separator />
        <q-card-section style="max-height: 50vh" class="scroll">
          <div class="row col-12 q-col-gutter-x-xs q-col-gutter-y-xs">
            <div class="col-xs-12 col-sm-6 col-md-6">
              <datepicker
                menu-class-name="modalfix"
                v-model="formData.dateStart"
                :locale="'th'"
                autoApply
                :enableTimePicker="false"
                week-start="0"
                :max-date="formData.dateEnd"
              >
                <template #year="{ year }">{{ year + 543 }}</template>
                <template #year-overlay-value="{ value }">{{
                  parseInt(value + 543)
                }}</template>
                <template #trigger>
                  <q-input
                    ref="dateRef"
                    class="full-width inputgreen cursor-pointer"
                    outlined
                    dense
                    :model-value="date2Thai(formData.dateStart)"
                    :rules="[(val:string) => !!val || `${'กรุณาเลือก วันที่เริ่มต้น'}`]"
                    hide-bottom-space
                    :label="`${'วันที่เริ่มต้น'}`"
                  >
                    <template v-slot:prepend>
                      <q-icon
                        name="event"
                        class="cursor-pointer"
                        color="primary"
                      >
                      </q-icon>
                    </template>
                  </q-input>
                </template>
              </datepicker>
            </div>

            <div class="col-xs-12 col-sm-6 col-md-6">
              <datepicker
                menu-class-name="modalfix"
                v-model="formData.dateEnd"
                :locale="'th'"
                autoApply
                :enableTimePicker="false"
                week-start="0"
                :min-date="formData.dateStart"
              >
                <template #year="{ year }">{{ year + 543 }}</template>
                <template #year-overlay-value="{ value }">{{
                  parseInt(value + 543)
                }}</template>
                <template #trigger>
                  <q-input
                    ref="dateRef"
                    class="full-width inputgreen cursor-pointer"
                    outlined
                    dense
                    :model-value="date2Thai(formData.dateEnd)"
                    :rules="[(val:string) => !!val || `${'กรุณาเลือก วันที่สิ้นสุด'}`]"
                    hide-bottom-space
                    :label="`${'วันที่สิ้นสุด'}`"
                  >
                    <template v-slot:prepend>
                      <q-icon
                        name="event"
                        class="cursor-pointer"
                        color="primary"
                      >
                      </q-icon>
                    </template>
                  </q-input>
                </template>
              </datepicker>
            </div>

            <div class="col-xs-12 col-sm-6 col-md-6">
              <q-input
                class="full-width inputgreen cursor-pointer"
                outlined
                dense
                lazy-rules
                v-model="formData.posNo"
                :rules="[(val:string) => !!val || `${'กรุณากรอกตำแหน่งเลขที่'}`]"
                hide-bottom-space
                :label="`${'ตำแหน่งเลขที่'}`"
              />
            </div>
            <div class="col-xs-12 col-sm-6 col-md-6">
              <q-input
                class="full-width inputgreen cursor-pointer"
                outlined
                dense
                lazy-rules
                v-model="formData.position"
                :rules="[(val:string) => !!val || `${'กรุณากรอกตำแหน่ง'}`]"
                hide-bottom-space
                :label="`${'ตำแหน่ง'}`"
              />
            </div>
            <div class="col-xs-12 col-sm-6 col-md-6">
              <q-checkbox
                disable
                v-model="formData.status"
                label="ใช้งาน"
                keep-color
              />
            </div>
          </div>
        </q-card-section>
        <q-separator />
        <q-card-actions align="right">
          <q-btn label="บันทึก" id="onSubmit" type="submit" color="public">
            <q-tooltip>บันทึกข้อมูล</q-tooltip>
          </q-btn>
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>

  <!-- <DialogHistory v-model:modal="modalHistory" v-model:id="rowId" /> -->
  <DialogHistory
    v-model:modal="modalHistory"
    :title="`ประวัติแก้ไขรักษาการในตำแหน่ง`"
    :columns="columnsHistory"
    :visible-columns="visibleColumnsHistory"
    :fetch-data="fetchDataHistory"
  />

  <DialogPreviewCommand
    v-model:modal="modalCommand"
    v-model:command="command"
    v-model:command-id="commandId"
    :citizen-id="citizenId"
  />
</template>

<style scoped></style>
