<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 { useResultDataStore } 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 type { OptionDataYear } from "@/modules/07_insignia/interface/index/Main";
import type { QTableProps, QInput } from "quasar";
import { useQuasar } from "quasar";

const DataStore = useResultDataStore();
const mixin = useCounterMixin();
const {
  showLoader,
  hideLoader,
  messageError,

} = 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>([]);

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

const fecthRound = async () => {
  await http
    .get(config.API.noteround())
    .then((res) => {
      let data = res.data.result;
      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;
      // console.log(roundYear.value);
    })
    .catch((err) => {
      console.log(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)
    })
};

const fecthInsigniaType = async () => {
  await http(config.API.insigniaType)
    .then((res) => {
      // console.log(res);
      let data = res.data.result;
      DataStore.fetchDatainsigniaType(data);
      tab.value = DataStore.insigniaType[0].name;

      fecthlistInsignia()
      fecthInsignia();
    })
    .catch((err) => {
      console.log(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",
  },
]);
const rows = ref<FormProprsalsRound[]>([]);

watch(tab, () => {
  insigniaOp.value = DataStore.insigniaOp.filter((x: any) => x.type == tab.value)
  fecthlistInsignia();
});

const selectorInsignia = () => {
  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 () => {
  showLoader();
  await http
    .get(config.API.insigniaManageType(tab.value, Number(roundYear.value)))
    .then((res) => {
      let data = res.data.result;
      rows.value = [];
      // console.log("dsata===>", data);
      rows.value = data.map((e: any) => ({
        id: e.id,
        insignia: e.insignia,
        insigniaId: e.insigniaId,
        total: e.total,
        allocate: e.allocate,
        remain: e.remain,
        //   status: DataStore.status(e.status),
      }));
    })
    .catch((err) => {
      console.log(err);
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
};


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

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

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

const editData = (data: any) => {
  personId.value = data.id;
  profileType.value = data.profileType;
  action.value = "editData";
  modal.value = true;
};

const save = async (insigniaId: string, total: string) => {
  showLoader()
  await http
    .post(config.API.insigniaManageAdd(), {
      insignia: insigniaId,
      year: `${roundYear.value}`,
      total: total,
    })
    .then((res) => {
      fecthlistInsignia();
    })
    .catch((err) => {
      messageError($q, err)
    }).finally(() => {
      hideLoader();
      close();
    });
};

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">
    <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 />

    <div>
      <div v-for="item in DataStore.insigniaType">
        <div v-if="tab == item.name" 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="selectorInsignia" />
            </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="rows" :filter="filterKeyword" 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-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-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>

        <div v-else-if="tab == item.name" class="q-pa-md">
          <div class="row col-12 q-pb-sm q-col-gutter-x-xs">
            <selector outlined dense lazy-rules v-model="DataStore.insignia" hide-bottom-space :label="`${'เครื่องราชฯ'}`"
              emit-value map-options option-label="name" :options="DataStore.insigniaOp" option-value="id" use-input
              input-debounce="0" style="min-width: 150px" />
            <div>
              <q-btn @click="addData()" size="12px" flat round color="add" icon="mdi-plus">
                <q-tooltip>เพิ่ม</q-tooltip>
              </q-btn>
            </div>
            <div>
              <q-btn flat round color="light-blue" icon="upload">
                <!-- <q-tooltip>อัพโหลดไฟล์</q-tooltip> -->
                <q-menu>
                  <q-list style="min-width: 150px">
                    <q-item clickable v-close-popup>
                      <q-item-section avatar><q-icon color="green-7" name="mdi-file-excel" /></q-item-section>
                      <q-item-section>บันทึกผลการได้รับพระราชทานเครื่องราชอิสริยาภรณ์</q-item-section>
                    </q-item>
                    <q-item clickable v-close-popup>
                      <q-item-section avatar><q-icon color="green-7" name="mdi-file-excel" /></q-item-section>
                      <q-item-section>บันทึกผลการจ่ายใบกำกับ</q-item-section>
                    </q-item>
                  </q-list>
                </q-menu>
              </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 :rows="rows" :columns="columns" :visible-columns="visibleColumns" :filter="filter" row-key="name">
            <template v-slot:body-cell="props">
              <q-td :props="props">
                <div v-if="props.col.name == 'no'">
                  {{ props.rowIndex + 1 }}
                </div>

                <div v-else-if="props.col.name == 'action'">
                  <q-btn dense size="12px" flat round color="primary" @click="editData(props.row)"
                    icon="mdi-pencil-outline">
                    <q-tooltip>แก้ไขข้อมูล</q-tooltip>
                  </q-btn>
                </div>

                <div v-else>
                  {{ props.value }}
                </div>
              </q-td>
            </template>
          </d-table>
        </div>

        <div v-else-if="tab == item.name" class="q-pa-md">
          <div class="row col-12 q-pb-sm q-col-gutter-x-xs">
            <selector outlined dense lazy-rules v-model="DataStore.insignia" hide-bottom-space :label="`${'เครื่องราชฯ'}`"
              emit-value map-options option-label="name" :options="DataStore.insigniaOp" option-value="id" use-input
              input-debounce="0" style="min-width: 150px" />
            <div>
              <q-btn @click="addData()" size="12px" flat round color="add" icon="mdi-plus">
                <q-tooltip>เพิ่ม</q-tooltip>
              </q-btn>
            </div>
            <div>
              <q-btn flat round color="light-blue" icon="upload">
                <!-- <q-tooltip>อัพโหลดไฟล์</q-tooltip> -->
                <q-menu>
                  <q-list style="min-width: 150px">
                    <q-item clickable v-close-popup>
                      <q-item-section avatar><q-icon color="green-7" name="mdi-file-excel" /></q-item-section>
                      <q-item-section>บันทึกผลการได้รับพระราชทานเครื่องราชอิสริยาภรณ์</q-item-section>
                    </q-item>
                    <q-item clickable v-close-popup>
                      <q-item-section avatar><q-icon color="green-7" name="mdi-file-excel" /></q-item-section>
                      <q-item-section>บันทึกผลการจ่ายใบกำกับ</q-item-section>
                    </q-item>
                  </q-list>
                </q-menu>
              </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 :rows="rows" :columns="columns" :visible-columns="visibleColumns" :filter="filter" row-key="name">
            <template v-slot:body-cell="props">
              <q-td :props="props">
                <div v-if="props.col.name == 'no'">
                  {{ props.rowIndex + 1 }}
                </div>

                <div v-else-if="props.col.name == 'action'">
                  <q-btn dense size="12px" flat round color="primary" @click="editData(props.row)"
                    icon="mdi-pencil-outline">
                    <q-tooltip>แก้ไขข้อมูล</q-tooltip>
                  </q-btn>
                </div>

                <div v-else>
                  {{ props.value }}
                </div>
              </q-td>
            </template>
          </d-table>
        </div>
      </div>

    </div>

    <DialogForm :modal="modal" :save="save" :close="close" :insignia-list="insigniaOp" />
  </q-card>
</template>
<style lang="scss" scoped>
.arrow {
  transition: transform 0.5s;
}

.arrow-active {
  transition: transform 0.5s;
  transform: rotate(-90deg);
}

.bg-base {
  background-color: #f3f3f398;
}

.v-enter-active,
.v-leave-active {
  transition: opacity 0.5s ease;
}

.v-enter-from,
.v-leave-to {
  opacity: 0;
}

.flexsave {
  display: flex;
  justify-content: flex-end;
}
</style>
