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

import http from "@/plugins/http";
import config from "@/app.config";
import router from "@/router";
import { checkPermission } from "@/utils/permissions";
import { useOrderPlacementDataStore } from "@/modules/10_order/store";
import { useOrderStore } from "@/modules/11_discipline/store/OrderStore";

import { useCounterMixin } from "@/stores/mixin";
import type { DataOption1 } from "@/modules/10_order/interface/index/Main";
import PopupHistory from "@/modules/10_order/components/PopupHistory.vue";
import TableOrder from "@/modules/11_discipline/components/9_Order/TableOrder.vue";

const $q = useQuasar(); //ใช้ noti quasar
const mixin = useCounterMixin();
const stroe = useOrderStore();
const { showLoader, hideLoader, messageError, date2Thai } = mixin;

const commandCodes = ref<string[]>([
  "C-PM-19",
  "C-PM-20",
  "C-PM-25",
  "C-PM-26",
  "C-PM-27",
  "C-PM-28",
  "C-PM-29",
  "C-PM-30",
  "C-PM-31",
  "C-PM-32",
]);

// รายการข้อมูลปีงบประมาณ
const fiscalyear = ref<number | null>(0);
const fiscalyearOP = ref<any>([{ id: 0, name: "ทั้งหมด" }]);
const fiscalyearFilter1 = ref<any>([]);
async function fiscalYearFilter() {
  await http.get(config.API.yearOptionsOrder()).then((res) => {
    const response = res.data.result;
    fiscalyearOP.value = [{ id: 0, name: "ทั้งหมด" }];
    response.map((r: any) => {
      fiscalyearOP.value.push({ id: r.id, name: r.name.toString() });
    });

    fiscalyearFilter1.value = [{ id: 0, name: "ทั้งหมด" }];
    response.map((r: any) => {
      fiscalyearFilter1.value.push({
        id: r.id,
        name: r.name.toString(),
      });
    });
  });
}

// รายการข้อมูลประเภทคำสั่ง
const OrderType = ref<string>("");
const OrderTypeFilter1 = ref<any>([]);
const OrderTypeOption = ref<DataOption1[]>([{ id: "", name: "ทั้งหมด" }]);

// รายการข้อมูลสถานะคำสั่ง
const OrderStatus = ref<string>("ทั้งหมด");
const OrderStatusOption = ref<DataOption1[]>([
  { id: "ทั้งหมด", name: "ทั้งหมด" },
]);
const OrderStatusFilter1 = ref<DataOption1[]>([
  { id: "ทั้งหมด", name: "ทั้งหมด" },
]);
const addedOrderStatusValues: string[] = [];

// ค้นหาในตาราง
const filterKeyword = ref<string>("");
const filterRef = ref<any>(null);

/** ล้างค่า input */
function resetFilter() {
  filterKeyword.value = "";
  filterRef.value.focus();
}

/** ประเภทครับสั่ง ฟิลเตอร์ */
async function OrderTypeFilter() {
  await http
    .get(config.API.typeOrder())
    .then((res) => {
      const response = res.data.result;
      const filterRes = response.filter((e: any) =>
        commandCodes.value.includes(e.commandCode)
      );

      OrderTypeOption.value = [{ id: "", name: "ทั้งหมด" }];
      OrderTypeOption.value.push(...filterRes);

      OrderTypeFilter1.value = [{ id: "", name: "ทั้งหมด" }];
      OrderTypeFilter1.value.push(...filterRes);
    })
    .catch((e) => {
      messageError($q, e);
    });
}

/** ฟังชั่นฟิลเตอร์ตามค่า ประเภท สถานะ ปี */
async function searchFilterTable() {
  stroe.filterListOrder(OrderType.value, OrderStatus.value, fiscalyear.value);
}

/** สถานะคำสั่ง ฟิลเตอร์ */
async function OrderStatusFilter() {
  for (let data of stroe.mainData) {
    const OrderStatusValue = data.orderStatusName;

    if (
      OrderStatusValue === null ||
      parseInt(OrderStatusValue) > parseInt(OrderStatusValue)
    ) {
      OrderStatus.value = OrderStatusValue;
    }

    if (!addedOrderStatusValues.includes(OrderStatusValue)) {
      OrderStatusFilter1.value.push({
        id: OrderStatusFilter1.value.length.toString(),
        name: OrderStatusValue,
      });
      addedOrderStatusValues.push(OrderStatusValue);
    }
  }
}

/**
 * ฟิลเตอร์ข้อมูลจาก input
 * @param val ค่าที่ป้อนให้ input
 * @param update function จาก quasar
 * @param refData type ที่กำหนด ของ input นั้นๆ
 */
function filterSelector(val: any, update: Function, refData: string) {
  switch (refData) {
    case "fiscalyearOP":
      update(() => {
        fiscalyearOP.value = fiscalyearFilter1.value.filter(
          (v: any) => v.name.indexOf(val) > -1
        );
      });
      break;
    case "OrderTypeOption":
      update(() => {
        OrderTypeOption.value = OrderTypeFilter1.value.filter(
          (v: any) => v.name.indexOf(val) > -1
        );
      });
      break;
    case "OrderStatusOption":
      update(() => {
        OrderStatusOption.value = OrderStatusFilter1.value.filter(
          (v: any) => v.name.indexOf(val) > -1
        );
      });
      break;
    default:
      break;
  }
}

async function fetchOrderlist() {
  showLoader();
  await http
    .get(config.API.listOrder())
    .then((res: any) => {
      const data = res.data.result;
      const typeid = OrderTypeOption.value.map((e) => e.id);

      const filterListOrder = data.filter((e: any) =>
        typeid.includes(e.orderTypeValue)
      );

      stroe.fetchOrder(filterListOrder);
    })
    .catch((e: any) => {
      messageError($q, e);
    })
    .finally(async () => {
      hideLoader();
    });
}

// สร้างคำสั่งใหม่
function clickAdd() {
  router.push({ name: "disciplineOrderAdd" });
}
onMounted(async () => {
  await fiscalYearFilter();
  await OrderTypeFilter();
  await fetchOrderlist();
  await OrderStatusFilter();
});
</script>

<template>
  <div class="toptitle text-dark col-12 row items-center">
    ออกคำสั่งลงโทษทางวินัย
  </div>
  <div>
    <q-card flat bordered class="col-12 q-mt-sm q-pa-md">
      <div class="row q-col-gutter-sm">
        <div class="row col-12 q-col-gutter-sm">
          <q-select
            class="col-xs-12 col-sm-3 col-md-"
            v-model="fiscalyear"
            label="ปีงบประมาณ"
            dense
            emit-value
            map-options
            :options="fiscalyearOP"
            option-value="id"
            option-label="name"
            lazy-rules
            use-input
            hide-bottom-space
            :readonly="false"
            :borderless="false"
            :outlined="true"
            :hide-dropdown-icon="false"
            @update:model-value="searchFilterTable"
            @filter="(inputValue:any,
                      doneFn:Function) => filterSelector(inputValue, doneFn,'fiscalyearOP'
                      ) "
          >
            <template v-slot:no-option>
              <q-item>
                <q-item-section class="text-grey"> ไม่มีข้อมูล </q-item-section>
              </q-item>
            </template>
            <template v-if="fiscalyear !== 0" v-slot:append>
              <q-icon
                name="cancel"
                @click.stop.prevent="
                  (fiscalyearOP = fiscalyearFilter1)((fiscalyear = 0)),
                    searchFilterTable()
                "
                class="cursor-pointer"
              />
            </template>
          </q-select>
          <!-- use-input -->
          <div>
            <q-btn
              v-if="checkPermission($route)?.attrIsCreate"
              size="12px"
              flat
              round
              color="add"
              icon="mdi-plus"
              @click="clickAdd"
            >
              <q-tooltip>เพิ่มข้อมูล</q-tooltip>
            </q-btn>
          </div>
          <q-space />

          <q-input
            class="col-xs-12 col-sm-3 col-md-2"
            standout
            dense
            v-model="filterKeyword"
            ref="filterRef"
            outlined
            debounce="300"
            placeholder="ค้นหา"
          >
            <template v-slot:append>
              <q-icon v-if="filterKeyword == ''" name="search" />
              <q-icon
                v-if="filterKeyword !== ''"
                name="clear"
                class="cursor-pointer"
                @click="resetFilter"
              />
            </template>
          </q-input>

          <q-select
            v-model="stroe.visibleColumns"
            multiple
            outlined
            dense
            options-dense
            :display-value="$q.lang.table.columns"
            emit-value
            map-options
            :options="stroe.columns"
            option-value="name"
            
            style="min-width: 140px"
            class="col-xs-12 col-sm-3 col-md-2"
          >
          </q-select>
        </div>
        <div class="col-12">
          <q-card bordered class="col-12 filter-card q-pa-sm">
            <div class="row col-12 q-col-gutter-sm">
              <div class="col-xs-12 col-sm-3 col-md-4">
                <q-select
                  v-model="OrderType"
                  label="ประเภท"
                  dense
                  emit-value
                  map-options
                  option-label="name"
                  :options="OrderTypeOption"
                  option-value="id"
                  lazy-rules
                  use-input
                  hide-bottom-space
                  :readonly="false"
                  :borderless="false"
                  :outlined="true"
                  :hide-dropdown-icon="false"
                  @update:model-value="searchFilterTable"
                  @filter="(inputValue:any,
                    doneFn:Function) => filterSelector(inputValue, doneFn,'OrderTypeOption'
                    ) "
                >
                  <template v-slot:no-option>
                    <q-item>
                      <q-item-section class="text-grey">
                        ไม่มีข้อมูล
                      </q-item-section>
                    </q-item>
                  </template>
                  <template v-if="OrderType !== ''" v-slot:append>
                    <q-icon
                      name="cancel"
                      @click.stop.prevent="
                        (OrderTypeOption = OrderTypeFilter1),
                          (OrderType = ''),
                          searchFilterTable()
                      "
                      class="cursor-pointer"
                    />
                  </template>
                </q-select>
              </div>
              <div class="col-xs-12 col-sm-3 col-md-3">
                <q-select
                  v-model="OrderStatus"
                  label="สถานะ"
                  dense
                  emit-value
                  map-options
                  option-label="name"
                  :options="OrderStatusOption"
                  option-value="name"
                  lazy-rules
                  use-input
                  hide-bottom-space
                  :readonly="false"
                  :borderless="false"
                  :outlined="true"
                  :hide-dropdown-icon="false"
                  @update:model-value="searchFilterTable"
                  @filter="(inputValue:any,
                      doneFn:Function) => filterSelector(inputValue, doneFn,'OrderStatusOption'
                      ) "
                >
                  <template v-slot:no-option>
                    <q-item>
                      <q-item-section class="text-grey">
                        ไม่มีข้อมูล
                      </q-item-section>
                    </q-item>
                  </template>
                  <template v-if="OrderStatus !== 'ทั้งหมด'" v-slot:append>
                    <q-icon
                      name="cancel"
                      @click.stop.prevent="
                        (OrderStatusOption = OrderStatusFilter1),
                          (OrderStatus = 'ทั้งหมด'),
                          searchFilterTable()
                      "
                      class="cursor-pointer"
                    />
                  </template>
                </q-select>
              </div>
              <q-space />
              <div><PopupHistory :OrderTypeOption="OrderTypeOption" /></div>
            </div>
          </q-card>
        </div>
        <div class="col-12">
          <TableOrder :filterTable="filterKeyword" />
        </div>
      </div>
    </q-card>
  </div>
</template>

<style lang="scss" scope>
.filter-card {
  background-color: #f1f1f1b0;
}

.toggle-expired-account {
  font-size: 12px;
  font-weight: 400;
  font-size: 15px;
  line-height: 150%;
  color: #35373c;
}

.icon-color {
  color: #4154b3;
}

.custom-header-table {
  max-height: 64vh;

  .q-table tr:nth-child(odd) td {
    background: white;
  }

  .q-table tr:nth-child(even) td {
    background: #f8f8f8;
  }

  .q-table thead tr {
    background: #ecebeb;
  }

  .q-table thead tr th {
    position: sticky;
    z-index: 1;
  }

  /* this will be the loading indicator */
  .q-table thead tr:last-child th {
    /* height of all previous header rows */
    top: 48px;
  }

  .q-table thead tr:first-child th {
    top: 0;
  }
}
</style>
