<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 { QTableProps } from "quasar";
import type {
  RequestItemsObject,
  DisciplineOps,
  DataOption,
} from "@/modules/04_registryPerson/interface/index/discipline";

import DialogHeader from "@/components/DialogHeader.vue";
import DialogHistory from "@/modules/04_registryPerson/components/detail/GovernmentInformation/02_DisciplineHistory.vue";

const route = useRoute();
const $q = useQuasar();
const mixin = useCounterMixin();
const {
  date2Thai,
  dialogConfirm,
  showLoader,
  hideLoader,
  messageError,
  success,
  pathRegistryEmp,
} = 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 disciplineData = reactive<RequestItemsObject>({
  date: null, //วัน/เดือน/ปี
  level: "", //ระดับการลงโทษทางวินัย
  detail: "", //รายละเอียด
  unStigma: "", //ประเภทคำสั่ง
  refCommandNo: "", //เลขที่คำสั่ง
  profileId: profileId.value,
  refCommandDate: null, //เอกสารอ้างอิง (ลงวันที่)
});

const rows = ref<RequestItemsObject[]>([]); //รายการวินัย
const mode = ref<string>("table"); //การแสดงผล Table card
const filterKeyword = ref<string>(""); //คำค้นหา
const columns = ref<QTableProps["columns"]>([
  {
    name: "date",
    align: "left",
    label: "วัน เดือน ปี",
    sortable: true,
    field: "date",
    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: "detail",
    align: "left",
    label: "รายละเอียด",
    sortable: true,
    field: "detail",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "level",
    align: "left",
    label: "ระดับการลงโทษทางวินัย",
    sortable: true,
    field: "level",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "unStigma",
    align: "left",
    label: "ประเภทคำสั่ง",
    sortable: true,
    field: "unStigma",
    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: "refCommandDate",
    align: "left",
    label: "เอกสารอ้างอิง (ลงวันที่)",
    sortable: true,
    field: "refCommandDate",
    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" }),
  },
]);
const visibleColumns = ref<String[]>([
  "level",
  "detail",
  "unStigma",
  "refCommandNo",
  "refCommandDate",
  "date",
]);
const pagination = ref({
  page: 1,
  rowsPerPage: 10,
});

const edit = ref<boolean>(false); //สถานะการแก้ไข
const modal = ref<boolean>(false); //แสดงข้อมูลวินัย
const modalHistory = ref<boolean>(false); //แสดงประวัติแก้ไขวินัย
const id = ref<string>(""); //id ที่ต้แงการแก้ไข

const Ops = ref<DisciplineOps>({
  levelOptions: [
    { id: "0", name: "ไม่ร้ายแรง", disable: true },
    { id: "ภาคทัณฑ์", name: "ภาคทัณฑ์", disable: false },
    {
      id: "ตัดเงินเดือน",
      name: "ตัดเงินเดือน",
      disable: false,
    },
    {
      id: "ลดขั้นเงินเดือน",
      name: "ลดขั้นเงินเดือน",
      disable: false,
    },
    { id: "4", name: "ร้ายแรง", disable: true },
    { id: "ปลดออก", name: "ปลดออก", disable: false },
    { id: "ไล่ออก", name: "ไล่ออก", disable: false },
    { id: "อื่นๆ", name: "อื่นๆ", disable: false },
  ],
});
const OpsFilter = ref<DisciplineOps>({
  levelOptions: [
    { id: "0", name: "ไม่ร้ายแรง", disable: true },
    { id: "ภาคทัณฑ์", name: "ภาคทัณฑ์", disable: false },
    {
      id: "ตัดเงินเดือน",
      name: "ตัดเงินเดือน",
      disable: false,
    },
    {
      id: "ลดขั้นเงินเดือน",
      name: "ลดขั้นเงินเดือน",
      disable: false,
    },
    { id: "4", name: "ร้ายแรง", disable: true },
    { id: "ปลดออก", name: "ปลดออก", disable: false },
    { id: "ไล่ออก", name: "ไล่ออก", disable: false },
    { id: "อื่นๆ", name: "อื่นๆ", disable: false },
  ],
});

/**
 * function ค้นหา คำใน option
 * @param val คำค้นหา
 * @param update function
 * @param refData type select
 */
function filterSelector(val: string, update: Function, refData: string) {
  switch (refData) {
    case "levelOptions":
      update(() => {
        Ops.value.levelOptions = OpsFilter.value.levelOptions.filter(
          (v: DataOption) => v.name.indexOf(val) > -1
        );
      });
      break;
    default:
      break;
  }
}

/**
 * ปิด dialog ข้อมูลวินัย
 */
function closeDialog() {
  modal.value = false;
  edit.value = false;
  disciplineData.date = null;
  disciplineData.detail = "";
  disciplineData.level = "";
  disciplineData.unStigma = "";
  disciplineData.refCommandNo = "";
  disciplineData.refCommandDate = null;
}

/**
 * เปิด dialog ข้อมูลวินัย
 */
function openDialogAdd() {
  modal.value = true;
}

/**
 * function fetch ข้อมูลรายการวินัย
 */
async function fetchData(id: string) {
  showLoader();
  http
    .get(config.API.profileNewDisciplineByProfileId(id, empType.value))
    .then((res) => {
      rows.value = res.data.result;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * funciton เพิ่มช้อมูลวินัย
 */
function addData() {
  showLoader();
  const body = {
    date: disciplineData.date,
    level: disciplineData.level,
    detail: disciplineData.detail,
    unStigma: disciplineData.unStigma,
    refCommandNo: disciplineData.refCommandNo,
    profileId: empType.value === "" ? disciplineData.profileId : undefined,
    profileEmployeeId:
      empType.value !== "" ? disciplineData.profileId : undefined,
    refCommandDate: disciplineData.refCommandDate,
  };
  http
    .post(config.API.profileNewDiscipline(empType.value), body)
    .then(async () => {
      await fetchData(profileId.value);
      await success($q, "บันทึกข้อมูลสำเร็จ");
      closeDialog();
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * funciton บันทึกแก่ไขช้อมูลวินัย
 */
function editData(idData: string) {
  showLoader();
  http
    .patch(
      config.API.profileNewDisciplineByDisciplineId(idData, empType.value),
      {
        ...disciplineData,
        profileId: undefined,
      }
    )
    .then(async () => {
      await fetchData(profileId.value);
      await success($q, "บันทึกข้อมูลสำเร็จ");
      closeDialog();
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * กดเลือกข้อมูลที่จะแก้ไข
 * @param props ค่า props ใน row ที่เลือก
 */
function openDialogEdit(props: RequestItemsObject) {
  modal.value = true;
  edit.value = true;
  id.value = props.id ? props.id : "";
  disciplineData.date = props.date;
  disciplineData.detail = props.detail;
  disciplineData.level = props.level;
  disciplineData.unStigma = props.unStigma;
  disciplineData.refCommandNo = props.refCommandNo;
  disciplineData.refCommandDate = props.refCommandDate;
}

/**
 * function ดูประวัติการแ้ไขรายการวินัย
 * @param idOrder
 */
function openDialogHistory(idOrder: string) {
  modalHistory.value = true;
  id.value = idOrder;
}

/**
 * function ยืนยันการบันทึกข้อมูล
 */
function onSubmit() {
  dialogConfirm(
    $q,
    () => {
      edit.value ? editData(id.value) : addData();
    },
    "ยืนยันการบันทึกข้อมูล",
    "ต้องการยืนยันการบันทึกข้อมูลนี้หรือไม่ ?"
  );
}

/**
 * ทำงานเมื่อ Components ถูกเรียกใช้งาน
 */
onMounted(() => {
  fetchData(profileId.value);
});
</script>
<template>
  <div class="row items-center q-gutter-x-sm q-pb-sm">
    <q-btn
      v-if="isLeave == false && checkPermission($route)?.attrIsUpdate"
      dense
      color="primary"
      icon="add"
      flat
      round
      @click="openDialogAdd()"
      ><q-tooltip>เพิ่มข้อมูล</q-tooltip></q-btn
    >

    <q-space />
    <q-input
      standout
      dense
      v-model="filterKeyword"
      ref="filterRef"
      outlined
      placeholder="ค้นหา"
      debounce="300"
    >
      <template v-slot:append>
        <q-icon name="search" />
      </template>
    </q-input>
    <q-select
      v-if="mode == 'table'"
      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
    :card-container-class="mode === 'card' ? 'q-col-gutter-md' : ''"
    :grid="mode === 'card'"
    ref="table"
    row-key="id"
    flat
    bordered
    dense
    :columns="columns"
    :rows="rows"
    :paging="true"
    :filter="filterKeyword.trim()"
    v-model:pagination="pagination"
    :rows-per-page-options="[10, 25, 50, 100]"
    :visible-columns="visibleColumns"
  >
    >
    <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="openDialogHistory(props.row.id)"
          >
            <q-tooltip>ประวัติแก้ไขวินัย</q-tooltip>
          </q-btn>
          <q-btn
            v-if="isLeave == false && checkPermission($route)?.attrIsUpdate"
            flat
            dense
            round
            color="edit"
            icon="edit"
            clickable
            @click="openDialogEdit(props.row)"
          >
            <q-tooltip>แก้ไขข้อมูล</q-tooltip>
          </q-btn>
        </q-td>
        <q-td v-for="col in props.cols" :key="col.id">
          <div>
            {{ col.value ? col.value : "-" }}
          </div>
        </q-td>
      </q-tr>
    </template>
    <template v-slot:item="props" v-else>
      <div class="col-xs-12 col-sm-6 col-md-6">
        <q-card flat bordered class="q-pa-none">
          <div class="row bg-grey-3">
            <q-space />
            <div>
              <q-btn
                color="deep-purple"
                icon="mdi-history"
                flat
                round
                @click="openDialogHistory(props.row.id)"
                ><q-tooltip>ประวิติแก้ไขวินัย</q-tooltip></q-btn
              >
              <q-btn
                v-if="isLeave == false && checkPermission($route)?.attrIsUpdate"
                color="edit"
                icon="edit"
                flat
                round
                @click="openDialogEdit(props.row)"
                ><q-tooltip>แก้ไข</q-tooltip></q-btn
              >
            </div>
          </div>
          <q-separator />
          <q-card-section class="q-pa-none">
            <div class="row q-pa-sm">
              <div class="col-3 text-grey-6 text-weight-medium">
                ระดับการลงโทษทางวินัย
              </div>
              <div class="col-3">
                {{ props.row.level !== "" ? props.row.level : "-" }}
              </div>
              <div class="col-3 text-grey-6 text-weight-medium">
                วัน/เดือน/ปี
              </div>
              <div class="col-3">
                {{ props.row.date ? date2Thai(props.row.date) : "-" }}
              </div>
            </div>
            <q-separator />
            <div class="row q-pa-sm bg-grey-2">
              <div class="col-3 text-grey-6 text-weight-medium">ล้างมลทิน</div>
              <div class="col-3">
                {{ props.row.unStigma !== "" ? props.row.unStigma : "-" }}
              </div>
              <div class="col-3 text-grey-6 text-weight-medium">
                เลขที่คำสั่ง
              </div>
              <div class="col-3">
                {{
                  props.row.refCommandNo !== "" ? props.row.refCommandNo : "-"
                }}
              </div>
            </div>
            <q-separator />
            <div class="row q-pa-sm">
              <div class="col-3 text-grey-6 text-weight-medium">
                เอกสารอ้างอิง (ลงวันที่)
              </div>
              <div class="col-3">
                {{
                  props.row.refCommandDate
                    ? date2Thai(props.row.refCommandDate)
                    : "-"
                }}
              </div>
            </div>
            <q-separator />
            <div class="row q-pa-sm bg-grey-2">
              <div class="col-3 text-grey-6 text-weight-medium">รายละเอียด</div>
              <div class="col-9">
                {{ props.row.detail !== "" ? props.row.detail : "-" }}
              </div>
            </div>
          </q-card-section>
        </q-card>
      </div>
    </template>
  </d-table>

  <!-- dialog add edit -->
  <q-dialog v-model="modal" persistent>
    <q-card>
      <q-form @submit.prevent greedy @validation-success="onSubmit()">
        <DialogHeader
          :tittle="edit ? 'แก้ไขข้อมูลวินัย' : 'เพิ่มข้อมูลวินัย'"
          :close="closeDialog"
        />
        <q-separator color="grey-4" />
        <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="disciplineData.date"
                :locale="'th'"
                autoApply
                :enableTimePicker="false"
                week-start="0"
              >
                <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(disciplineData.date)"
                    :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
                ref="detailRef"
                class="full-width inputgreen cursor-pointer"
                outlined
                dense
                lazy-rules
                v-model="disciplineData.detail"
                :rules="[(val:string) => !!val || `${'กรุณากรอกรายละเอียด'}`]"
                hide-bottom-space
                :label="`${'รายละเอียด'}`"
              />
            </div>
            <div class="col-xs-12 col-sm-6 col-md-6">
              <selector
                class="full-width inputgreen cursor-pointer"
                outlined
                dense
                lazy-rules
                v-model="disciplineData.level"
                :label="`${'ระดับการลงโทษทางวินัย'}`"
                emit-value
                map-options
                option-label="name"
                :options="Ops.levelOptions"
                option-value="id"
                use-input
                hide-selected
                fill-input
                clearable
                hide-bottom-space
                input-debounce="0"
                @filter="(inputValue:string,
                    doneFn:Function) => filterSelector(inputValue, doneFn,'levelOptions'
                    ) "
              />
            </div>
            <div class="col-xs-12 col-sm-6 col-md-6">
              <q-input
                class="full-width inputgreen cursor-pointer"
                outlined
                dense
                v-model="disciplineData.unStigma"
                hide-bottom-space
                :label="`${'ประเภทคำสั่ง'}`"
              />
            </div>
            <div class="col-xs-12 col-sm-6 col-md-6">
              <q-input
                ref="refCommandNoRef"
                class="full-width inputgreen cursor-pointer"
                outlined
                dense
                lazy-rules
                v-model="disciplineData.refCommandNo"
                hide-bottom-space
                :label="`${'เลขที่คำสั่ง'}`"
                :rules="[(val:string) => !!val || `${'กรุณากรอกเลขที่คำสั่ง'}`]"
              >
                <template v-slot:append>
                  <q-icon name="mdi-file" class="cursor-pointer" />
                </template>
              </q-input>
            </div>
            <div class="col-xs-12 col-sm-6 col-md-6">
              <datepicker
                menu-class-name="modalfix"
                v-model="disciplineData.refCommandDate"
                :locale="'th'"
                autoApply
                :enableTimePicker="false"
                week-start="0"
              >
                <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
                    clearable
                    dense
                    :model-value="date2Thai(disciplineData.refCommandDate)"
                    hide-bottom-space
                    :label="`${'เอกสารอ้างอิง (ลงวันที่)'}`"
                    @clear="disciplineData.refCommandDate = null"
                  >
                    <template v-slot:prepend>
                      <q-icon
                        name="event"
                        class="cursor-pointer"
                        color="primary"
                      >
                      </q-icon>
                    </template>
                  </q-input>
                </template>
              </datepicker>
            </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="id" />
</template>

<style scoped></style>
