<script setup lang="ts">
import { ref, onMounted } from "vue";
import type { QTableProps } from "quasar";
import { useCounterMixin } from "@/stores/mixin";
import { useRouter } from "vue-router";
import { useInsigniaDataStore } from "@/modules/01_metadataNew/stores/InsigniaStore";
import dialogHeader from "@/components/DialogHeader.vue";
import { useQuasar } from "quasar";
import http from "@/plugins/http";
import config from "@/app.config";

const store = useInsigniaDataStore();
const router = useRouter();
const mixin = useCounterMixin();
const {
  dialogRemove,
  dialogConfirm,
  success,
  messageError,
  showLoader,
  hideLoader,
} = mixin;
const columns = ref<QTableProps["columns"]>([
  {
    name: "name",
    align: "left",
    label: "ลำดับชั้นเครื่องราชฯ",
    sortable: true,
    field: "name",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "createdAt",
    align: "center",
    label: "วันที่สร้าง",
    sortable: true,
    field: "createdAt",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "lastUpdatedAt",
    align: "center",
    label: "วันที่แก้ไข",
    sortable: true,
    field: "lastUpdatedAt",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.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: "isActive",
    align: "left",
    label: "สถานะ",
    sortable: true,
    field: "isActive",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);

const $q = useQuasar();

const editId = ref<string>("");
const filterKeyword = ref<string>("");
const dialog = ref<boolean>(false);
const isActive = ref<boolean>(false);
const name = ref<string>("");
const nameRef = ref<any>(null);
const dialogStatus = ref<string>("");
const visibleColumns = ref<string[]>([
  "name",
  "createdAt",
  "lastUpdatedAt",
  "lastUpdateFullName",
  "isActive",
]);

async function fetchData() {
  showLoader();
  await http
    .get(config.API.insigniaTypeOrg)
    .then(async (res) => {
      store.fetchData(res.data.result);
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

onMounted(async () => {
  fetchData();
});

function closeDialog() {
  dialog.value = false;
}

function onclickDetail(id: string) {
  router.push(`/master-data/insignia/detail/${id}`);
}

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

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

async function deleteData(id: string) {
  await http
    .delete(config.API.insigniaTypeNewIdOrg(id))
    .then(() => {
      fetchData();
      success($q, "ลบข้อมูลสำเร็จ");
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

function validateForm() {
  nameRef.value.validate();
  onSubmit();
}

async function onSubmit() {
  if (name.value.length > 0) {
    dialogConfirm(
      $q,
      async () => {
        dialogStatus.value === "create" ? addData() : editData(editId.value);
        closeDialog();
        name.value = "";
        isActive.value = false;
      },
      "ยืนยันการบันทึกข้อมูล",
      "ต้องการยืนยันการบันทึกข้อมูลนี้หรือไม่ ?"
    );
  }
}
</script>

<template>
  <q-toolbar style="padding: 0">
    <q-btn
      flat
      round
      color="primary"
      icon="add"
      @click.stop="
        () => {
          dialogStatus = 'create';
          dialog = true;
        }
      "
    >
      <q-tooltip> เพิ่มข้อมูล </q-tooltip>
    </q-btn>
    <q-space />
    <div class="row q-gutter-sm">
      <q-input outlined dense v-model="filterKeyword" label="ค้นหา"></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"
        options-cover
        style="min-width: 150px"
      />
    </div>
  </q-toolbar>

  <d-table
    ref="table"
    :columns="columns"
    :rows="store.row"
    :filter="filterKeyword"
    row-key="name"
    flat
    bordered
    :paging="true"
    dense
    class="custom-header-table"
    :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-tr>
    </template>
    <template v-slot:body="props">
      <q-tr
        :props="props"
        class="cursor-pointer"
        @click.stop="onclickDetail(props.row.id)"
      >
        <q-td v-for="col in props.cols" :key="col.id">
          <div v-if="col.name == 'isActive'">
            <q-icon
              v-if="col.value == false"
              name="mdi-close"
              color="red"
              class="text-h5"
            />
            <q-icon v-else name="mdi-check" color="positive" class="text-h5" />
          </div>
          <div v-else>
            {{ col.value }}
          </div>
        </q-td>
        <q-td auto-width>
          <q-btn
            color="edit"
            flat
            dense
            round
            class="q-mr-xs"
            size="12px"
            icon="edit"
            clickable
            @click.stop="
              () => {
                dialogStatus = 'edit';
                dialog = true;
                editId = props.row.id;
                name = props.row.name;
                isActive = props.row.isActive;
              }
            "
          >
            <q-tooltip>แก้ไขข้อมูล</q-tooltip>
          </q-btn>
          <q-btn
            color="red"
            flat
            dense
            round
            size="12px"
            icon="mdi-delete"
            clickable
            @click.stop="
              dialogRemove($q, async () => await deleteData(props.row.id))
            "
            v-close-popup
          >
            <q-tooltip>ลบข้อมูล</q-tooltip>
          </q-btn>
        </q-td>
      </q-tr>
    </template>
  </d-table>

  <q-dialog v-model="dialog" class="dialog" persistent>
    <q-card style="min-width: 350px">
      <form @submit.prevent="validateForm">
        <q-card-section class="flex justify-between" style="padding: 0">
          <dialog-header
            :tittle="dialogStatus === 'edit' ? 'แก้ไขข้อมูล' : 'เพิ่มข้อมูล'"
            :close="closeDialog"
          />
        </q-card-section>

        <q-separator color="grey-4" />
        <q-card-section class="q-pa-none">
          <div class="col-12 q-ma-md">
            <q-input
              ref="nameRef"
              outlined
              v-model="name"
              label="ลำดับชั้นเครื่องราชฯ"
              dense
              lazy-rules
              borderless
              :rules="[
                (val) => val.length > 0 || 'กรุณากรอกลำดับชั้นเครื่องราชฯ',
              ]"
              hide-bottom-space
            />
          </div>
          <div
            class="col q-ma-md q-pa-sm bg-white border_custom text-weight-medium"
          >
            <div class="row items-center q-my-sm justify-between">
              <p class="q-ma-none">สถานะการใช้งาน</p>
              <label class="toggle-control">
                <input type="checkbox" dense v-model="isActive" @change="" />
                <span class="control"></span>
              </label>
            </div>
          </div>
        </q-card-section>

        <q-card-actions align="right">
          <q-btn
            id="onSubmit"
            type="submit"
            dense
            unelevated
            label="บันทึก"
            color="public"
          >
            <q-tooltip>บันทึกข้อมูล</q-tooltip>
          </q-btn>
        </q-card-actions>
      </form>
    </q-card>
  </q-dialog>
</template>

<style scoped lang="scss">
.border_custom {
  border-radius: 6px !important;
  border: 1px solid #e1e1e1;
}
$toggle-background-color-on: #06884d;
$toggle-background-color-off: darkgray;
$toggle-control-color: white;
$toggle-width: 40px;
$toggle-height: 25px;
$toggle-gutter: 3px;
$toggle-radius: 50%;
$toggle-control-speed: 0.15s;
$toggle-control-ease: ease-in;

// These are our computed variables
// change at your own risk.
$toggle-radius: $toggle-height / 2;
$toggle-control-size: $toggle-height - ($toggle-gutter * 2);

.toggle-control {
  display: block;
  position: relative;
  padding-left: $toggle-width;
  margin-bottom: 12px;
  cursor: pointer;
  font-size: 22px;
  user-select: none;

  input {
    position: absolute;
    opacity: 0;
    cursor: pointer;
    height: 0;
    width: 0;
  }

  input:checked ~ .control {
    background-color: $toggle-background-color-on;

    &:after {
      left: $toggle-width - $toggle-control-size - $toggle-gutter;
    }
  }

  .control {
    position: absolute;
    top: -7px;
    left: -15px;
    height: $toggle-height;
    width: $toggle-width;
    border-radius: $toggle-radius;
    background-color: $toggle-background-color-off;
    transition: background-color $toggle-control-speed $toggle-control-ease;

    &:after {
      content: "";
      position: absolute;
      left: $toggle-gutter;
      top: $toggle-gutter;
      width: $toggle-control-size;
      height: $toggle-control-size;
      border-radius: $toggle-radius;
      background: $toggle-control-color;
      transition: left $toggle-control-speed $toggle-control-ease;
    }
  }
}
</style>
