<script setup lang="ts">
import { ref, onMounted, watch, useAttrs } from "vue";
import http from "@/plugins/http";
import config from "@/app.config";
import router from "@/router";
import { useQuasar } from "quasar";

/** impotrType */
import type { OptionDataYear } from "@/modules/07_insignia/interface/index/Main";
import type { QTableProps, QInput } from "quasar";

/** impotrComponents */
import DialogForm from "@/modules/07_insignia/components/4_Allocate/DialogForm.vue";
import DialogEdit from "@/modules/07_insignia/components/4_Allocate/DialogEdit.vue";

/** impotrStores */
import { useCounterMixin } from "@/stores/mixin";
import { useAllocateDataStore } from "@/modules/07_insignia/storeAllocate";
const DataStore = useAllocateDataStore();
const mixin = useCounterMixin();
const { showLoader, hideLoader, messageError, dialogRemove, success } = mixin;

const $q = useQuasar();
const attrs = ref<any>(useAttrs());

const tab = ref<string>("");
const selectRound = ref<string>();
const selectRoundOption = ref<OptionDataYear[]>([]);
const modal = ref<boolean>(false);
const action = ref<string>("");
const roundYear = ref<number>();
const insigniaOp = ref<any>([]);
const filterInsigniaOp = ref<any>({ insigniaOp: [] });
const loadView = ref<boolean>(false);
const pagination = ref({
  sortBy: "desc",
  descending: false,
  page: 1,
  rowsPerPage: 10,
});

/** ข้อมูล Table*/
const visibleColumns = ref<string[]>([
  "no",
  "insignia",
  "total",
  "allocate",
  "remain",
]);
const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: false,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },

  {
    name: "insignia",
    align: "left",
    label: "เครื่องราชอิสริยาภรณ์",
    sortable: true,
    field: "insignia",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "total",
    align: "left",
    label: "จำนวนทั้งหมด",
    sortable: true,
    field: "total",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "allocate",
    align: "left",
    label: "จัดสรรแล้ว",
    sortable: true,
    field: "allocate",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "remain",
    align: "left",
    label: "คงเหลือ",
    sortable: true,
    field: "remain",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);
const filterRef = ref<QInput>();
const filter = ref<string>("");
const rowData = ref<any>([]);

/** function เรียกรอบการเสนอขอ*/
async function fecthRound() {
  await http
    .get(config.API.noteround())
    .then(async (res) => {
      let data = res.data.result;
      if (data.length !== 0) {
        selectRoundOption.value = data.map((e: any) => ({
          id: e.id,
          name: "รอบการเสนอขอพระราชทานเครื่องราชฯ ปี" + "  " + (e.year + 543),
          year: e.year,
        }));
        if (DataStore.roundId && DataStore.roundYear) {
          selectRound.value = DataStore.roundId;
          roundYear.value = DataStore.roundYear;
        } else {
          selectRound.value = data[0].id;
          roundYear.value = data[0].year;
        }
        if (selectRound.value) {
          DataStore.roundId = selectRound.value;
        }
        if (roundYear.value) {
          await fecthInsigniaType();
        }
      }
    })
    .catch((err) => {
      messageError($q, err);
    });
}

/** function เรียกประเภทเครื่องราช*/
async function fecthInsignia() {
  await http
    .get(config.API.insignia)
    .then((res) => {
      let data = res.data.result;
      DataStore.fetchDatainsignia(data);
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(async () => {
      insigniaOp.value = await DataStore.insigniaOp.filter(
        (x: any) => x.type == tab.value || x.type === ""
      );
    });
}

/** function เรียก Tab*/
const fecthInsigniaType = async () => {
  await http(config.API.insigniaType)
    .then((res) => {
      let data = res.data.result;
      DataStore.fetchDatainsigniaType(data);
      if (DataStore.mainTab) {
        tab.value = DataStore.mainTab;
      } else tab.value = DataStore.insigniaType[0].name;
      loadView.value = true;
      fecthInsignia();
    })
    .catch((err) => {
      messageError($q, err);
    });
};

/** function เลือกรอบการเสนขอ*/
async function selectorRound(round: string | undefined) {
  selectRound.value = round;
  if (selectRound.value) {
    DataStore.roundId = selectRound.value;
  }
  const yearFilter = selectRoundOption.value.find((x: any) => x.id == round); // หาปีของรอบการเสนอขอ
  roundYear.value = yearFilter?.year;
  DataStore.roundYear = roundYear.value;
  await fecthlistInsignia();
}

/** function เรียกรายการเครืองราชฯ */
async function fecthlistInsignia() {
  DataStore.mainTab = tab.value;
  showLoader();
  await http
    .get(config.API.insigniaManageType(tab.value, Number(roundYear.value)))
    .then((res) => {
      let data = res.data.result;
      DataStore.listinsignia(data);
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * function reDirectToPage หน่วยงานจัดสรรเครื่องราชอิสริยาภรณ์
 * @param id  จัดสรรเครื่องราชอิสริยาภรณ์
 * @param name ชื่อเครื่องราช
 */
function redirectToPage(id: string, name: string) {
  DataStore.insigniaName = name;
  router.push(`/insignia/allocate/org/${id}`);
}

/** ตัวแปร popup*/
const modalEdit = ref<boolean>(false);
const actionType = ref<string>("");
/** function closePopup*/
function close() {
  modal.value = false;
  modalEdit.value = false;
}

/** function openPopup การเพิ่มการจัดสรรเครื่องราชฯ*/
const addData = () => {
  modal.value = true;
  action.value = "addData";
};

/** function openPopup การแกไขการจัดสรรเครื่องราชฯ*/
const clickEditrow = (data: any) => {
  rowData.value = data;
  modalEdit.value = true;
  actionType.value = "insignia";
};
// บันทึกการเพิ่มการจัดสรรเครื่องราชฯ
const save = async (insigniaId: string, total: string) => {
  showLoader();
  await http
    .post(config.API.insigniaManageAdd(), {
      insignia: insigniaId,
      year: `${roundYear.value}`,
      total: total,
    })
    .then(async () => {
      success($q, "บันทึกข้อมูลสำเร็จ");
      await fecthlistInsignia();
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
      close();
    });
};

//
/**
 * function บัททึกการแก้ไขการจัดสรรเครื่องราชฯ
 * @param id  รอบการเสนอ
 * @param insigniaId การจัดสรรเครื่องราชฯ
 * @param total จำนวน
 * @param year ปี
 */
async function saveEdit(
  id: string,
  insigniaId: string,
  total: Number,
  year: Number
) {
  showLoader();
  let body = {
    insignia: insigniaId,
    year: year,
    total: Number(total),
  };
  await http
    .put(config.API.insigniaManageById(id), body)
    .then(async () => {
      success($q, "แก้ไขข้อมูลสำเร็จ");
      await fecthlistInsignia();
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
      close();
    });
}

/**
 * function  ลบการจัดสรรเครื่องราชฯ
 * @param insigniaId  การจัดสรรเครื่องราชฯ
 */
async function clickDelete(insigniaId: string) {
  dialogRemove($q, async () => {
    showLoader();
    await http
      .delete(config.API.insigniaManageById(insigniaId))
      .then(async () => {
        success($q, "ลบข้อมูลสำเร็จ");
        await fecthlistInsignia();
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

function resetFilter() {
  // reset ค่าที่ค้นหาเมื่อกดปุ่ม X ในกล่องค้นหา
  filter.value = "";
  filterRef.value!.focus();
}

/**
 * function ค้นหาข้อมูลใน option
 * @param val คำค้นหา
 * @param update function
 * @param name ชื่อ Selec
 */
function filterSelector(val: any, update: Function, name: any) {
  update(() => {
    const needle = val.toLowerCase();
    if (name === "filterInsigniaOp") {
      DataStore.insignia = undefined as any;
      filterInsigniaOp.value = insigniaOp.value.filter(
        (v: any) => v.name.toLowerCase().indexOf(needle) > -1
      );
    }
  });
}

/**
 *  function เคลียร์  filter
 * @param name ชื่อ filter
 */
const clearInsigniaFilters = (name: string) => {
  console.log(insigniaOp.value);
  if (name === "filterInsigniaOp") {
    DataStore.insignia = "";
    filterInsigniaOp.value = insigniaOp.value;
  }
};

/** function callback ทำงานเมื่อ Tab มีการเปลี่ยน*/
watch(tab, () => {
  insigniaOp.value = DataStore.insigniaOp.filter(
    (x: any) => x.type == tab.value || x.type === ""
  );
  let a = insigniaOp.value.find((e: any) => e.id == DataStore.insignia);
  if (!a) {
    DataStore.insignia = "";
  }
  filterInsigniaOp.value = insigniaOp.value;
  fecthlistInsignia();
});

/** Hook*/
onMounted(async () => {
  await fecthRound();
});
</script>

<template>
  <div class="toptitle text-dark col-12 row items-center">
    จัดสรรเครื่องราชอิสริยาภรณ์
  </div>
  <q-card
    flat
    bordered
    class="col-12 q-my-md q-mt-sm rounded-borders"
    v-if="loadView"
  >
    <div class="bg-grey-1 col-12 row items-center">
      <div class="q-pl-md q-pr-sm text-weight-medium text-grey-7">รอบ</div>
      <q-select
        hide-bottom-space
        borderless
        dense
        lazy-rules
        emit-value
        map-options
        options-dense
        option-label="name"
        option-value="id"
        v-model="selectRound"
        :options="selectRoundOption"
        use-input
        input-debounce="0"
        input-class="text-bold text-grey"
        @update:model-value="selectorRound(selectRound)"
      >
        <template v-slot:no-option>
          <q-item>
            <q-item-section class="text-grey"> ไม่มีข้อมูล </q-item-section>
          </q-item>
        </template>
      </q-select>
    </div>
    <q-separator />
    <q-tabs
      dense
      v-model="tab"
      align="left"
      class="bg-white text-grey"
      active-color="primary"
      indicator-color="primary"
    >
      <div v-for="item in DataStore.insigniaType">
        <q-tab :name="item.name" :label="item.label" />
      </div>
    </q-tabs>

    <q-separator />
    <q-tab-panels v-model="tab" animated>
      <q-tab-panel
        v-for="item in DataStore.insigniaType"
        :key="item.name"
        :name="item.name"
        class="q-pa-none"
      >
        <div class="q-pa-md">
          <div class="row col-12 q-pb-sm q-col-gutter-x-xs">
            <div>
              <q-select
                v-model="DataStore.insignia"
                dense
                outlined
                lazy-rules
                hide-bottom-space
                :label="`${'เครื่องราชฯ'}`"
                emit-value
                map-options
                option-label="name"
                :options="filterInsigniaOp"
                option-value="id"
                :readonly="false"
                use-input
                :borderless="false"
                style="min-width: 350px"
                @update:model-value="
                  DataStore.selectInsignia(DataStore.insignia)
                "
                @filter="(inputValue:any,
                      doneFn:Function) => filterSelector(inputValue, doneFn,'filterInsigniaOp'
                      ) "
              >
                <template
                  v-if="
                    DataStore.insignia !== undefined &&
                    DataStore.insignia !== ''
                  "
                  v-slot:append
                >
                  <q-icon
                    name="cancel"
                    @click.stop.prevent="
                      clearInsigniaFilters('filterInsigniaOp'),
                        DataStore.selectInsignia(DataStore.insignia)
                    "
                    class="cursor-pointer"
                  />
                </template>
                <template v-slot:no-option>
                  <q-item>
                    <q-item-section class="text-grey">
                      ไม่มีข้อมูล
                    </q-item-section>
                  </q-item>
                </template>
              </q-select>
            </div>

            <div>
              <q-btn
                @click="addData()"
                size="12px"
                flat
                round
                color="add"
                icon="mdi-plus"
              >
                <q-tooltip>เพิ่ม</q-tooltip>
              </q-btn>
            </div>
            <q-space />
            <div class="items-center" style="display: flex">
              <!-- ค้นหาข้อความใน table -->
              <q-input
                standout
                dense
                v-model="filter"
                ref="filterRef"
                outlined
                debounce="300"
                placeholder="ค้นหา"
                style="max-width: 200px"
                class="q-ml-sm"
              >
                <template v-slot:append>
                  <q-icon v-if="filter == ''" name="search" />
                  <q-icon
                    v-if="filter !== ''"
                    name="clear"
                    class="cursor-pointer"
                    @click="resetFilter"
                  />
                </template>
              </q-input>
              <!-- แสดงคอลัมน์ใน table -->
              <q-select
                v-model="visibleColumns"
                :display-value="$q.lang.table.columns"
                multiple
                outlined
                dense
                :options="columns"
                options-dense
                option-value="name"
                map-options
                emit-value
                style="min-width: 150px"
                class="gt-xs q-ml-sm"
              />
            </div>
          </div>
          <d-table
            ref="table"
            :columns="columns"
            :rows="DataStore.rows"
            :filter="filter"
            row-key="id"
            flat
            bordered
            :paging="true"
            dense
            class="custom-header-table"
            v-bind="attrs"
            :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-tr>
            </template>
            <template v-slot:body="props">
              <q-tr :props="props" class="cursor-pointer">
                <q-td
                  key="no"
                  :props="props"
                  @click="redirectToPage(props.row.id, props.row.insignia)"
                >
                  {{ props.rowIndex + 1 }}
                </q-td>
                <q-td
                  key="year"
                  :props="props"
                  @click="redirectToPage(props.row.id, props.row.insignia)"
                >
                  {{ props.row.year }}
                </q-td>
                <q-td
                  key="insignia"
                  :props="props"
                  @click="redirectToPage(props.row.id, props.row.insignia)"
                >
                  {{ props.row.insignia }}
                </q-td>
                <q-td
                  key="total"
                  :props="props"
                  @click="redirectToPage(props.row.id, props.row.insignia)"
                >
                  {{ props.row.total }}
                </q-td>
                <q-td
                  key="allocate"
                  :props="props"
                  @click="redirectToPage(props.row.id, props.row.insignia)"
                >
                  {{ props.row.allocate }}
                </q-td>
                <q-td
                  key="remain"
                  :props="props"
                  @click="redirectToPage(props.row.id, props.row.insignia)"
                >
                  {{ props.row.remain }}
                </q-td>
                <q-td auto-width>
                  <q-btn
                    icon="mdi-dots-vertical"
                    size="12px"
                    color="grey-7"
                    flat
                    round
                    dense
                    @click.stop
                  >
                    <q-menu
                      transition-show="jump-down"
                      transition-hide="jump-up"
                    >
                      <q-list dense style="min-width: auto">
                        <q-item clickable @click.stop="clickEditrow(props.row)">
                          <q-item-section
                            style="min-width: 0px"
                            avatar
                            class="q-py-sm"
                          >
                            <q-tooltip>แก้ไข</q-tooltip>
                            <q-icon
                              color="primary"
                              size="xs"
                              name="mdi-pencil"
                            />
                          </q-item-section>
                          <q-item-section>แก้ไข</q-item-section>
                        </q-item>
                        <q-item
                          clickable
                          v-close-popup
                          @click.stop="clickDelete(props.row.id)"
                        >
                          <q-item-section
                            style="min-width: 0px"
                            avatar
                            class="q-py-sm"
                          >
                            <q-tooltip>ลบ</q-tooltip>
                            <q-icon color="red" size="xs" name="mdi-delete" />
                          </q-item-section>
                          <q-item-section>ลบ</q-item-section>
                        </q-item>
                      </q-list>
                    </q-menu>
                  </q-btn>
                </q-td>
              </q-tr>
            </template>
          </d-table>
        </div>
      </q-tab-panel>
    </q-tab-panels>
  </q-card>
  <q-card v-else>
    <div class="q-pa-md q-gutter-sm">
      <q-banner inline-actions rounded class="bg-grey-1 text-center">
        ไม่มีข้อมูลรอบการเสนอขอพระราชทานเครื่องราชอิสริยาภรณ์
      </q-banner>
    </div>
  </q-card>

  <DialogForm
    :modal="modal"
    :save="save"
    :close="close"
    :insignia-list="insigniaOp"
  />

  <DialogEdit
    :modal="modalEdit"
    :save="saveEdit"
    :close="close"
    :insigniadata="rowData"
    :actionType="actionType"
  />
</template>
<style lang="scss" scoped></style>
