<template>
  <div class="toptitle text-dark col-12 row items-center">
    ประกาศเกษียณอายุราชการ
  </div>
  <q-card flat bordered class="col-12 q-mt-sm">
    <div class="row col-12">
      <q-tabs
        v-model="tab"
        dense
        class="text-grey"
        active-color="primary"
        active-class="bg-teal-1"
        indicator-color="primary"
        align="left"
      >
        <q-tab name="officer" label="ขรก.กทม.สามัญ" @click="type = 'officer'" />
        <q-tab
          name="employee"
          label="ลูกจ้างประจำ"
          @click="type = 'employee'"
        />
      </q-tabs>
    </div>
    <q-separator />
    <div class="col-12 row q-pa-md">
      <div class="row col-12">
        <div class="row col-12 q-col-gutter-sm">
          <q-select
            v-model="fiscalyear"
            label="ปีงบประมาณ"
            dense
            emit-value
            map-options
            :options="yearOptions"
            option-value="id"
            option-label="name"
            lazy-rules
            hide-bottom-space
            :readonly="false"
            :borderless="false"
            :outlined="true"
            :hide-dropdown-icon="false"
            style="min-width: 150px"
          />
          <div>
            <q-btn
              @click="clickAdd()"
              size="12px"
              flat
              round
              color="add"
              icon="mdi-plus"
              :disable="checkjson == true"
            >
              <q-tooltip>เพิ่ม</q-tooltip>
            </q-btn>
            <!-- <q-menu>
              <q-list style="min-width: 100px">
                <q-item clickable @click="clickAdd">
                  <q-item-section>ขรก.กทม.สามัญ</q-item-section>
                </q-item>
                <q-item clickable @click="clickAdd">
                  <q-item-section>ลูกจ้างประจำ</q-item-section>
                </q-item>
              </q-list>
            </q-menu> -->
          </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-pt-sm">
          <q-table
            ref="table"
            :columns="columns"
            :rows="rows"
            :filter="filterKeyword"
            row-key="name"
            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="nextPage(props.row)"
              >
                <q-td key="no" :props="props">
                  {{ props.rowIndex + 1 }}
                </q-td>
                <q-td key="Date" :props="props">
                  {{ props.row.Date }}
                </q-td>
                <q-td key="retireNumber" :props="props">
                  {{ props.row.total }}
                </q-td>
                <q-td key="typeReport" :props="props">
                  {{ props.row.typeReport }}
                </q-td>
                <!-- <q-td auto-width>
                  <q-btn
                    dense
                    size="12px"
                    flat
                    round
                    color="red"
                    @click="clickDelete(props.row.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="primary"
                :max="scope.pagesNumber"
                :max-pages="5"
                size="sm"
                boundary-links
                direction-links
              ></q-pagination>
            </template>
          </q-table>
        </div>
      </div>
    </div>
  </q-card>

  <q-dialog v-model="modal">
    <q-card style="width: 450px; max-width: 80vw">
      <q-card-section>
        <div class="text-h6">เพิ่มประกาศ</div>
      </q-card-section>

      <q-card-section class="q-pt-none">
        เลือกประกาศที่ต้องการเพิ่มข้อมูล
      </q-card-section>
      <q-separator />
      <div class="q-pa-md">
        <q-list>
          <q-item class="q-item-custom">
            <q-item-section avatar class="q-item-custom">
              <q-radio
                v-model="radio"
                val="ADD"
                color="teal"
                @click="action = ''"
              />
            </q-item-section>
            <q-item-section>
              <q-item-label>ประกาศเพิ่มผู้เกษียณ</q-item-label>
            </q-item-section>
          </q-item>

          <q-item class="q-item-custom">
            <q-item-section avatar class="q-item-custom">
              <q-radio
                v-model="radio"
                val="EDIT"
                color="teal"
                @click="action = ''"
              />
            </q-item-section>
            <q-item-section>
              <q-item-label>ประกาศแก้ไขข้อมูลผู้เกษียณ</q-item-label>
              <q-item-label v-if="radio === 'EDIT'">
                <q-select
                  dense
                  v-model="action"
                  :options="actionOption"
                  label="เลือกรอบ"
                  option-label="round"
                  option-value="id"
                  emit-value
                  map-options
                  :rules="[(val) => !!val || 'กรุณาเลือกรอบ']"
                />
              </q-item-label>
            </q-item-section>
          </q-item>

          <q-item class="q-item-custom">
            <q-item-section avatar class="q-item-custom">
              <q-radio
                v-model="radio"
                val="REMOVE"
                color="teal"
                @click="action = ''"
              />
            </q-item-section>
            <q-item-section>
              <q-item-label>ประกาศยกเลิกผู้เกษียณ</q-item-label>
              <q-item-label v-if="radio === 'REMOVE'">
                <q-select
                  dense
                  v-model="action"
                  :options="actionOption"
                  label="เลือกรอบ"
                  option-label="round"
                  option-value="id"
                  emit-value
                  map-options
                  :rules="[(val) => !!val || 'กรุณาเลือกรอบ']"
              /></q-item-label>
            </q-item-section>
          </q-item>
        </q-list>
      </div>
      <q-separator />

      <q-card-actions align="right" class="bg-white text-teal">
        <q-btn flat label="ยกเลิก" color="red" v-close-popup />
        <q-btn
          flat
          label="ตกลง"
          @click="clickSelect(action)"
          :disable="radio === '' || (action === '' && radio !== 'ADD')"
        />
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

<script setup lang="ts">
import { onMounted, ref, useAttrs, reactive, watch, computed } from "vue";
import type { QTableProps } from "quasar";
import type {
  FormMainProbation,
  FormMainProbation2,
} from "@/modules/05_placement/interface/request/Main";
import { useQuasar } from "quasar";
import { useRouter } from "vue-router";
import http from "@/plugins/http";
import config from "@/app.config";
import { useCounterMixin } from "@/stores/mixin";
import type { resMain } from "@/modules/06_retirement/interface/response/Main";

const mixin = useCounterMixin();
const { messageError, date2Thai, showLoader, hideLoader, dialogConfirm } =
  mixin;
const router = useRouter();
const $q = useQuasar(); //ใช้ noti quasar
const modal = ref<boolean>(false);
const radio = ref<string>("");
const pagination = ref({
  sortBy: "desc",
  descending: false,
  page: 1,
  rowsPerPage: 10,
});

const actionOption = ref<resMain[]>([]);
const action = ref<string>("");

const type = ref<string>("officer");
const visibleColumns = ref<string[]>([
  "no",
  "Date",
  "retireNumber",
  "typeReport",
]); //ค้นหา คอลัมน์ คอลัมน์ที่แสดง

// หัวตาราง
const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "Date",
    align: "left",
    label: "วันที่สร้าง",
    field: "Date",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "retireNumber",
    align: "left",
    label: "จำนวนผู้เกษียณ",
    field: "retireNumber",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "typeReport",
    align: "left",
    label: "ประเภทประกาศ",
    field: "typeReport",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);

// ข้อมูลตาราง (จำลอง)
const currentYear = new Date().getFullYear();
const rows = ref<resMain[]>([]);
const tab = ref<any>("officer");
const visibleColumns2 = ref<string[]>(["no", "name", "retireNumber"]);
const yearOptions = reactive<any[]>([]);
const filteryear = () => {
  // console.log(yearOptions);
  yearOptions.push({ id: currentYear, name: currentYear + 543 });
  // console.log(yearOptions[0].id);
  fiscalyear.value = yearOptions[0].id;
  fetchRetirement(type.value, currentYear);
};
const fetchRetirement = async (type: string, year: any) => {
  radio.value = "";
  showLoader();
  await http
    .get(config.API.retirement(type, year))
    .then((res) => {
      // console.log(res);
      rows.value = [];
      let data = res.data.result;
      rows.value = data.map((items: any) => ({
        id: items.id,
        Date: date2Thai(items.createdAt),
        year: items.year,
        retireNumber: items.round,
        total: items.total,
        round: items.round,
        typeReport: typeReportChangeName(items.typeReport),
        json: items.json,
        document: items.document,
      }));
      actionOption.value = rows.value;
      rows.value.sort((a, b) => a.round - b.round);
      checkststus(rows.value);
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
};
onMounted(() => {
  filteryear();
});
// หัวตาราง2
const columns2 = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: true,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "name",
    align: "left",
    label: "วันที่สร้าง",
    sortable: true,
    field: "name",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "retireNumber",
    align: "left",
    label: "จำนวนผู้เกษียณ",
    sortable: true,
    field: "total",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);

// ข้อมูลตาราง (จำลอง)
const rows2 = ref<FormMainProbation2[]>([
  {
    no: "1",
    name: "นายใจดี ยอดใจ ",
    position: "นักวิชาการพัสดุ",
    level: "ปฏิบัติการ",
    institution: "กลุ่มงานโครงสร้างและอัตรากำลัง ๒",
  },
  {
    no: "2",
    name: "นายจักกริน บัณฑิต",
    position: "นักวิชาการพัสดุ",
    level: "ปฏิบัติการ",
    institution: "กลุ่มงานโครงสร้างและอัตรากำลัง ๒",
  },
  {
    no: "3",
    name: "นางสาวกัณฐิมา กาฬสินธุ์",
    position: "นักจัดการงานทั่วไป",
    level: "ปฏิบัติการ",
    institution: "กลุ่มงานช่วยนักบริหาร",
  },
  {
    no: "4",
    name: "นางสาวเมขลา กระจ่างมนตรี",
    position: "นักจัดการงานทั่วไป",
    level: "ปฏิบัติการ",
    institution: "กลุ่มงานช่วยนักบริหาร",
  },
  {
    no: "5",
    name: "นางสาวฐิติรัตน์ พงษ์ศิริ",
    position: "นักจัดการงานทั่วไป",
    level: "ปฏิบัติการ",
    institution: "กลุ่มงานช่วยนักบริหาร",
  },
]);

// const clickDelete = (id: string) => {
//   $q.dialog({
//     title: "ยืนยันการลบข้อมูล",
//     message: "ต้องการลบข้อมูลนี้ใช่หรือไม่?",
//     cancel: {
//       flat: true,
//       color: "negative",
//     },
//     persistent: true,
//   })
//     .onOk(async () => {})
//     .onCancel(() => {})
//     .onDismiss(() => {});
// };

const clickAdd = () => {
  console.log(rows.value.length, type.value);
  if (rows.value.length == 0) {
    dialogConfirm(
      $q,
      async () => {
        let data = { type: type.value, year: currentYear };
        await cerateRetirement(data);
      },
      "ยืนยันการเพิ่มข้อมูลประกาศเกษียณ",
      "ต้องการเพิ่มข้อมูลประกาศเกษียณใช่หรือไม่ ?"
    );
  } else {
    modal.value = true;
    action.value = "";
    radio.value = "";
  }
};
const cerateRetirement = async (data: object) => {
  await http
    .post(config.API.createProfile(), data)
    .then((res) => {
      let response = res.data.result;
      let retirementId = response.id;
      router.push(`/retirement/${retirementId}`);
    })
    .catch((e) => {
      messageError($q, e);
    });
};
const clickSelect = async (action: string) => {
  dialogConfirm(
    $q,
    async () => {
      let data = {
        type: type.value,
        year: currentYear,
        retireHistoryId: action,
        option: radio.value,
      };

      await cerateRetirement(data);
    },
    "ยืนยันการแก้ไขข้อมูลประกาศเกษียณ",
    "ต้องการแก้ไขข้อมูลประกาศเกษียณใช่หรือไม่ ?"
  );
};

const checkjson = ref<boolean>();

const checkststus = (data: any) => {
  let jsonfasle = data.find((e: any) => e.document == false);
  // console.log(jsonfasle)

  if (jsonfasle) {
    checkjson.value = true;
  } else checkjson.value = false;
};
const fiscalyear = ref<number>();
// const fiscalyearOP = ref<any>([
//   { id: 1, name: "ทั้งหมด" },
//   { id: 2, name: "2565" },
//   { id: 3, name: "2565" },
// ]);

// ค้นหาในตาราง
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;
};
const nextPage = (prop: any) => {
  // console.log(prop.id);

  router.push(`/retirement/${prop.id}`);
};

watch(type, () => {
  fetchRetirement(type.value, currentYear);
});
const typeReportChangeName = (val: string) => {
  // console.log(val);
  switch (val) {
    case "EDIT":
      return "ประกาศแก้ไขเกษียณ";
    case "ADD":
      return "ประกาศเพิ่มเกษียณ";
    case "REMOVE":
      return "ประกาศยกเลิกเกษียณ";
    default:
      return "ประกาศข้อมูลเกษียณ";
  }
};
</script>

<style lang="scss" scope>
.filter-card {
  background-color: #f1f1f1b0;
}
.q-item-custom {
  padding: 0;
}

.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>
