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

import http from "@/plugins/http";
import config from "@/app.config";
import { useCounterMixin } from "@/stores/mixin";
import { useDataStore } from "@/modules/05_command/stores/main";

import type {
  ActiveOptions,
  ListOrder,
  Tabs,
  DateOption,
} from "@/modules/05_command/interface/index/Main";

import Header from "@/components/DialogHeader.vue";
import PageOrder from "@/modules/05_command/components/ViewPdf.vue";
import TemplateDetail from "@/modules/05_command/components/FormTemplate.vue";

const $q = useQuasar();
const mixin = useCounterMixin();
const store = useDataStore();
const {
  dialogConfirm,
  success,
  showLoader,
  hideLoader,
  dialogRemove,
  messageError,
} = mixin;

const isActive = ref<string>(""); // สถานะของรายการคำสั่ง
// options สถานะการใช้งาน
const activeOptions = ref<ActiveOptions[]>([
  {
    value: true,
    label: "Active",
  },
  {
    value: false,
    label: "InActive",
  },
]);

// Tabs
const tabs = ref<Tabs[]>([
  {
    value: "order",
    label: "คำสั่ง",
  },
  {
    value: "account",
    label: "บัญชีแนบท้าย",
  },
  {
    value: "template",
    label: "ข้อความต้นแบบ",
  },
]);

const dataCategory = ref<DateOption[]>([]); //ข้อมูล หมวดหมู่
const categoryOP = ref<DateOption[]>([]); // options หมวดหมู่

const idOrder = ref<string>(""); // Id คำสั่ง
const activeOrderId = ref<string>(""); // Id คำสั่งที่เลือก
const name = ref<string>(""); // ชื่อคำสั่ง
const category = ref<string>(""); // หมวดหมู่
const listOrder = ref<ListOrder[]>([]); // list คำสั่ง
const status = ref<boolean>(false); // สถานะ
const isEdit = ref<boolean>(false); //เก็บ true/false เช็คแก้ไข
const dialogFormCommand = ref<boolean>(false); // model คำสั่ง

/**
 * ฟังก์ชั่นค้นหาคำสั่ง ตามสถานะ
 * @param val สถานะ true/false
 */
function searchByStatus(val: string) {
  console.log(val);
}

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

  isEdit.value = true;
  dialogFormCommand.value = true;
}

/**
 * ลบ คำสั่ง
 * @param id id คำสั่ง
 */
function onDelete(id: string) {
  dialogRemove($q, () => {
    // http
    //   .delete(config.API.)
    //   .then((res) => {})
    //   .catch((e) => {
    //     messageError($q, e);
    //   })
    //   .finally(() => {});
  });
}

/** ปิด dialog */
function closeDialog() {
  idOrder.value = "";
  isEdit.value = false;
  dialogFormCommand.value = false;
  name.value = "";
  status.value = false;
}

/** บันทึกข้อมูล dialog */
function onSubmit() {
  dialogConfirm($q, () => {});
}

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

/**
 * ฟังก์ชั่นดึงรายการประเภทคำสั่ง
 */
async function fetchOrderType() {
  showLoader();
  await http
    .get(config.API.commandType)
    .then(async (res) => {
      listOrder.value = res.data.result.map((item: any) => {
        return {
          name: item.name,
          category: item.category,
          commandCode: item.commandCode,
          id: item.id,
          status: true,
        };
      });
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * ฟังก์ชั่นค้นหาข้อมูลใน Select หมวดหมู่
 * @param val คำค้นหา
 * @param update ฟังก์ชั่นค้นหา
 */
function filterSelector(val: string, update: Function) {
  update(() => {
    category.value = val ? "" : category.value;
    categoryOP.value = dataCategory.value.filter(
      (v: any) => v.name.indexOf(val) > -1
    );
  });
}

/** เริ่มเมื่อโหลดหน้านี้*/
onMounted(() => {
  fetchOrderType();
});
</script>

<template>
  <div class="toptitle text-dark col-12 row items-center">
    รายการคำสั่งและ Template
  </div>
  <div class="row q-col-gutter-sm">
    <div class="col-4">
      <q-card bordered style="height: 100%">
        <div class="row items-center q-pa-sm">
          <div class="col-2">
            <q-btn
              flat
              dense
              round
              icon="add"
              color="primary"
              @click="onDialogAdd()"
            >
              <q-tooltip>เพิ่มข้อมูล</q-tooltip>
            </q-btn>
          </div>
          <q-space />
          <div class="col-12 col-md-6">
            <q-select
              outlined
              dense
              v-model="isActive"
              class="inputgreen"
              label="สถานะการใช้งาน"
              :options="activeOptions"
              option-label="label"
              option-value="value"
              emit-value
              @update:model-value="searchByStatus"
            ></q-select>
          </div>
        </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.name }}
                  </q-item-label>
                </q-item-section>
                <q-item-section side center @click.stop>
                  <q-icon
                    name="mdi-dots-vertical"
                    class="q-pa-none q-ml-xs"
                    color="grey-13"
                    flat
                    dense
                  >
                    <q-menu
                      transition-show="jump-down"
                      transition-hide="jump-up"
                    >
                      <q-list dense style="min-width: 160px">
                        <q-item
                          clickable
                          v-close-popup
                          @click="onDialogEdit(item)"
                        >
                          <q-item-section
                            style="min-width: 0px"
                            avatar
                            class="q-py-sm"
                          >
                            <q-icon color="edit" size="xs" name="mdi-pencil" />
                          </q-item-section>
                          <q-item-section>แก้ไข</q-item-section>
                        </q-item>
                        <q-separator />
                        <q-item
                          clickable
                          v-close-popup
                          @click="onDelete(item.id)"
                        >
                          <q-item-section
                            style="min-width: 0px"
                            avatar
                            class="q-py-sm"
                          >
                            <q-icon color="red" size="xs" name="mdi-delete" />
                          </q-item-section>
                          <q-item-section>ลบ</q-item-section>
                        </q-item>

                        <q-separator />
                      </q-list> </q-menu
                  ></q-icon>
                </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-8">
      <q-card bordered style="height: 100%">
        <div v-if="activeOrderId !== ''">
          <q-tabs
            dense
            v-model="store.currentTab"
            align="left"
            indicator-color="primary"
            active-color="primary bg-teal-1"
            inline-label
            class="text-body2 text-grey-7"
          >
            <q-tab
              v-for="tab in tabs"
              :key="tab.value"
              v-on:click="store.currentTab = tab.value"
              :label="tab.label"
              :name="tab.value"
              class="q-py-xs"
            />
          </q-tabs>
          <q-separator />
          <q-tab-panels v-model="store.currentTab" animated>
            <q-tab-panel name="order">
              <PageOrder
                v-model:type="store.currentTab"
                :id-order="activeOrderId"
              />
            </q-tab-panel>
            <q-tab-panel name="account">
              <PageOrder
                v-model:type="store.currentTab"
                :id-order="activeOrderId"
              />
            </q-tab-panel>
            <q-tab-panel name="template">
              <TemplateDetail
                v-model:type="store.currentTab"
                :command-id="activeOrderId"
              />
            </q-tab-panel>
          </q-tab-panels>
        </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="dialogFormCommand" 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="name"
                label="ชื่อคำสั่ง"
                class="inputgreen"
                :rules="[(val:string) => !!val || `${'กรุณากรอกชื่อคำสั่ง'}`,]"
                hide-bottom-space
              ></q-input>
            </div>
            <div class="col-12">
              <q-select
                class="inputgreen"
                v-model="category"
                :label="`${'หมวดหมู่'}`"
                dense
                emit-value
                map-options
                option-label="name"
                :options="categoryOP"
                option-value="id"
                lazy-rules
                use-input
                hide-bottom-space
                outlined
                :rules="[(val:string) => !!val || `${'กรุณาเลือกหมวดหมู่'}`]"
                @filter="(inputValue:string,
                    doneFn:Function) => filterSelector(inputValue, doneFn) "
              >
                <template v-slot:no-option>
                  <q-item>
                    <q-item-section class="text-grey">
                      ไม่มีข้อมูล
                    </q-item-section>
                  </q-item>
                </template>
              </q-select>
            </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="status" />
                  <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>
