<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import http from "@/plugins/http";
import config from "@/app.config";
import { useCounterMixin } from "@/stores/mixin";
import { useQuasar } from "quasar";
import { useRoute } from "vue-router";

import type { QTableProps } from "quasar";
import type {
  FormEmployment,
  FormEmploymentRef,
  EmploymentList,
  Respones,
} from "@/modules/08_registryEmployee/interface/response/Main";

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

const rows = ref<EmploymentList[]>([]);
const columns = ref<QTableProps["columns"]>([
  {
    name: "dateEmployment",
    align: "left",
    label: "วันที่จ้าง",
    sortable: false,
    field: "dateEmployment",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "orderEmployment",
    align: "left",
    label: "คำสั่งจ้าง",
    sortable: false,
    field: "orderEmployment",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);
const visibleColumns = ref<string[]>(["dateEmployment", "orderEmployment"]);
const filter = ref<string>();
onMounted(async () => {
  await fetchList();
});

async function fetchList() {
  showLoader();
  await http
    .get(config.API.employmentId(profileId.value))
    .then((res) => {
      const data = res.data.result;
      const list: EmploymentList[] = data.map((e: Respones) => ({
        id: e.id,
        orderEmployment: e.command,
        dateEmployment: date2Thai(e.date),
        dataISO: e.date,
      }));
      rows.value = list;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

// เพิ่มข้อมูลการจ้าง
const modal = ref<boolean>(false);
const formData = reactive<FormEmployment>({
  dateEmployment: null,
  orderEmployment: "",
});
const dateEmploymentRef = ref<object | null>();
const orderEmploymentRef = ref<object | null>();
const formDataRef: FormEmploymentRef = {
  dateEmployment: dateEmploymentRef,
  orderEmployment: orderEmploymentRef,
};

function onClickAdd() {
  modal.value = true;
  actions.value = "";
  formData.dateEmployment = null;
  formData.orderEmployment = "";
}
function colsePopup() {
  modal.value = false;
  modalHistory.value = false;
}
// validateForm
function validateForm() {
  const hasError = [];
  for (const key in formDataRef) {
    if (Object.prototype.hasOwnProperty.call(formDataRef, key)) {
      const property = formDataRef[key];
      if (property.value && typeof property.value.validate === "function") {
        const isValid = property.value.validate();
        hasError.push(isValid);
      }
    }
  }
  if (hasError.every((result) => result === true)) {
    console.log(formData);
    if (actions.value == "edit") {
      onSubmitEdit();
    } else onSubmit();
  } else {
    console.log("ไม่ผ่าน ");
  }
}
// การเพิ่ม
function onSubmit() {
  dialogConfirm(
    $q,
    async () => {
      const data = {
        command: formData.orderEmployment,
        date: formData.dateEmployment,
      };
      await http
        .post(config.API.employmentId(profileId.value), data)
        .then(async () => {
          await fetchList();
          success($q, "บันทึกข้อมูลสำเร็จ");
        })
        .catch((err) => {
          messageError($q, err);
        })
        .finally(() => {
          colsePopup();
        });
    },
    "ยืนยันการบันทึกข้อมูล",
    "ต้องการยืนยันการบันทึกข้อมูลนี้หรือไม่ ?"
  );
}
// การลบ
function cilckDelete(id: string) {
  dialogRemove(
    $q,
    async () => {
      await http
        .delete(config.API.employmentId(id))
        .then(async () => {
          await fetchList();
          success($q, "ลบข้อมูลสำเร็จ");
        })
        .catch((err) => {
          messageError($q, err);
        });
    },
    "ยืนยันการลบข้อมูล",
    "ต้องการยืนยันการลบข้อมูลนี้หรือไม่ ?"
  );
}
// การแก้ไข
const actions = ref<string>("");
const employmentRowId = ref<string>("");
function clickEdit(data: any, actionstype: string) {
  modal.value = true;
  actions.value = actionstype;
  employmentRowId.value = data.id;
  formData.dateEmployment = data.dataISO;
  formData.orderEmployment = data.orderEmployment;
}
function onSubmitEdit() {
  dialogConfirm(
    $q,
    async () => {
      const data = {
        command: formData.orderEmployment,
        date: formData.dateEmployment,
      };
      await http
        .put(config.API.employmentId(employmentRowId.value), data)
        .then(async () => {
          await fetchList();
          success($q, "บันทึกข้อมูลสำเร็จ");
        })
        .catch((err) => {
          messageError($q, err);
        })
        .finally(() => {
          colsePopup();
        });
    },
    "ยืนยันการบันทึกข้อมูล",
    "ต้องการยืนยันการบันทึกข้อมูลนี้หรือไม่ ?"
  );
}
// ประวัติการแก้ไข
const modalHistory = ref<boolean>(false);
const rowsHis = ref<EmploymentList[]>([]);
const columnsHis = ref<QTableProps["columns"]>([
  {
    name: "dateEmployment",
    align: "left",
    label: "วันที่จ้าง",
    sortable: false,
    field: "dateEmployment",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "orderEmployment",
    align: "left",
    label: "คำสั่งจ้าง",
    sortable: false,
    field: "orderEmployment",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  // {
  //   name: "createdFullName",
  //   align: "left",
  //   label: "ผู้สร้าง",
  //   sortable: false,
  //   field: "createdFullName",
  //   headerStyle: "font-size: 14px",
  //   style: "font-size: 14px",
  // },
  // {
  //   name: "createdAt",
  //   align: "left",
  //   label: "วันที่สร้าง",
  //   sortable: false,
  //   field: "createdAt",
  //   headerStyle: "font-size: 14px",
  //   style: "font-size: 14px",
  // },
  {
    name: "lastUpdateFullName",
    align: "left",
    label: "ผู้ดำเนินการ",
    sortable: false,
    field: "lastUpdateFullName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "lastUpdatedAt",
    align: "left",
    label: "วันที่แก้ไข",
    sortable: false,
    field: "lastUpdatedAt",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);
const visibleColumnsHis = ref<string[]>([
  "dateEmployment",
  "orderEmployment",
  // "createdFullName",
  // "createdAt",
  "lastUpdateFullName",
  "lastUpdatedAt",
]);
const filterHis = ref<string>();
async function openPopupHistory(id: string) {
  modalHistory.value = true;
  filterHis.value = "";
  showLoader();
  await http
    .get(config.API.employmentHistoryId(id))
    .then((res) => {
      const data = res.data.result;
      const list: EmploymentList[] = data.map((e: Respones) => ({
        id: e.id,
        orderEmployment: e.command,
        dateEmployment: date2Thai(e.date),
        createdFullName: e.createdFullName,
        createdAt: date2Thai(e.createdAt),
        lastUpdateFullName: e.lastUpdateFullName,
        lastUpdatedAt: date2Thai(e.lastUpdatedAt),
      }));
      rowsHis.value = list;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}
const pagination = ref({
  descending: true,
  page: 1,
  rowsPerPage: 10,
});
const paginationHis = ref({
  descending: true,
  page: 1,
  rowsPerPage: 10,
});
</script>

<template>
  <q-card flat bordered class="col-12 q-px-lg q-py-md">
    <div class="flex items-center">
      <div class="flex items-center">
        <q-icon name="mdi-clipboard" size="1.5em" color="grey-5" class="q-mr-md" />

        <div class="text-bold text-subtitle2 col-12 row items-center">
          ข้อมูลการจ้าง
        </div>
      </div>
      <div class="q-gutter-sm q-mx-sm">
        <q-btn size="12px" flat round color="primary" @click="onClickAdd" icon="mdi-plus">
          <q-tooltip>เพิ่มข้อมูลการจ้าง</q-tooltip>
        </q-btn>
      </div>

      <q-space />
      <div class="q-gutter-sm" style="display: flex">
        <q-input outlined dense v-model="filter" label="ค้นหา" style="min-width: 150px" />

        <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" options-cover style="min-width: 150px" />
      </div>
    </div>
    <div class="q-mt-sm">
      <d-table flat bordered id="table" ref="table" :columns="columns" :rows="rows" :filter="filter"
        row-key="dateEmployment" :paging="true" dense :visible-columns="visibleColumns" v-model:pagination="pagination">
        <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-th auto-width></q-th>
            <q-th auto-width></q-th>
          </q-tr>
        </template>
        <template v-slot:body="props">
          <q-tr :props="props" class="cursor-pointer" style="height: 40px">
            <q-td v-for="col in props.cols" :key="col.name" :props="props">
              <div>
                {{ col.value }}
              </div>
            </q-td>
            <q-td>
              <q-btn dense flat round color="primary" icon="mdi-pencil" @click="clickEdit(props.row, 'edit')">
                <q-tooltip>แก้ไขข้อมูล</q-tooltip>
              </q-btn>
            </q-td>
            <q-td>
              <q-btn dense flat round color="red" icon="mdi-delete" @click="cilckDelete(props.row.id)">
                <q-tooltip>ลบข้อมูล</q-tooltip></q-btn>
            </q-td>
            <q-td>
              <q-btn dense flat round color="info" @click="openPopupHistory(props.row.id)" icon="mdi-history">
                <q-tooltip>ประวัติข้อมูลการจ้าง </q-tooltip>
              </q-btn>
            </q-td>
          </q-tr>
        </template>
      </d-table>
    </div>
  </q-card>

  <q-dialog v-model="modal">
    <q-card style="width: 700px; max-width: 80vw">
      <q-toolbar>
        <q-toolbar-title class="text-subtitle1 text-weight-bold">
          <span style="margin-right: 0" v-if="actions == 'edit'">
            แก้ข้อมูลการจ้าง
          </span>
          <span style="margin-right: 0" v-else> เพิ่มข้อมูลการจ้าง </span>
        </q-toolbar-title>
        <q-btn for="closeDialog" icon="close" unelevated round dense style="color: #eb0505; background-color: #ffdede"
          @click="colsePopup" />
      </q-toolbar>
      <q-separator />
      <form @submit.prevent="validateForm">
        <q-card-section class="q-pt-none">
          <div class="col-12 row q-pa-md">
            <div class="col-xs-12 col-sm-12 row q-col-gutter-x-md q-col-gutter-y-xs">
              <div class="col-xs-12 col-sm-6">
                <datepicker menu-class-name="modalfix" v-model="formData.dateEmployment" :locale="'th'" autoApply
                  borderless :enableTimePicker="false" week-start="0">
                  <template #year="{ year }">
                    {{ year + 543 }}
                  </template>
                  <template #year-overlay-value="{ value }">
                    {{ parseInt(value + 543) }}
                  </template>
                  <template #trigger>
                    <q-input for="inputdateEmployment" ref="dateEmploymentRef" outlined dense
                      class="full-width datepicker" :model-value="formData.dateEmployment != null
                          ? date2Thai(formData.dateEmployment)
                          : null
                        " label="วันที่จ้าง" :rules="[(val) => !!val || `${'กรุณาเลือกวันที่จ้าง'}`]" lazy-rules>
                      <template v-slot:prepend>
                        <q-icon name="event" class="cursor-pointer" style="color: var(--q-primary)">
                        </q-icon>
                      </template>
                    </q-input>
                  </template>
                </datepicker>
              </div>

              <div class="col-xs-12 col-sm-6">
                <q-input for="inputOrderEmployment" ref="orderEmploymentRef" dense outlined
                  v-model="formData.orderEmployment" label="คำสั่งจ้าง"
                  :rules="[(val) => !!val || `${'กรุณากรอกคำสั่งจ้าง'}`]" lazy-rules />
              </div>
            </div>
          </div>
          <div class="row col-12">
            <q-space />
          </div>
        </q-card-section>
        <q-separator />
        <q-card-actions align="right" class="bg-white text-teal">
          <q-btn for="ButtonOnSubmit" id="onSubmit" flat round color="secondary" icon="mdi-content-save-outline"
            type="submit"><q-tooltip>บับทึกข้อมูล</q-tooltip></q-btn>
        </q-card-actions>
      </form>
    </q-card>
  </q-dialog>

  <q-dialog v-model="modalHistory">
    <q-card style="width: 800px; max-width: 80vw">
      <q-toolbar>
        <q-toolbar-title class="text-subtitle1 text-weight-bold">
          <span style="margin-right: 0"> ประวัติข้อมูลการจ้าง </span>
        </q-toolbar-title>
        <q-btn for="closeDialog" icon="close" unelevated round dense style="color: #eb0505; background-color: #ffdede"
          @click="colsePopup" />
      </q-toolbar>
      <q-separator />

      <q-card-section class="q-pt-none q-mt-sm">
        <q-toolbar class="q-pa-none">
          <q-space />
          <div class="q-gutter-sm" style="display: flex">
            <q-input outlined dense v-model="filterHis" label="ค้นหา" style="min-width: 150px" />

            <q-select v-model="visibleColumnsHis" multiple outlined dense options-dense
              :display-value="$q.lang.table.columns" emit-value map-options :options="columnsHis" option-value="name"
              options-cover style="min-width: 150px" />
          </div>
        </q-toolbar>
        <d-table flat bordered id="table" ref="table" :columns="columnsHis" :rows="rowsHis" :filter="filterHis"
          row-key="dateEmployment" :paging="true" dense :visible-columns="visibleColumnsHis"
          v-model:pagination="paginationHis">
          <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-tr>
          </template>
          <template v-slot:body="props">
            <q-tr :props="props" class="cursor-pointer" style="height: 40px">
              <q-td v-for="col in props.cols" :key="col.name" :props="props">
                <div>
                  {{ col.value }}
                </div>
              </q-td>
            </q-tr>
          </template>
        </d-table>
      </q-card-section>
    </q-card>
  </q-dialog>
</template>

<style scoped></style>
