<script setup lang="ts">
import { ref, onMounted, computed, watch } from "vue";
import AddList from "../ListRetirement/AddList.vue";
import { useCounterMixin } from "@/stores/mixin";
import { useQuasar } from "quasar";
import { useRoute } from "vue-router";
import { useRouter } from "vue-router";
import http from "@/plugins/http";
import config from "@/app.config";

const route = useRoute();
const router = useRouter();
const $q = useQuasar();
const mixin = useCounterMixin();
const { showLoader, hideLoader, messageError, success } = mixin;
// const type_params = route.params.type;
// const year_params = route.params.year;
const retireld_params = route.params.retirementId;
const orderCoverDocs = ref<string>("");
const orderCoverPdf = ref<string>("");
const modalNote = ref<boolean>(false);
const note = ref<string>("");
const retireProfileId = ref<string>("");
const retireld = ref<string>(retireld_params.toString());
const profileId = ref<string>("");
const filter = ref<string>("");
const statusUpload = ref<boolean>();

const columns = ref<any["columns"]>([
  {
    name: "order",
    label: "ลำดับ",
    title: "ลำดับ",
    field: "order",
    align: "left",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  /*  {
     name: "fixname",
     align: "left",
     label: "คำนำหน้านาม",
     title: "คำนำหน้านาม",
     field: "fixname",
     headerStyle: "font-size: 14px",
     style: "font-size: 14px",
   }, */
  {
    name: "name",
    align: "left",
    label: "ชื่อ - นามสกุล",
    title: "ชื่อ - นามสกุล",
    field: "name",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "organizationOrganization",
    align: "left",
    label: "สังกัด",
    title: "สังกัด",
    field: "organizationOrganization",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "positionType",
    align: "left",
    label: "ตำแหน่ง (ประเภท)",
    title: "ตำแหน่ง",
    subtitle: "ประเภท",
    field: "positionType",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "position",
    align: "left",
    label: "ตำแหน่ง (ทางการบริหาร)",
    title: "ตำแหน่ง",
    subtitle: "ทางการบริหาร",
    field: "position",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "positionLavel",
    align: "left",
    label: "ตำแหน่ง (ในสายงาน/ระดับ)",
    title: "ตำแหน่ง",
    subtitle: "ในสายงาน/ระดับ",
    field: "positionLavel",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "positionNumber",
    align: "left",
    label: "ตำแหน่ง (เลขที่) ",
    title: "ตำแหน่ง",
    subtitle: "เลขที่",
    field: "positionNumber",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "govGroup",
    align: "left",
    label: "ส่วนราชการ (ระดับฝ่าย/กลุ่มงาน/ส่วน)",
    title: "ส่วนราชการ",
    subtitle: "ระดับฝ่าย/กลุ่มงาน/ส่วน",
    field: "govGroup",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "govOffice",
    align: "left",
    label: "ส่วนราชการ (ระดับสถาบัน/สำนักงาน/กอง)",
    title: "ส่วนราชการ",
    subtitle: "ระดับสถาบัน/สำนักงาน/กอง",
    field: "govOffice",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "bureau",
    align: "left",
    label: "หน่วยงาน",
    title: "หน่วยงาน",
    field: "bureau",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);
const rows = ref<any>([]);
const visibleColumns = ref<string[]>([
  "order",
  "fixname",
  "name",
  "organizationOrganization",
  "positionType",
  "position",
  "positionLavel",
  "positionNumber",
  "govGroup",
  "govOffice",
  "bureau",
]);

const action = ref<string>("");
const fileUpload = ref<any>(null);
const clickOpenDownloadPDF =() =>{window.open(orderCoverPdf.value);}
const clickOpenDownloadDoc =() =>{window.open(orderCoverDocs.value);}

onMounted(() => {
  retireld.value = retireld_params.toString();
  fecthlistprofile(retireld.value);
  fetchReportCover("pdf", retireld.value);
  fetchReportCover("docx", retireld.value);
});
const round = ref<number>();
const typeReport = ref<string>("");
const statusReport = ref<boolean>();
const dataProfile = ref<Object>([]);
// fecthlist
const fecthlistprofile = async (id: string) => {
  showLoader();
  await http
    .get(config.API.listRetire(id))
    .then((res) => {
      console.log(res);
      dataProfile.value = res.data.result;
      round.value = res.data.result.round;
      statusReport.value = res.data.result.json;
      typeReport.value = res.data.result.typeReport;
      rows.value = res.data.result.profile.map((e: any) => ({
        id: e.id,
        profileId: e.profileId,
        order: e.order,
        fixname: e.prefix,
        name: e.fullName,
        organizationOrganization: e.organizationOrganization,
        positionType: e.positionType,
        position: e.position,
        positionNumber: e.posNoEmployee,
        positionLavel: e.positionEmployeeLevel,
        bureau: e.oc,
        reason: e.reason,
        remove: e.remove,
      }));
      console.log(statusReport.value);
      if (statusReport.value == false) {
        fecthCheck(retireld.value);
      } else statusUpload.value = true;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
};
const fecthCheck = async (id: string) => {
  await http
    .get(config.API.checkfileupload(id))
    .then((res) => {
      statusUpload.value = res.data.result;
    })
    .catch((err) => {
      console.log(err);
    });
};
// DelProfile
const clickDelete = () => {
  $q.dialog({
    title: "ยืนยันการลบข้อมูล",
    message: "ต้องการลบข้อมูลนี้ใช่หรือไม่?",
    cancel: {
      flat: true,
      color: "negative",
    },
    persistent: true,
  })
    .onOk(async () => {
      await http
        .post(config.API.removeProfile(), {
          retireProfileId: retireProfileId.value,
          reason: note.value,
        })
        .then(() => {
          success($q, "ลบข้อมูลสำเร็จ");
        })
        .catch((e) => {
          messageError($q, e);
        })
        .finally(async () => {
          retireld.value = retireld_params.toString();
          await fecthlistprofile(retireld.value);
          modalNote.value = false;
        });
    })
    .onCancel(() => {})
    .onDismiss(() => {});
};
// note
// const fetchReason = async (prop: string) => {
//   await http
//     .get(config.API.reasonId(prop))
//     .then((res: any) => {
//       console.log(res.data.result);
//       note.value = res.data.result.reason;
//       retireProfileId.value = res.data.result.id;
//     })
//     .catch((e: any) => {
//       messageError($q, e);
//     });
// };
const saveNote = () => {
  console.log(retireProfileId.value, note.value);

  $q.dialog({
    title: "ยืนยันการบันทึกข้อมูลข้อมูล",
    message: "ต้องการบันทึกข้อมูลนี้ใช่หรือไม่?",
    cancel: {
      flat: true,
      color: "negative",
    },
    persistent: true,
  })
    .onOk(async () => {
      await http
        .post(config.API.createnote(), {
          retireProfileId: retireProfileId.value,
          reason: note.value,
        })
        .then(() => {
          success($q, "บันทึกข้อมูลสำเร็จ");
        })
        .catch((e) => {
          messageError($q, e);
        })
        .finally(async () => {
          retireld.value = retireld_params.toString();
          fecthlistprofile(retireld.value);
          modalNote.value = false;
        });
    })
    .onCancel(() => {})
    .onDismiss(() => {});
};

const UpdateListId = (retireld: string, pId: string) => {
  profileId.value = pId;
  fecthlistprofile(retireld);
  console.log("profileId", profileId.value);
};
const backHistory = () => {
  window.history.back();
};
const visibleNote = computed(() => {
  if (note.value === "" || note.value === undefined) {
    return true;
  }
});
const uploadFile = async (event: any) => {
  showLoader();
  const selectedFile = event;
  console.log(selectedFile);
  const formdata = new FormData();
  formdata.append("file", selectedFile);
  await http
    .put(config.API.fileRetirement(retireld.value.toString()), formdata)
    .then((res) => {
      success($q, "เพิ่มไฟล์สำเร็จ");
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      fileUpload.value = null;
      fecthlistprofile(retireld.value);
      fecthCheck(retireld.value);
      hideLoader();
    });
};

const fetchReportCover = async (type: string, orderId: string) => {
  showLoader();
  await http
    .get(config.API.reportRetireList(type, orderId))
    .then(async (res) => {
      if (type == "pdf") {
        orderCoverPdf.value = res.data.result;
      } else {
        orderCoverDocs.value = res.data.result;
      }
    })
    .catch((e) => {
      // messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
};

// const classrow = (prop: any) => {
//   if (profileId.value !== "" && prop.profileId === profileId.value) {
//     return "color: #26a69a;";
//   } else return "";
// };
const paging = ref<boolean>(true);
const pagination = ref({
  sortBy: "order",
  descending: false,
  page: 1,
  rowsPerPage: 10,
});
const paginationLabel = (start: number, end: number, total: number) => {
  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"
    />
    รายชื่อผู้เกษียณอายุราชการ
  </div>
  <div>
    <q-card class="col-12 q-pa-md">
      <div class="row col-12 q-pb-sm">
        <div class="row">
          <AddList
            :dataProfile="dataProfile"
            :retireld="retireld"
            :profile-id="profileId"
            :UpdateListId="UpdateListId"
            v-if="
              statusReport === false &&
              (typeReport == 'ADD' || typeReport == '' || typeReport == null) &&
              statusUpload !== true
            "
          />

          <!-- <q-btn flat round style="color: #016987;" icon="save" @click="saveList">
          <q-tooltip>บันทึกข้อมูล</q-tooltip>
        </q-btn> -->
          <q-btn color="primary" flat round icon="download">
            <q-menu>
              <q-list style="min-width: 100px">
                <q-item
                  clickable
                  v-close-popup
                  type="a"
                  @click="clickOpenDownloadPDF"
                  target="_blank"
                >
                  <q-item-section avatar
                    ><q-icon color="red" name="mdi-file-pdf"
                  /></q-item-section>
                  <q-item-section>ไฟล์ .PDF</q-item-section>
                </q-item>
                <q-item
                  clickable
                  v-close-popup
                  type="a"
                  @click="clickOpenDownloadDoc"
                  target="_blank"
                >
                  <q-item-section avatar
                    ><q-icon color="blue" name="mdi-file-word"
                  /></q-item-section>
                  <q-item-section>ไฟล์ .docx</q-item-section>
                </q-item>
              </q-list>
            </q-menu>
            <q-tooltip>ดาวน์โหลดไฟล์</q-tooltip>
          </q-btn>
          <q-file
            bg-color="white"
            clearable
            outlined
            dense
            v-model="fileUpload"
            accept=".pdf"
            :style="fileUpload === null ? 'width: 150px' : 'width: auto'"
            label="อัพโหลดไฟล์"
            v-if="statusUpload !== true"
          >
            <template v-slot:prepend>
              <q-icon color="light-blue" name="attach_file" />
              <q-tooltip>อัพโหลดไฟล์</q-tooltip>
            </template>
          </q-file>
          <q-btn
            flat
            round
            color="light-blue"
            icon="upload"
            @click="uploadFile(fileUpload)"
            v-if="fileUpload !== null"
          />
        </div>
        <q-space />
        <div class="row">
          <q-tabs shrink>
            <q-input
              borderless
              outlined
              dense
              debounce="300"
              v-model="filter"
              placeholder="ค้นหา"
              style="max-width: 200px"
              class="q-ml-sm"
            >
              <template v-slot:append>
                <q-icon name="search" />
              </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="gt-xs q-ml-sm"
            >
              <!-- <template v-slot:option="{ opt }">
                <div>{{ opt.label }}</div>
                <div class="sublabel">{{ opt.sublabel }}</div>
              </template> -->
            </q-select>
          </q-tabs>
        </div>
      </div>

      <div>
        <q-table
          flat
          dense
          bordered
          :rows="rows"
          :columns="columns"
          row-key="order"
          class="custom-header-table"
          :filter="filter"
          :visible-columns="visibleColumns"
          no-data-label="ไม่มีข้อมูล"
          :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">
                <div class="text-grey-7 text-weight-medium">
                  <span class="row">{{ col.title }}</span>
                  <span class="row" style="font-size: 12px">{{
                    col.subtitle
                  }}</span>
                </div>
              </q-th>
              <q-th auto-width />
              <q-th
                auto-width
                v-if="
                  (typeReport === 'EDIT' ||
                    typeReport === null ||
                    typeReport === '') &&
                  statusReport === false &&
                  statusUpload !== true
                "
              />
              <q-th
                auto-width
                v-if="
                  (typeReport === 'REMOVE' ||
                    typeReport === null ||
                    typeReport === '') &&
                  statusReport === false &&
                  statusUpload !== true
                "
              />
            </q-tr>
          </template>
          <template v-slot:body="props">
            <q-tr
              :props="props"
              class="cursor-pointer"
              :style="props.row.profileId === profileId && 'color: #26a69a;'"
              @click.stop="router.push(`/registry/${props.row.profileId}`)"
            >
              <q-td key="order" :props="props">{{ props.row.order }} </q-td>
              <!-- <q-td key="fixname" :props="props">{{ props.row.fixname }}</q-td> -->
              <q-td key="name" :props="props">{{
                props.row.fixname + props.row.name
              }}</q-td>
              <q-td
                class="table_ellipsis"
                key="organizationOrganization"
                :props="props"
                >{{ props.row.organizationOrganization }}</q-td
              >
              <q-td key="positionType" :props="props">{{
                props.row.positionType
              }}</q-td>
              <q-td key="position" :props="props">{{
                props.row.position
              }}</q-td>
              <q-td key="positionLavel" :props="props">{{
                props.row.positionLavel
              }}</q-td>
              <q-td key="positionNumber" :props="props">{{
                props.row.positionNumber
              }}</q-td>
              <q-td key="govGroup" :props="props">{{
                props.row.govGroup
              }}</q-td>
              <q-td key="govOffice" :props="props">{{
                props.row.govOffice
              }}</q-td>
              <q-td class="table_ellipsis" key="bureau" :props="props">{{
                props.row.bureau
              }}</q-td>
              <q-td>
                <!-- <q-btn
                  :props="props"
                  flat
                  round
                  class="text-teal-5"
                  icon="mdi-note"
                  dense
                  v-if="retireld_params !== undefined"
                  @click="
                    fetchReason(props.row.id), (modalNote = true), (note = '')
                  "
                >
                  <q-tooltip>โน้ต</q-tooltip></q-btn
                > -->
                <!-- <q-btn
                  flat
                  round
                  color="blue"
                  dense
                  icon="mdi-file-account"
                  @click.stop="router.push(`/registry/${props.row.profileId}`)"
                >
                  <q-tooltip>ดูข้อมูลทะเบียนประวัติ</q-tooltip>
                </q-btn> -->
              </q-td>

              <q-td
                auto-width
                v-if="
                  (typeReport === 'EDIT' ||
                    typeReport === null ||
                    typeReport === '') &&
                  statusReport === false &&
                  statusUpload !== true
                "
              >
                <q-btn
                  flat
                  round
                  color="primary"
                  icon="mdi-pencil"
                  dense
                  @click.stop="
                    (modalNote = true),
                      (note = props.row.reason),
                      (action = 'edit'),
                      (retireProfileId = props.row.id)
                  "
                >
                  <q-tooltip>กรอกเหตุผล</q-tooltip>
                </q-btn>
              </q-td>
              <q-td
                auto-width
                v-if="
                  (typeReport === 'REMOVE' ||
                    typeReport === null ||
                    typeReport === '') &&
                  statusReport === false &&
                  statusUpload !== true
                "
              >
                <q-btn
                  flat
                  round
                  class="text-red-14"
                  icon="mdi-delete"
                  dense
                  @click.stop="
                    (modalNote = true),
                      (action = 'delete'),
                      (note = props.row.reason),
                      (retireProfileId = props.row.id)
                  "
                  ><q-tooltip>ลบข้อมูล</q-tooltip></q-btn
                >
              </q-td>
            </q-tr>
          </template>
          <template v-slot:pagination="scope">
            <q-pagination
              v-model="pagination.page"
              color="primary"
              :max="scope.pagesNumber"
              :max-pages="5"
              size="sm"
              boundary-links
              direction-links
            ></q-pagination>
          </template>
        </q-table>
      </div>
    </q-card>
  </div>

  <!-- note -->
  <q-dialog v-model="modalNote">
    <q-card style="width: 700px; max-width: 80vw">
      <q-card-section class="q-pt-none">
        <q-toolbar class="q-py-md">
          <q-toolbar-title class="header-text text-weight-bolder"
            >กรอกเหตุผล
          </q-toolbar-title>
          <q-btn
            icon="close"
            unelevated
            round
            dense
            @click="modalNote = false"
            style="color: #ff8080; background-color: #ffdede"
          />
        </q-toolbar>
      </q-card-section>
      <q-card-section class="q-pt-none">
        <q-input
          outlined
          dense
          lazy-rules
          v-model="note"
          :rules="[(val) => !!val || 'กรุณากรอกเหตุผล']"
          :label="`${'กรอกเหตุผล'}`"
          type="textarea"
        />
      </q-card-section>

      <q-card-actions align="right">
        <q-btn
          v-if="action === 'delete'"
          label="บันทึก"
          color="secondary"
          :disable="visibleNote"
          @click="clickDelete"
        />
        <q-btn
          v-else
          label="บักทึก"
          color="secondary"
          @click="saveNote"
          :disable="visibleNote"
        />
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

<style lang="scss" scope>
.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;
  }

  .q-table thead tr:last-child th {
    top: 48px;
  }

  .q-table thead tr:first-child th {
    top: 0;
  }
}

.q-btn-dropdown__arrow {
  display: none;
}
</style>
