<script setup lang="ts">
import { ref, onMounted, reactive } from "vue";
import type { QTableProps } from "quasar";
import type {
  RequestItemsObject,
  FormFilter,
  DataOption,
  DisciplineOps,
} from "@/modules/04_registryNew/interface/index/discipline";
import { useCounterMixin } from "@/stores/mixin";
import { useQuasar } from "quasar";
import DialogHeader from "@/components/DialogHeader.vue";
import http from "@/plugins/http";
import config from "@/app.config";
import DialogHistory from "@/modules/04_registryNew/components/detail/GovernmentInformation/02_DisciplineHistory.vue";
import { useRoute } from "vue-router";

const route = useRoute();
const profileId = ref<string>(
  route.params.id ? route.params.id.toString() : ""
);
const $q = useQuasar();
const mixin = useCounterMixin();
const {
  date2Thai,
  dialogConfirm,
  showLoader,
  hideLoader,
  messageError,
  success,

  dialogRemove,
} = mixin;
const disciplineData = reactive<RequestItemsObject>({
  date: new Date(),
  level: "",
  detail: "",
  unStigma: "",
  refCommandNo: "",
  profileId: profileId.value,
  refCommandDate: null,
});
const rows = ref<RequestItemsObject[]>([]);
const mode = ref<string>("table");
const filterKeyword = ref<string>("");
const formFilter = reactive<FormFilter>({
  page: 1,
  pageSize: 12,
  keyword: "",
  type: "",
  posType: "",
  posLevel: "",
  retireYear: "",
  rangeYear: { min: 0, max: 60 },
  isShowRetire: false,
  isProbation: false,
});

const currentPage = ref<number>(1);
const maxPage = ref<number>(1);
const pagination = ref({
  page: 1,
  rowsPerPage: 10,
});

const visibleColumns = ref<String[]>([
  "level",
  "detail",
  "unStigma",
  "refCommandNo",
  "refCommandDate",
  "date",
]);
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 dateRef = ref<object | null>(null);
const detailRef = ref<object | null>(null);
const refCommandNoRef = ref<object | null>(null);

/** dialog */
const edit = ref<boolean>(false);
const modal = ref<boolean>(false);
const modalHistory = ref<boolean>(false);

const id = ref<string>("");

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

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;
}

function openDialogAdd() {
  modal.value = true;
}

async function fetchData(id: string) {
  showLoader();
  await http
    .get(config.API.profileNewDisciplineByProfileId(id))
    .then(async (res) => {
      rows.value = res.data.result;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

async function addData() {
  await http
    .post(config.API.profileNewDiscipline, disciplineData)
    .then(() => {
      fetchData(profileId.value);
      success($q, "บันทึกข้อมูลสำเร็จ");
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

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

// function deleteData(idData: string) {
//   dialogRemove($q, () =>
//     http
//       .delete(config.API.profileNewDisciplineByDisciplineId(idData))
//       .then(() => {
//         fetchData(profileId.value);
//         success($q, "ลบข้อมูลสำเร็จ");
//       })
//       .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 openDialogHistory(idOrder: string) {
  modalHistory.value = true;
  id.value = idOrder;
}

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

onMounted(async () => {
  await fetchData(profileId.value);
});
</script>
<template>
  <div class="row items-center q-gutter-x-sm q-pb-sm">
    <q-btn 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
          v-if="filterKeyword == ''"
          name="search"
          @click.stop.prevent="filterKeyword = ''"
          class="cursor-pointer"
        />
        <q-icon
          v-if="filterKeyword"
          name="cancel"
          @click.stop.prevent="filterKeyword = ''"
          class="cursor-pointer"
        />
      </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"
      options-cover
      style="min-width: 150px"
    />
    <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"
    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 v-for="col in props.cols" :key="col.name" :props="props">
          <span class="text-weight-medium">{{ col.label }}</span>
        </q-th>
        <q-th auto-width></q-th>
      </q-tr>
    </template>
    <template v-slot:body="props" v-if="mode === 'table'">
      <q-tr :props="props" class="cursor-pointer">
        <q-td v-for="col in props.cols" :key="col.id">
          <div v-if="col.name === 'no'">
            {{
              (formFilter.page - 1) * formFilter.pageSize + props.rowIndex + 1
            }}
          </div>
          <div v-else>
            {{ col.value ? col.value : "-" }}
          </div>
        </q-td>
        <q-td auto-width>
          <q-btn
            color="primary"
            flat
            dense
            round
            class="q-mr-xs"
            size="14px"
            icon="mdi-pencil-outline"
            clickable
            @click="openDialogEdit(props.row)"
          >
            <q-tooltip>แก้ไขข้อมูล</q-tooltip>
          </q-btn>
          <q-btn
            color="info"
            flat
            dense
            round
            size="14px"
            icon="mdi-history"
            @click="openDialogHistory(props.row.id)"
          >
            <q-tooltip>ประวัติแก้ไขวินัย</q-tooltip>
          </q-btn>
          <!-- <q-btn
            color="red"
            flat
            dense
            round
            size="14px"
            icon="mdi-delete"
            clickable
            @click.stop="deleteData(props.row.id)"
            v-close-popup
          >
            <q-tooltip>ลบข้อมูล</q-tooltip>
          </q-btn> -->
        </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 class="q-gutter-x-sm">
              <q-btn
                color="primary"
                icon="mdi-pencil-outline"
                flat
                round
                @click="openDialogEdit(props.row)"
                ><q-tooltip>แก้ไข</q-tooltip></q-btn
              >
              <q-btn
                color="info"
                icon="mdi-history"
                flat
                round
                @click="openDialogHistory(props.row.id)"
                ><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-6 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-6 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-6 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
                clearable
                hide-bottom-space
                input-debounce="0"
                @filter="(inputValue:string,
                    doneFn:Function) => filterSelector(inputValue, doneFn,'levelOptions'
                    ) "
              />
            </div>
            <div class="col-xs-6 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-6 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-6 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
            dense
            unelevated
            label="บันทึก"
            id="onSubmit"
            type="submit"
            color="public"
            class="q-px-md"
          >
            <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>
