<script setup lang="ts">
import { ref, useAttrs, onMounted } from "vue";
import type { QTableProps } from "quasar";
import router from "@/router";
import { useCounterMixin } from "@/stores/mixin";
import { useQuasar } from "quasar";
import type { FormProprsalsRound2 } from "@/modules/07_insignia/interface/request/Main";
import config from "@/app.config";
import http from "@/plugins/http";

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

const visibleColumns = ref<string[]>([
  "period_name",
  "period_year",
  "period_start",
  "period_end",
  // "status",
  "statusRoyal",
]); //ค้นหา คอลัมน์ คอลัมน์ที่แสดง

// หัวตาราง
const columns = ref<QTableProps["columns"]>([
  {
    name: "period_name",
    align: "left",
    label: "รอบการเสนอขอพระราชทานเครื่องราชฯ",
    sortable: true,
    field: "period_name",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "period_year",
    align: "left",
    label: "ปีที่เสนอ",
    sortable: true,
    field: "period_year",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "period_start",
    align: "left",
    label: "วันที่เริ่มต้น",
    sortable: true,
    field: "period_start",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    // sort: (a: string, b: string) =>
    //   a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "period_end",
    align: "left",
    label: "วันที่สิ้นสุด",
    sortable: true,
    field: "period_end",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    // sort: (a: string, b: string) =>
    //   a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "statusRoyal",
    align: "center",
    label: "สถานะราชกิจจานุเบกษา",
    sortable: true,
    field: "statusRoyal",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);

// ข้อมูลตาราง (จำลอง)
const rows = ref<FormProprsalsRound2[]>([]);

onMounted(async () => {
  await fetchData();
});

const fetchData = async () => {
  showLoader();
  await http
    .get(config.API.listRoundInsignia())
    .then((res) => {
      const data = res.data.result;
      rows.value = data.map((e: FormProprsalsRound2) => ({
        period_id: e.period_id,
        period_name: e.period_name,
        period_year: e.period_year + 543,
        period_amount: e.period_amount,
        period_start:
          e.period_start == null ? null : date2Thai(new Date(e.period_start)),
        period_end:
          e.period_end == null ? null : date2Thai(new Date(e.period_end)),
        period_isActive: e.period_isActive,
        period_doc: e.period_doc,
        period_status: e.period_status.result,
      }));
      console.log(rows.value);
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
};

const clickEdit = (col: any) => {
  router.push(`/insignia/round-add/${col.period_id}`);
};

const clickDelete = (id: string) => {
  dialogRemove($q, async () => {
    showLoader();
    await http
      .delete(config.API.RoundInsignia(id))
      .then(() => {
        success($q, "ลบข้อมูลการเสนอขอสำเร็จ");
        fetchData();
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(() => {
        hideLoader();
      });
  });
};

const clickAdd = () => {
  router.push({ name: "roundAdd" });
};

const clickProposals = (file: string) => {
  if (file !== null) {
    window.open(file);
  }
};
const clickListInsignia = async (propsId: string) => {
  dialogConfirm(
    $q,
    async () => {
      await getRequest(propsId);
    },
    "ยืนยันการคำนวณราชชื่อผู้ได้รับเครื่องราช",
    "ต้องการยืนยันการคำนวณราชชื่อผู้ได้รับเครื่องราชนี้หรือไม่ ?"
  );
};
const getRequest = async (id: string) => {
  showLoader();
  await http
    .get(config.API.requestInsignia(id))
    .then(() => {
      success($q, "ยืนยันสำเร็จ");
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(async () => {
      await fetchData();
    });
};
// const downloadFile = (response: any, name: string) => {
//   const link = document.createElement("a");
//   var fileName = name;
//   link.href = response;
//   link.setAttribute("target", "_blank");
//   link.setAttribute("download", fileName);
//   document.body.appendChild(link);
//   link.click();
//   document.body.removeChild(link);
// };

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

const attrs = ref<any>(useAttrs());
const paging = ref<boolean>(true);
const pagination = ref({
  sortBy: "desc",
  descending: false,
  page: 1,
  rowsPerPage: 10,
});
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">
    รายการรอบการเสนอขอพระราชทานเครื่องราชอิสริยาภรณ์
  </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">
        <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="Order"
          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 auto-width />
              <q-th auto-width />
            </q-tr>
          </template>
          <template v-slot:body="props">
            <q-tr :props="props" class="cursor-pointer">
              <q-td
                key="period_name"
                :props="props"
                @click="clickEdit(props.row)"
              >
                {{ props.row.period_name }}
              </q-td>
              <q-td
                key="period_year"
                :props="props"
                @click="clickEdit(props.row)"
              >
                {{ props.row.period_year }}
              </q-td>
              <q-td
                key="period_start"
                :props="props"
                @click="clickEdit(props.row)"
              >
                {{ props.row.period_start }}
              </q-td>
              <q-td
                key="period_end"
                :props="props"
                @click="clickEdit(props.row)"
              >
                {{ props.row.period_end }}
              </q-td>
              <q-td
                key="period_isActive"
                :props="props"
                @click="clickEdit(props.row)"
              >
                <q-icon
                  v-if="props.row.period_isActive == true"
                  name="mdi-close"
                  color="grey-5"
                  class="text-h5"
                  @click="clickEdit(props.row)"
                />
                <q-icon
                  v-else
                  name="mdi-check"
                  color="positive"
                  class="text-h5"
                  @click="clickEdit(props.row)"
                />
              </q-td>
              <q-td key="statusRoyal" :props="props">
                <q-icon
                  v-if="props.row.statusRoyal == 'ยังไม่ได้เสนอ'"
                  name="mdi-timer-sand"
                  color="orange"
                  class="text-h5"
                  @click="clickEdit(props.row)"
                />
                <q-icon
                  v-else
                  name="mdi-check"
                  color="positive"
                  class="text-h5"
                  @click="clickEdit(props.row)"
                />
              </q-td>
              <q-td auto-width>
                <q-btn
                  dense
                  size="12px"
                  flat
                  round
                  color="primary"
                  @click="clickListInsignia(props.row.period_id)"
                  icon="mdi-account-check"
                >
                  <q-tooltip>ผู้ได้รับเครื่องราชฯ</q-tooltip>
                </q-btn>
              </q-td>
              <q-td auto-width>
                <q-btn
                  dense
                  type="a"
                  size="12px"
                  flat
                  target="_blank"
                  round
                  color="light-blue-8"
                  icon="mdi-file-download"
                  :href="props.row.period_doc"
                >
                  <!-- @click="
                downloadFile(props.row.period_doc, props.row.period_name)
              " -->

                  <q-tooltip>ดาวน์โหลดเอกสารประกอบ </q-tooltip>
                </q-btn>
              </q-td>
              <q-td auto-width>
                <q-btn
                  dense
                  size="12px"
                  flat
                  round
                  color="red"
                  @click="clickDelete(props.row.period_id)"
                  icon="mdi-delete"
                >
                  <q-tooltip>ลบข้อมูล</q-tooltip>
                </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>
</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>
