<script setup lang="ts">
import { ref, onMounted, watch, useAttrs } from "vue";
// import { useRouter } from "vue-router";
import { useCounterMixin } from "@/stores/mixin";
import http from "@/plugins/http";
import config from "@/app.config";
import { useAllocateDataStore } from "@/modules/07_insignia/storeAllocate";
import type { FormProprsalsRound } from "@/modules/07_insignia/interface/request/Main";
import router from "@/router";
import DialogForm from "@/modules/07_insignia/components/4_Allocate/DialogForm.vue";
import DialogEdit from "@/modules/07_insignia/components/4_Allocate/DialogEdit.vue";

import type { OptionDataYear } from "@/modules/07_insignia/interface/index/Main";
import type { QTableProps, QInput } from "quasar";
import { Loading, useQuasar } from "quasar";
import type { load } from "@/router/loader";

const DataStore = useAllocateDataStore();
const mixin = useCounterMixin();
const { showLoader, hideLoader, messageError, dialogRemove, success } = mixin;

const redirectToPage = (id: string, name: string) => {
  DataStore.insigniaName = name;
  router.push(`/insignia/allocate/org/${id}`);
};
const paging = ref<boolean>(true);
const paginationLabel = (start: string, end: string, total: string) => {
  if (paging.value == true) return " " + start + "-" + end + " ใน " + total;
  else return start + "-" + end + " ใน " + total;
};
const pagination = ref({
  sortBy: "desc",
  descending: false,
  page: 1,
  rowsPerPage: 10,
});
const $q = useQuasar();
const tab = ref<string>("");
const attrs = ref<any>(useAttrs());
const selectRound = ref<string>();
const selectRoundOption = ref<OptionDataYear[]>([]);
const modal = ref<boolean>(false);
const action = ref<string>("");
const personId = ref<string>();
const profileType = ref<string>("");
const filterKeyword = ref<string>("");
const roundYear = ref<number>();
const insigniaOp = ref<any>([]);
const loadView = ref<boolean>(false);

onMounted(async () => {
  await fecthRound();
  // await fecthInsigniaType();
});

const fecthRound = async () => {
  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,
        }));
        selectRound.value = data[0].id;
        roundYear.value = data[0].year;
        if (roundYear.value) {
          await fecthInsigniaType();
        }
      }
    })
    .catch((err) => {
      messageError($q, err);
    });
};

const fecthInsignia = async () => {
  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 === ""
      );
    });
};

const fecthInsigniaType = async () => {
  console.log(DataStore.mainTab);

  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);
    });
};

const visibleColumns = ref<string[]>([
  "no",
  "insignia",
  "total",
  "allocate",
  "remain",
]); //ค้นหา คอลัมน์ คอลัมน์ที่แสดง
const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: true,
    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",
  },
]);
watch(tab, () => {
  insigniaOp.value = DataStore.insigniaOp.filter(
    (x: any) => x.type == tab.value || x.type === ""
  );
  DataStore.insignia = "";
  fecthlistInsignia();
});

const selectorRound = (round: string) => {
  selectRound.value = round;
  const yearFilter = selectRoundOption.value.find((x: any) => x.id == round);
  roundYear.value = yearFilter?.year;
};

const fecthlistInsignia = async () => {
  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();
    });
};

const filterRef = ref<QInput>();
const filter = ref<string>("");

const close = () => {
  modal.value = false;
  modalEdit.value = false;
};

const addData = () => {
  modal.value = true;
  action.value = "addData";
};

const modalEdit = ref<boolean>(false);
const rowData = ref<any>([]);
const actionType = ref<string>("");
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();
    });
};
const saveEdit = async (
  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();
    });
};
const clickDelete = async (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();
      });
  });
};

const resetFilter = () => {
  // reset ค่าที่ค้นหาเมื่อกดปุ่ม X ในกล่องค้นหา
  filter.value = "";
  filterRef.value!.focus();
};
</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>
      <selector
        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:emit-value="selectorRound"
      >
      </selector>
    </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="insigniaOp"
                option-value="id"
                :readonly="false"
                :borderless="false"
                style="min-width: 150px"
                @update:model-value="DataStore.selectInsignia"
              />
            </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"
            :pagination-label="paginationLabel"
            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"
                @click="redirectToPage(props.row.id, props.row.insignia)"
              >
                <q-td key="no" :props="props">
                  {{ props.rowIndex + 1 }}
                </q-td>
                <q-td key="year" :props="props">
                  {{ props.row.year }}
                </q-td>
                <q-td key="insignia" :props="props">
                  {{ props.row.insignia }}
                </q-td>
                <q-td key="total" :props="props">
                  {{ props.row.total }}
                </q-td>
                <q-td key="allocate" :props="props">
                  {{ props.row.allocate }}
                </q-td>
                <q-td key="remain" :props="props">
                  {{ 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
                          v-close-popup
                          @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>
            <template v-slot:pagination="scope">
              <q-pagination
                v-model="pagination.page"
                active-color="primary"
                color="dark"
                :max="scope.pagesNumber"
                :max-pages="5"
                size="sm"
                boundary-links
                direction-links
              ></q-pagination>
            </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>
