<script setup lang="ts">
import { onMounted, ref, useAttrs } from "vue";
import type { QTableProps } from "quasar";
import router from "@/router";
import { useQuasar } from "quasar";
import cardTop from "@/modules/07_insignia/components/2_Manage/StatCard.vue";
import DialogForm from "@/modules/07_insignia/components/4_Allocate/DialogForm.vue";
import { useRoute } from "vue-router";
import http from "@/plugins/http";
import config from "@/app.config";
import { useCounterMixin } from "@/stores/mixin";
import { useAllocateDataStore } from "@/modules/07_insignia/storeAllocate";
import DialogEdit from "@/modules/07_insignia/components/4_Allocate/DialogEdit.vue";

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

const name = ref<string>("");
const $q = useQuasar(); //ใช้ noti quasar
const route = useRoute();
const id = ref<string>(route.params.id.toString());
const modal = ref<boolean>(false);
const orgList = ref<any>([]);
const pagination = ref({
  sortBy: "desc",
  descending: false,
  page: 1,
  rowsPerPage: 10,
});
const stat = ref<any>({
  total: 0,
  allocate: 0,
  remain: 0,
});

onMounted(async () => {
  fecthDashboard();
  fecthListData();
  name.value = DataStore.insigniaName;

  fetchOrgList();
});

const fecthDashboard = async () => {
  showLoader();
  await http
    .get(config.API.insigniaManageOrgDashboard(id.value))
    .then((res) => {
      stat.value = {
        total: res.data.result.total,
        allocate: res.data.result.allocate,
        remain: res.data.result.remain,
      };
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => hideLoader());
};

const fecthListData = async () => {
  showLoader();
  await http
    .get(config.API.insigniaManageOrg(id.value))
    .then((res) => {
      // console.log("res===>", res)
      rows.value = res.data.result.map((e: any) => ({
        id: e.id,
        organization: e.organizationOrganization,
        total: e.total,
        allocate: e.allocate,
        remain: e.remain,
      }));
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => hideLoader());
};

const fetchOrgList = async () => {
  showLoader();
  await http
    .get(config.API.typeOc())
    .then(async (response: any) => {
      orgList.value = response.data.result.map((e: any) => ({
        id: e.organizationId,
        name: e.organizationName,
      }));
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
};

const backHistory = () => {
  router.push(`/insignia/allocate`);
};

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

const save = async (organizationId: string, total: string) => {
  showLoader();
  await http
    .post(config.API.insigniaManageOrgAdd(), {
      organizationOrganizationId: organizationId,
      insigniaManageId: id.value,
      total: total,
    })
    .then((res) => {
      fecthListData();
      fecthDashboard();
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
      close();
    });
};
const saveEdit = async (organizationId: string, amount: number) => {
  showLoader();
  await http
    .put(config.API.insigniaManageOrg(organizationId), { total: Number(amount) })
    .then(async () => {
      success($q, "แก้ไขมูลสำเร็จ");
      await fecthDashboard();
      await fecthListData();
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
      close();
    });
};
const rowData = ref<any>([]);
const modalEdit = ref<boolean>(false);
const clickEditrow = (data: any) => {
  rowData.value = data;
  modalEdit.value = true;
};

const clickDelete = async (insigniaId: string) => {
  dialogRemove($q, async () => {
    showLoader();
    await http
      .delete(config.API.insigniaManageOrg(insigniaId))
      .then(async () => {
        success($q, "ลบข้อมูลสำเร็จ");
        await fecthDashboard();
        await fecthListData();
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      });
  });
};

const visibleColumns = ref<string[]>([
  "no",
  "organization",
  "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: "organization",
    align: "left",
    label: "หน่วยงาน",
    sortable: true,
    field: "organization",
    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<any[]>([]);

const clickAdd = () => {
  modal.value = true;
};

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

const filterKeyword2 = ref<string>("");
const filterRef2 = ref<any>(null);
const resetFilter2 = () => {
  filterKeyword2.value = "";
  filterRef2.value.focus();
};

const attrs = ref<any>(useAttrs());

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;
};
</script>

<template>
  <div class="toptitle text-dark col-12 row items-center">
    <q-btn
      icon="mdi-arrow-left"
      unelevated
      round
      dense
      flat
      color="primary"
      class="q-mr-sm"
      @click="backHistory"
    />
    หน่วยงานจัดสรรเครื่องราชอิสริยาภรณ์ {{ name }}
  </div>
  <q-card bordered class="q-py-sm row col-12">
    <div class="col-12 row bg-white">
      <div class="fit q-px-md q-py-sm">
        <div class="row col-12 q-col-gutter-md fit">
          <cardTop
            :amount="stat.total"
            label="จำนวนเครื่องราช ฯ ทั้งหมด"
            color="#016987"
          />
          <cardTop
            :amount="stat.allocate"
            label="จำนวนเครื่องราช ฯ ที่จัดสรรให้หน่วยงานแล้ว"
            color="#02A998"
          />
          <cardTop
            :amount="stat.remain"
            label="จำนวนเครื่องราช ฯ คงเหลือ"
            color="#2EA0FF"
          />
        </div>
      </div>
    </div>
  </q-card>
  <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">
        <div>
          <q-btn
            @click="clickAdd()"
            size="12px"
            flat
            round
            color="add"
            icon="mdi-plus"
          >
            <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="visibleColumns"
          multiple
          outlined
          dense
          options-dense
          :display-value="$q.lang.table.columns"
          emit-value
          map-options
          :options="columns"
          option-value="name"
          options-cover
          style="min-width: 150px"
          class="col-xs-12 col-sm-3 col-md-2"
        />
      </div>
      <div class="col-12">
        <q-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-th auto-width></q-th>
            </q-tr>
          </template>
          <template v-slot:body="props">
            <q-tr :props="props" class="cursor-pointer">
              <q-td key="no" :props="props">
                {{ props.rowIndex + 1 }}
              </q-td>
              <q-td key="organization" :props="props">
                <!-- @click="redirectToPage(props.row.id)" -->
                {{ props.row.organization }}
              </q-td>
              <q-td key="total" :props="props">
                <!-- @click="redirectToPage(props.row.id)" -->
                {{ props.row.total }}
              </q-td>
              <q-td key="allocate" :props="props">
                <!-- @click="redirectToPage(props.row.id)" -->
                {{ props.row.allocate }}
              </q-td>
              <q-td key="remain" :props="props">
                <!-- @click="redirectToPage(props.row.id)" -->
                {{ 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>
        </q-table>
      </div>
    </div>
  </q-card>

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

  <DialogEdit
    :modal="modalEdit"
    :save="saveEdit"
    :close="close"
    :insigniadata="rowData"
  />
</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>
