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

import http from "@/plugins/http";
import config from "@/app.config";

import { useCounterMixin } from "@/stores/mixin";

import type {
  CommandSysType,
  ListTemplateSalary,
} from "@/modules/05_command/interface/index/Main";

import Header from "@/components/DialogHeader.vue";

const $q = useQuasar();
const mixin = useCounterMixin();

const {
  dialogConfirm,
  success,
  showLoader,
  hideLoader,
  dialogRemove,
  messageError,
} = mixin;

const total = ref<number>(0);
const totalList = ref<number>(1);
const pagination = ref({
  sortBy: "createdAt",
  descending: true,
  page: 1,
  rowsPerPage: 10,
});

const filter = ref<string>(""); // ตัวแปร ฟิลเตอร์
const listOrder = ref<CommandSysType[]>([]);
const activeOrderId = ref<string>(""); // ตัวแปรเก็บ id เพื่อเอาไป = class
const isActive = ref<boolean>(true); // สถานะการใช้งาน
const dataForm = reactive<ListTemplateSalary>({
  id: "",
  name: "",
  isActive: false,
});
const isEdit = ref<boolean>(false); //เก็บ true/false เช็คแก้ไข
const dialogForm = ref<boolean>(false); // model คำสั่ง

const rows = ref<ListTemplateSalary[]>([]);
const visibleColumns = ref<String[]>(["no", "name", "isActive"]);
const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: false,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    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: "isActive",
    align: "center",
    label: "สถานะการใช้งาน",
    sortable: true,
    field: "isActive",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);

/** เปิด dialog */
function onDialogAdd() {
  isEdit.value = false;
  dialogForm.value = true;
}
/**
 * เปิด dialog Edit
 * @param data ข้อมูลคำสั่ง
 */
function onDialogEdit(data: ListTemplateSalary) {
  dataForm.id = data.id;
  dataForm.name = data.name;
  dataForm.isActive = data.isActive;

  isEdit.value = true;
  dialogForm.value = true;
}

/**
 * ลบ คำสั่ง
 * @param id id คำสั่ง
 */
async function onDelete(id: string) {
  dialogRemove($q, async () => {
    showLoader();
    await http
      .delete(config.API.commandSalaryById(id))
      .then(async () => {
        await fetchSalaryList();
        success($q, "ลบข้อมูลเสร็จสิ้น");
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

/** ปิด dialog */
function closeDialog() {
  dataForm.id = "";
  dataForm.name = "";
  dataForm.isActive = false;
  isEdit.value = false;
  dialogForm.value = false;
}

/** บันทึกข้อมูล dialog */
function onSubmit() {
  dialogConfirm($q, async () => {
    const url = isEdit.value
      ? config.API.commandSalaryById(dataForm.id)
      : config.API.commandSalary;
    showLoader();
    await http[isEdit.value ? "put" : "post"](url, {
      name: dataForm.name,
      commandSysId: activeOrderId.value,
      isActive: dataForm.isActive,
    })
      .then(async () => {
        await fetchSalaryList();
        success($q, "บันทึกข้อมูลสำเร็จ");
        closeDialog();
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

/** เก็บ id list คำสั่งที่เลือก เพื่อใช้ class */
function selectInbox(data: CommandSysType) {
  activeOrderId.value = data.id;
  pagination.value.page = 1;
  filter.value = "";

  fetchSalaryList();
}

/**
 * ฟังก์ชั่นดึงรายการประเภทคำสั่ง
 */
async function fetchSalaryList() {
  showLoader();
  rows.value = [];
  await http
    .get(
      config.API.commandSalaryDetail(
        pagination.value.page,
        pagination.value.rowsPerPage,
        isActive.value,
        activeOrderId.value,
        filter.value
      )
    )
    .then(async (res) => {
      totalList.value = Math.ceil(
        res.data.result.total / pagination.value.rowsPerPage
      );
      total.value = res.data.result.total;
      rows.value = res.data.result.commandSalarys;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/** ดึงข้อมูล list */
async function getMainData() {
  showLoader();
  await http
    .get(config.API.commandSysList)
    .then(async (res) => {
      const data = await res.data.result;
      listOrder.value = data;
      hideLoader();
    })
    .catch((e) => {
      messageError($q, e);
      hideLoader();
    })
    .finally(() => {});
}

function updatePagination(newPagination: any) {
  pagination.value.page = 1;
  pagination.value.rowsPerPage = newPagination.rowsPerPage;
}

/** เช็คการเปลี่ยนแปลงของค่า  pagination.value.rowsPerPage*/
watch(
  () => pagination.value.rowsPerPage,
  async () => {
    await fetchSalaryList();
  }
);

/** เช็คการเปลี่ยนแปลงของค่า  isActive*/
watch(
  () => isActive.value,
  async () => {
    pagination.value.page = 1;
    await fetchSalaryList();
  }
);
/** เริ่มเมื่อโหลดหน้านี้*/
onMounted(() => {
  getMainData();
});
</script>

<template>
  <div class="toptitle text-dark col-12 row items-center">
    ต้นแบบ สำหรับลงในตำแหน่ง/เงินเดือน
  </div>
  <div class="row q-col-gutter-sm">
    <div class="col-3">
      <q-card bordered style="height: 100%">
        <div class="text-body1 q-pa-sm text-weight-medium">ประเภทระบบ</div>
        <q-separator />
        <q-card-section class="q-pa-sm">
          <q-scroll-area style="height: 70vh" class="scrollStyle">
            <q-list
              v-for="(item, index) in listOrder"
              :key="item.id"
              class="q-pr-sm"
            >
              <q-item
                clickable
                v-ripple
                :active="activeOrderId === item.id"
                active-class="my-menu_link"
                @click="selectInbox(item)"
              >
                <q-item-section>
                  <q-item-label>
                    {{ item.sysName }}
                  </q-item-label>
                </q-item-section>
              </q-item>
              <q-separator v-if="listOrder.length !== index + 1" />
            </q-list>
          </q-scroll-area>
        </q-card-section>
      </q-card>
    </div>
    <div class="col-9">
      <q-card bordered style="height: 100%">
        <div v-if="activeOrderId !== ''">
          <div class="row q-pa-sm q-col-gutter-sm">
            <div class="col-12">
              <div class="row q-gutter-sm items-center">
                <div>
                  <q-btn
                    flat
                    dense
                    round
                    icon="add"
                    color="primary"
                    @click="onDialogAdd"
                    ><q-tooltip>เพิ่มข้อมูล</q-tooltip>
                  </q-btn>
                </div>

                <q-space />

                <div class="row items-center no-wrap">
                  <q-label
                    :class="`${isActive ? `text-primary` : `text-orange`}`"
                    >{{ `${isActive ? `ใช้งาน` : `ไม่ใช้งาน`}` }}</q-label
                  >
                  <label :class="`q-ml-lg toggle-control`">
                    <input type="checkbox" v-model="isActive" />
                    <span class="control"></span>
                  </label>
                </div>

                <q-input
                  borderless
                  dense
                  outlined
                  v-model="filter"
                  placeholder="ค้นหา"
                  @keydown.enter.prevent="(pagination.page = 1), fetchSalaryList()"
                >
                  <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"
                />
              </div>
            </div>
            <div class="col-12">
              <d-table
                ref="table"
                :columns="columns"
                :rows="rows"
                row-key="id"
                flat
                bordered
                :paging="true"
                dense
                :rows-per-page-options="[25, 50, 100]"
                @update:pagination="updatePagination"
                :visible-columns="visibleColumns"
              >
                <template v-slot:pagination="scope">
                  ทั้งหมด {{ total }} รายการ
                  <q-pagination
                    v-model="pagination.page"
                    active-color="primary"
                    color="dark"
                    :max="Number(totalList)"
                    size="sm"
                    boundary-links
                    direction-links
                    :max-pages="5"
                    @update:model-value="fetchSalaryList"
                  ></q-pagination>
                </template>

                <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"
                      style="color: #000000; font-weight: 500"
                    >
                      <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">
                    <q-td auto-width>
                      <q-btn
                        flat
                        dense
                        round
                        icon="edit"
                        color="edit"
                        @click="onDialogEdit(props.row)"
                        ><q-tooltip>แก้ไขข้อมูล</q-tooltip>
                      </q-btn>
                      <q-btn
                        flat
                        dense
                        round
                        icon="mdi-delete"
                        color="red"
                        @click="onDelete(props.row.id)"
                        ><q-tooltip>ลบข้อมูล</q-tooltip>
                      </q-btn>
                    </q-td>
                    <q-td
                      v-for="col in props.cols"
                      :key="col.name"
                      :props="props"
                    >
                      <div v-if="col.name == 'no'">
                        {{
                          (pagination.page - 1) * pagination.rowsPerPage +
                          props.rowIndex +
                          1
                        }}
                      </div>
                      <div v-else-if="col.name == 'isActive'">
                        <q-icon
                          size="sm"
                          :color="props.row.isActive ? 'teal' : 'orange'"
                          :name="props.row.isActive ? 'mdi-check' : 'mdi-close'"
                        />
                      </div>
                      <div v-else>
                        {{ col.value }}
                      </div>
                    </q-td>
                  </q-tr>
                </template>
              </d-table>
            </div>
          </div>
        </div>
        <div v-else style="height: auto; max-width: 100%; max-height: 90vh">
          <div
            class="absolute-center text-center text-grey-9"
            style="width: 100%"
          >
            <div class="column items-center">
              <q-icon
                name="mdi-hand-pointing-left"
                size="lg"
                color="primary"
              ></q-icon>
              <span>กรุณาเลือกรายการคำสั่ง</span>
            </div>
          </div>
        </div>
      </q-card>
    </div>
  </div>

  <q-dialog v-model="dialogForm" persistent>
    <q-card class="col-12" style="min-width: 30%">
      <q-form greedy @submit.prevent @validation-success="onSubmit">
        <Header
          :tittle="`${
            isEdit ? 'แก้ไข' : 'เพิ่ม'
          }ต้นแบบสำหรับลงในตำแหน่ง/เงินเดือน`"
          :close="closeDialog"
        />
        <q-separator />

        <q-card-section>
          <div class="row q-col-gutter-sm">
            <div class="col-12">
              <q-input
                outlined
                dense
                v-model="dataForm.name"
                label="ข้อความต้นแบบ"
                class="inputgreen"
                :rules="[(val:string) => !!val || `${'กรุณากรอกข้อความต้นแบบ'}`,]"
                hide-bottom-space
              ></q-input>
            </div>
            <div class="col-12">
              <div class="row items-center justify-between border_custom">
                <p class="q-ma-none">สถานะการใช้งาน</p>
                <label :class="`toggle-control`">
                  <input type="checkbox" v-model="dataForm.isActive" />
                  <span class="control"></span>
                </label>
              </div>
            </div>
          </div>
        </q-card-section>
        <q-separator />

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

<style scoped lang="scss">
:deep(.scrollStyle .q-scrollarea__bar) {
  background-color: #909090;
  border-radius: 10px;
  width: 5px;
  opacity: 0.1;
  right: 0px;
}
:deep(.scrollStyle .q-scrollarea__thumb) {
  background-color: #909090;
  border-radius: 10px;
  width: 5px;
  opacity: 0.5;
  right: 0px;
}
.my-menu_link {
  background: #ebf9f7 !important;
  border-radius: 5px;
  color: #1bb19ab8 !important;
}

.my-menu-link .q-hoverable {
  border-radius: 5px;
}

.my-link {
  font-size: 0.75rem;
  padding: 2px;
  min-height: 10px !important;
}

.my-link:hover {
  border-radius: 5px;
}

.border_custom {
  border-radius: 5px !important;
  border: 1px solid #c8d3db;
  height: 40px;
  padding: 0 12px;
}
$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;
$toggle-radius: calc($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>
