<script setup lang="ts">
import { ref, onMounted, watch, reactive, computed } from "vue";
import { useQuasar, QForm } from "quasar";
import type { QTableProps } from "quasar";
import { useCounterMixin } from "@/stores/mixin";
import Table from "@/modules/05_placement/components/PersonalList/TableView.vue";
import DialogCard from "@/modules/05_placement/components/PersonalList/TableDetail.vue";
import DialogFooter from "@/modules/05_placement/components/PersonalList/DialogFooter.vue";
import DialogHeader from "@/modules/05_placement/components/PersonalList/DialogHeader.vue";
import type { PartialTableName } from "@/modules/05_placement/interface/request/placement";
import DialogOrgTree from "@/modules/05_placement/components/PersonalList/OrgTree.vue";
import { useRoute } from "vue-router";
import http from "@/plugins/http";
import config from "@/app.config";
import keycloak from "@/plugins/keycloak";
import router from "@/router";

let roleAdmin = ref<boolean>(false);

const props = defineProps({
  statCard: {
    type: Function,
    default: () => console.log("getStat"),
  },
});
const edit = ref<boolean>(true);
const modal = ref<boolean>(false); //modal ขอผ่อนผัน + สละสิทธิ์
const editRow = ref<boolean>(false); //เช็คมีการแก้ไขข้อมูล
const modalDisclaim = ref<boolean>(false); //modal ที่แสดงใช้สำหรับแก้ไขหรือไม่
const editvisible = ref<boolean>(true);
const modalDefermentDisclaim = ref<boolean>(false); //modal add detail
const checkValidate = ref<boolean>(false);
const modalwaitInfo = ref<boolean>(false); //modal add detail

const userNote = ref<string>("");
const filter = ref<string>("");
const Name = ref<string>();
const rowsAll = ref<any>([]);
const rows = ref<any>([]);
const rowsFilter = ref<any>([]);
const myForm = ref<any>();
const files = ref<any>(null);
const mixin = useCounterMixin(); //เรียกฟังก์ชันกลาง
const $q = useQuasar(); // show dialog

const {
  messageError,
  showLoader,
  hideLoader,
  dateText,
  success,
  dialogConfirm,
} = mixin;

const route = useRoute();
const examId = route.params.examId;
const examIdString = Array.isArray(examId) ? examId[0] : examId;
const personalId = ref<string>("");

const visibleColumns = ref<any[]>([
  "position",
  "fullName",
  "examNumber",
  "idCard",
  "positionNumber",
  "organizationName",
  "reportingDate",
  "bmaOfficer",
  "statusName",
  "draft",
  "positionCandidate",
]);
const visibleColumnslist = ref<any>([
  "fullName",
  "examNumber",
  "idCard",
  "positionNumber",
  "organizationName",
  "draft",
  "bmaOfficer",
  "positionCandidate",
]);

const columns = ref<QTableProps["columns"]>([
  {
    name: "position",
    align: "center",
    label: "ลำดับ",
    sortable: true,
    field: "position",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "fullName",
    align: "left",
    label: "ชื่อ-สกุล",
    sortable: true,
    field: "fullName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px,",
  },
  {
    name: "examNumber",
    align: "center",
    label: "ลำดับที่สอบได้",
    sortable: true,
    field: "examNumber",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "organizationName",
    align: "left",
    label: "หน่วยงานที่รับการบรรจุ",
    sortable: true,
    field: "organizationName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "positionCandidate",
    align: "left",
    label: "ตำแหน่งที่สอบ",
    sortable: true,
    field: "positionCandidate",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "reportingDate",
    align: "left",
    label: "วันที่รายงานตัว",
    sortable: true,
    field: "reportingDate",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "bmaOfficer",
    align: "left",
    label: "สถานภาพ",
    sortable: true,
    field: "bmaOfficer",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "draft",
    align: "left",
    label: "สถานะการส่งรายชื่อ",
    sortable: true,
    field: "draft",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "statusName",
    align: "left",
    label: "สถานะการบรรจุ",
    sortable: true,
    field: "statusName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);

const convertBmaOfficer = (val: string) => {
  switch (val) {
    case "OFFICER":
      return "ขรก.กทม. สามัญ";
    case "EMPLOYEE_PERM":
      return "ลูกจ้างประจำ";
    case "EMPLOYEE_TEMP":
      return "ลูกจ้างชั่วคราว";
    default:
      return "บุคคลภายนอก";
  }
};

const convertContainStatus = (val: string) => {
  switch (val) {
    case "UN-CONTAIN":
      return "ยังไม่บรรจุ";
    case "PREPARE-CONTAIN":
      return "เตรียมบรรจุ";
    case "CONTAIN":
      return "บรรจุแล้ว";
    case "DISCLAIM":
      return "สละสิทธิ์";
    default:
      return "-";
  }
};
const convertDraft = (val: boolean) => {
  switch (val) {
    case false:
      return "รอส่งตัว";
    case true:
      return "ส่งตัวแล้ว";
    default:
      return "-";
  }
};

const getTable = async () => {
  showLoader();
  await http
    .get(config.API.personalList(examIdString))
    .then(async (res: any) => {
      console.log(res);
      dataRes.value = res.data.result;
      rowsAll.value = [];
      (rowsFilter.value = []),
        res.data.result.map((data: any) => {
          const rowData = {
            personalId: data.personalId,
            idCard: data.idCard,
            fullName: data.fullName + " " + data.idCard,
            name: data.fullName,
            profilePhoto: data.profilePhoto ?? "",
            avatar: data.avatar ?? "",
            organizationName:
              data.organizationName +
              " " +
              data.organizationShortName +
              " " +
              data.positionNumber +
              " " +
              data.positionPath,
            orgName: data.organizationName,
            organizationShortName: data.organizationShortName,
            positionNumber: data.positionNumber,
            positionPath: data.positionPath,
            reportingDate:
              data.reportingDate == null
                ? null
                : dateText(new Date(data.reportingDate)),
            examNumber: data.examNumber,
            bmaOfficer: convertBmaOfficer(data.bmaOfficer),
            statusId: data.statusId,
            statusName: convertContainStatus(data.statusId),
            deferment: data.deferment,
            draft: convertDraft(data.draft),
            positionCandidate: data.positionCandidate,
          };

          rowsAll.value.push(rowData);
        });

      rows.value = roleAdmin
        ? rowsAll.value
        : rowsAll.value.filter((x: any) => x.statusId != "CONTAIN");

      rowsFilter.value = rows.value.filter(
        (e: any) =>
          e.draft == "รอส่งตัว" &&
          e.positionNumber !== null &&
          e.statusName == "เตรียมบรรจุ"
      );
      console.log(rowsFilter.value);
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      hideLoader();
    });
};

const appointModal = ref<boolean>(false);

const saveDeferment = async () => {
  myForm.value.validate().then(async (result: boolean) => {
    if (result) {
      dialogConfirm(
        $q,
        async () => await postDeferment(),
        "ยืนยันการขอผ่อนผัน",
        "ต้องการยืนยันการขอผ่อนผันข้อมูลนี้ใช่หรือไม่ ?"
      );
      // $q.dialog({
      //   title: "ยืนยันการขอผ่อนผัน",
      //   message: "ต้องการยืนยันการขอผ่อนผันข้อมูลนี้ใช่หรือไม่ ?",
      //   cancel: {
      //     flat: true,
      //     const: "negative",
      //   },
      //   persistent: true,
      // })
      //   .onOk(async () => {})
      //   .onCancel(() => {})
      //   .onDismiss(() => {});
    }
  });
};
const postDeferment = async () => {
  const formData = new FormData();
  formData.append("personalId", personalId.value);
  formData.append("note", userNote.value);
  formData.append("files", files.value[0]);
  showLoader();
  await http
    .post(config.API.deferment(), formData)
    .then(() => {
      success($q, "บันทึกสำเร็จ");
    })
    .catch((e) => {
      console.log(e);
    })
    .finally(async () => {
      await getTable();
      props.statCard();
      userNote.value = "";
      modalDefermentDisclaim.value = false;
      hideLoader();
    });
};

const saveDisclaim = async () => {
  myForm.value.validate().then(async (result: boolean) => {
    if (result) {
      dialogConfirm(
        $q,
        async () => await postDisclaimf(),
        "ยืนยันการสละสิทธิ์",
        "ต้องการยืนยันการสละสิทธิ์ข้อมูลนี้ใช่หรือไม่ ?"
      );
    }
  });
};
const postDisclaimf = async () => {
  const dataPost = {
    note: userNote.value,
    personId: personalId.value,
  };
  showLoader();
  console.log("ยืนยันการสละสิทธิ์");
  await http
    .post(config.API.disclaimF(), {
      note: dataPost.note,
      personalId: dataPost.personId,
    })
    .then(() => {
      success($q, "บันทึกสำเร็จ");
    })
    .finally(async () => {
      await getTable();
      props.statCard();
      userNote.value = "";
      modalDefermentDisclaim.value = false;
      hideLoader();
    });
};

const clickEditRow = () => {
  editRow.value = true;
};

const getClass = (val: boolean) => {
  return {
    "full-width inputgreen cursor-pointer ": val,
    "full-width cursor-pointer": !val,
  };
};

const selectData = (pid: string) => {
  if (roleAdmin.value === true) {
    personalId.value = pid;
    modal.value = true;
  } else {
    router.push("/placement/personal-detail/" + pid);
  }
};
const getNumFile = ref(0);
const dataInfo = reactive({
  reason: "",
  reliefDoc: "",
});

const editDetail = (
  props: PartialTableName,
  action: "disclaim" | "deferment" | "defermentInfo" | "disclaimInfo"
) => {
  Name.value = props.name;
  personalId.value = props.personalId;
  editRow.value = false;
  edit.value = true;

  if (action === "disclaim") {
    getNumFile.value = 0;
    modalDisclaim.value = true;
    modalDefermentDisclaim.value = true;
  } else if (action === "deferment") {
    getNumFile.value = 1;
    modalDisclaim.value = false;
    modalDefermentDisclaim.value = true;
  } else if (action === "defermentInfo") {
    http
      .get(config.API.placementDefermentInfo(props.personalId))
      .then((res: any) => {
        dataInfo.reason = res.data.result.reliefReason;
        dataInfo.reliefDoc = res.data.result.reliefDoc;
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(() => {
        modalDisclaim.value = false;
        modalwaitInfo.value = true;
      });
  } else if (action === "disclaimInfo") {
    http
      .get(config.API.placementDisclaimInfo(props.personalId))
      .then((res: any) => {
        dataInfo.reason = res.data.result.rejectReason;
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(() => {
        modalDisclaim.value = true;
        modalwaitInfo.value = true;
      });
  }
};

const dataRes = ref<any>([]);
const personal = ref<any>([]);
const openAppointModal = (pid: string) => {
  appointModal.value = true;
  personalId.value = pid;
  personal.value = dataRes.value.filter(
    (e: any) => e.personalId == personalId.value
  );
};

const clickCloseModalTree = async () => {
  await getTable();
  appointModal.value = false;
  props.statCard();
};

const validateData = async () => {
  checkValidate.value = true;
  await myForm.value.validate().then((result: boolean) => {
    if (result == false) {
      checkValidate.value = false;
    }
  });
};

const clickCloseSendModal = () => {
  modaladdlist.value = false;
};

const clickClose = async () => {
  userNote.value = "";

  if (editRow.value == true) {
    dialogConfirm(
      $q,
      () => {
        modalDefermentDisclaim.value = false;
        modalwaitInfo.value = false;
        modal.value = false;
        files.value = null;
      },
      `ข้อมูลมีการแก้ไข`,
      `ยืนยันที่จะปิดโดยไม่บันทึกใช่หรือไม่?`
    );
  } else {
    modalDefermentDisclaim.value = false;
    modalwaitInfo.value = false;
    modal.value = false;
  }
};
const displayAdd = ref<boolean>(true);
onMounted(async () => {
  if (keycloak.tokenParsed != null) {
    roleAdmin.value = await keycloak.tokenParsed.role.includes("placement1");
    console.log("roleAdmin===>", roleAdmin.value);
    if (roleAdmin.value === false) {
      displayAdd.value = false;
      visibleColumns.value = [
        "position",
        "fullName",
        "examNumber",
        "idCard",
        "positionNumber",
        "organizationName",
        "reportingDate",
        "bmaOfficer",
        "statusName",
        "positionCandidate",
      ];
    }
  }
  await getTable();
});
// watch(rowsAll, () => {
//   props.statCard();
// });
// watchEffect(() => {
//   if (getTable()) {
//     props.statCard();
//   }
// });

const containStatus = ref<boolean>(false);
watch(containStatus, () => {
  // console.log("containStatus===>", containStatus.value);
  if (containStatus.value) {
    rows.value = rowsAll.value.filter((x: any) => x.statusId == "CONTAIN");
  } else {
    rows.value = rowsAll.value.filter((x: any) => x.statusId != "CONTAIN");
  }
});
const modaladdlist = ref<boolean>(false);
const selected = ref<any>([]);
const personal_selected = ref<any>([]);
const filterlistAdd = ref<string>("");
const paging = ref<boolean>(true);
const savelist = () => {
  selected.value.map((e: any) => {
    personal_selected.value.push(e.personalId);
  });
  if (personal_selected.value) {
    // console.log(personal_selected.value);
    dialogConfirm(
      $q,
      async () => {
        showLoader();
        await http
          .put(config.API.putPosition(examId), personal_selected.value)
          .then(() => {
            success($q, "บันทึกสำเร็จ");
          })
          .catch((e: any) => {
            console.log(e);
          })
          .finally(async () => {
            await getTable();

            hideLoader();
          });
      },
      "ยืนยันการส่งรายชื่อไปยังหน่วยงาน",
      "ต้องการยืนยันการส่งรายชื่อไปยังหน่วยงานหรือไม่?"
    );
  }
};
const handleModalAddListUpdate = (val: boolean) => {
  modaladdlist.value = val;
  (selected.value = []), (personal_selected.value = []);
};
const checkSelected = computed(() => {
  if (selected.value.length === 0) {
    return true;
  }
});
const pagination = ref({
  sortBy: "fullname",
  descending: true,
  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>
  <q-form ref="myForm">
    <Table
      :contain-status="containStatus"
      :rows="rows"
      :columns="columns"
      :filter="filter"
      :visible-columns="visibleColumns"
      v-model:inputfilter="filter"
      v-model:inputvisible="visibleColumns"
      v-model:editvisible="editvisible"
      v-model:containfilter="containStatus"
      @update-modaladdlist="handleModalAddListUpdate"
      :history="true"
      :boss="true"
      :saveNoDraft="true"
      :role-admin="roleAdmin"
      :displayAdd="displayAdd"
      row-key="fullname"
    >
      <template #columns="props">
        <q-tr :props="props">
          <q-td
            v-for="col in props.cols"
            :key="col.name"
            :props="props"
            @click="selectData(props.row.personalId)"
            class="cursor-pointer"
          >
            <template v-if="col.name === 'position'">
              {{ props.rowIndex + 1 }}
            </template>
            <template
              v-else-if="col.name === 'fullName'"
              class="table_ellipsis"
            >
              <q-item v-ripple>
                <q-item-section avatar>
                  <img
                    v-if="props.row.avatar == ''"
                    src="@/assets/avatar_user.jpg"
                    class="col-4 img-info"
                  />
                  <img v-else :src="props.row.avatar" class="col-4 img-info" />
                </q-item-section>

                <q-item-section>
                  <div class="text-weight-medium">{{ props.row.name }}</div>
                  <div class="text-weight-light">{{ props.row.idCard }}</div>
                </q-item-section>
              </q-item>
            </template>
            <template v-else-if="col.name === 'examNumber'">
              <div class="text-weight-medium">
                {{ props.row.examNumber !== null ? props.row.examNumber : "-" }}
              </div>
            </template>

            <template v-else-if="col.name === 'organizationName'">
              <div
                v-if="
                  props.row.orgName !== null || props.row.positionPath !== null
                "
              >
                <div class="col-4">
                  <div class="text-weight-medium">
                    {{ props.row.orgName !== null ? props.row.orgName : "-" }}
                    {{
                      props.row.organizationShortName !== null
                        ? `(${props.row.organizationShortName})`
                        : ""
                    }}
                  </div>
                  <div class="text-weight-light">
                    {{
                      props.row.positionPath !== null
                        ? props.row.positionPath
                        : "-"
                    }}
                    {{
                      props.row.positionNumber !== null
                        ? `(${props.row.positionNumber})`
                        : ""
                    }}
                  </div>
                </div>
              </div>
              <div v-else>
                <div class="col-4">
                  <div class="text-weight-medium">-</div>
                </div>
              </div>
            </template>
            <template v-else-if="col.name === 'positionCandidate'">
              <div
                class="text-weight-medium"
                v-if="props.row.positionCandidate == null"
              >
                -
              </div>
              <div class="text-weight-medium" v-else>
                {{ props.row.positionCandidate }}
              </div>
            </template>
            <template
              v-else-if="col.name === 'reportingDate' && col.value !== '-'"
            >
              <div class="text-weight-medium">
                {{ props.row.reportingDate }}
              </div>
            </template>
            <template v-else-if="col.name === 'bmaOfficer'">
              <div class="text-weight-medium">
                {{ props.row.bmaOfficer !== null ? props.row.bmaOfficer : "-" }}
              </div>
            </template>
            <template v-else-if="col.name === 'draft'">
              <div class="text-weight-medium">
                {{ props.row.draft }}
              </div>
            </template>
            <template v-else-if="col.name === 'statusName'">
              <div class="text-weight-medium">
                {{ props.row.statusName }}
              </div>
            </template>
          </q-td>
          <q-td auto-width>
            <q-btn
              icon="mdi-dots-vertical"
              size="12px"
              color="grey-7"
              flat
              round
              dense
            >
              <q-menu transition-show="jump-down" transition-hide="jump-up">
                <q-list dense style="min-width: 100px">
                  <q-item
                    v-if="
                      (roleAdmin && props.row.statusId === 'UN-CONTAIN') ||
                      (props.row.draft === 'รอส่งตัว' &&
                        props.row.statusId !== 'DISCLAIM')
                    "
                    clickable
                    v-close-popup
                    @click="openAppointModal(props.row.personalId)"
                  >
                    <q-item-section
                      style="min-width: 0px"
                      avatar
                      class="q-py-sm"
                    >
                      <q-icon
                        color="primary"
                        size="xs"
                        name="mdi-bookmark-outline"
                      />
                    </q-item-section>
                    <q-item-section>เลือกหน่วยงานที่รับบรรจุ</q-item-section>
                  </q-item>

                  <q-separator />
                  <q-item
                    v-if="roleAdmin && props.row.statusId === 'UN-CONTAIN'"
                    clickable
                    v-close-popup
                    @click="editDetail(props.row, 'deferment')"
                  >
                    <q-item-section
                      style="min-width: 0px"
                      avatar
                      class="q-py-sm"
                    >
                      <q-icon
                        color="blue"
                        size="xs"
                        name="mdi-account-alert-outline"
                      />
                    </q-item-section>
                    <q-item-section>ขอผ่อนผัน</q-item-section>
                  </q-item>
                  <q-item
                    v-else-if="
                      props.row.deferment === true &&
                      props.row.statusId != 'DISCLAIM'
                    "
                    clickable
                    v-close-popup
                    @click="editDetail(props.row, 'defermentInfo')"
                  >
                    <q-item-section
                      style="min-width: 0px"
                      avatar
                      class="q-py-sm"
                    >
                      <q-icon
                        color="blue"
                        size="xs"
                        name="mdi-account-details-outline"
                      />
                    </q-item-section>
                    <q-item-section>ข้อมูลการผ่อนผัน</q-item-section>
                  </q-item>
                  <q-separator />
                  <q-item
                    v-if="
                      props.row.statusId === 'UN-CONTAIN' ||
                      props.row.statusId === 'PREPARE-CONTAIN'
                    "
                    clickable
                    v-close-popup
                    @click="editDetail(props.row, 'disclaim')"
                  >
                    <q-item-section
                      style="min-width: 0px"
                      avatar
                      class="q-py-sm"
                    >
                      <q-icon
                        color="pink"
                        size="xs"
                        name="mdi-account-cancel-outline"
                      />
                    </q-item-section>
                    <q-item-section>สละสิทธิ์</q-item-section>
                  </q-item>
                  <q-item
                    v-else-if="props.row.statusId === 'DISCLAIM'"
                    clickable
                    v-close-popup
                    @click="editDetail(props.row, 'disclaimInfo')"
                  >
                    <q-item-section
                      style="min-width: 0px"
                      avatar
                      class="q-py-sm"
                    >
                      <q-icon
                        color="pink"
                        size="xs"
                        name="mdi-account-cancel-outline"
                      />
                    </q-item-section>
                    <q-item-section>ข้อมูลการสละสิทธิ์</q-item-section>
                  </q-item>
                </q-list>
              </q-menu>
            </q-btn>
          </q-td>
        </q-tr>
      </template>
    </Table>
  </q-form>

  <!-- เลือกหน่วยงานที่บรรจุ -->
  <DialogOrgTree
    v-model:modal="appointModal"
    :personalId="personalId"
    :close="clickCloseModalTree"
    :personal="personal"
  />

  <!-- popup ขอผ่อนผัน / สละสิทธิ์ -->
  <q-form ref="myForm">
    <DialogCard
      v-model:Modal="modal"
      :personal-id="personalId"
      :close="clickClose"
      :validate="validateData"
    />
  </q-form>
  <q-dialog v-model="modalDefermentDisclaim" persistent>
    <q-card style="width: 800px">
      <q-form ref="myForm">
        <DialogHeader
          :title="`${modalDisclaim ? 'สละสิทธิ์' : 'ขอผ่อนผัน'} ${Name}`"
          :close="clickClose"
        />
        <q-separator />
        <q-card-section class="q-p-sm">
          <div class="col-xs-12 col-sm-12 col-md-12">
            <q-input
              :class="getClass(edit)"
              hide-bottom-space
              :outlined="edit"
              dense
              lazy-rules
              :rules="[(val) => !!val || 'กรุณากรอกเหตุผล']"
              :readonly="!edit"
              :borderless="!edit"
              v-model="userNote"
              :label="`${'กรอกเหตุผล'}`"
              @update:model-value="clickEditRow"
              type="textarea"
            />
            <q-file
              v-if="getNumFile === 1"
              v-model="files"
              dense
              :label="`${'เลือกไฟล์เอกสารหลักฐาน'}`"
              outlined
              use-chips
              :rules="[(val) => !!val || 'กรุณาเลือกไฟล์เอกสารหลักฐาน']"
              multiple
              @update:model-value="clickEditRow"
              class="q-py-sm"
            >
              <template v-slot:prepend>
                <q-icon name="attach_file" color="primary" />
              </template>
            </q-file>
          </div>
        </q-card-section>
        <q-separator />
        <DialogFooter
          :editvisible="true"
          :validate="validateData"
          :save="modalDisclaim ? saveDisclaim : saveDeferment"
        />
      </q-form>
    </q-card>
  </q-dialog>

  <!-- dialog ข้อมูลขอผ่อนผัน / สละสิทธิ์ -->
  <q-dialog v-model="modalwaitInfo" persistent>
    <q-card style="width: 500px; max-width: 500px">
      <q-form ref="myForm">
        <DialogHeader
          :title="`${modalDisclaim ? 'สละสิทธิ์' : 'ขอผ่อนผัน'} ${Name}`"
          :close="clickClose"
        />
        <q-separator />
        <q-card-section class="q-p-sm">
          <div class="row">
            <div class="col-3 text-grey-7">เหตุผล</div>
            <div class="col-4">{{ dataInfo.reason }}</div>
          </div>
          <div v-if="!modalDisclaim" class="row q-pt-md">
            <div class="col-3 text-grey-7 q-mt-sm">เอกสารหลักฐาน</div>
            <div class="col-2 q-mt-sm">
              <q-btn
                type="a"
                :href="dataInfo.reliefDoc"
                color="primary"
                flat
                dense
                round
                size="14px"
                icon="mdi-download"
                target="_blank"
              />
            </div>
          </div>
        </q-card-section>
        <q-separator />
      </q-form>
    </q-card>
  </q-dialog>

  <!-- dialog เพิ่มรายชื่อ -->
  <q-dialog v-model="modaladdlist">
    <q-card style="width: 900px; max-width: 80vw">
      <DialogHeader
        title="ส่งรายชื่อไปยังหน่วยงาน"
        :close="clickCloseSendModal"
      />
      <q-separator />
      <q-card-section class="q-pt-none">
        <div class="row justify-end">
          <div class="col-5">
            <q-toolbar style="padding: 0">
              <q-input
                borderless
                outlined
                dense
                debounce="300"
                v-model="filterlistAdd"
                placeholder="ค้นหา"
                style="width: 850px; max-width: auto"
              >
                <template v-slot:append>
                  <q-icon name="search" />
                </template>
              </q-input>
              <q-select
                v-model="visibleColumnslist"
                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"
              />
            </q-toolbar>
          </div>
        </div>

        <q-table
          flat
          bordered
          dense
          :rows="rowsFilter"
          :columns="columns"
          :filter="filterlistAdd"
          row-key="name"
          class="custom-header-table"
          selection="multiple"
          v-model:selected="selected"
          :pagination-label="paginationLabel"
          :visible-columns="visibleColumnslist"
        >
          <template v-slot:header-selection="scope">
            <q-checkbox
              keep-color
              color="primary"
              dense
              v-model="scope.selected"
            />
          </template>
          <!-- <template v-slot:body-selection="scope">
            <q-checkbox
              keep-color
              color="primary"
              dense
              v-model="scope.selected"
            />
          </template> -->
          <template v-slot:body="props">
            <q-tr :props="props">
              <q-td>
                <q-checkbox
                  keep-color
                  color="primary"
                  dense
                  v-model="props.selected"
                />
              </q-td>
              <q-td
                v-for="col in props.cols"
                :key="col.name"
                :props="props"
                class="cursor-pointer"
              >
                <template v-if="col.name === 'position'">
                  {{ props.rowIndex + 1 }}
                </template>
                <template
                  v-else-if="col.name === 'fullName'"
                  class="table_ellipsis"
                >
                  <div class="row col-12 text-no-wrap items-center">
                    <img
                      v-if="props.row.avatar == null"
                      src="@/assets/avatar_user.jpg"
                      class="col-4 img-info"
                    />
                    <img
                      v-else
                      :src="props.row.avatar"
                      class="col-4 img-info"
                    />
                    <div class="col-4">
                      <div class="text-weight-medium">{{ props.row.name }}</div>
                      <div class="text-weight-light">
                        {{ props.row.idCard }}
                      </div>
                    </div>
                  </div>
                </template>
                <template v-else-if="col.name === 'examNumber'">
                  <div class="text-weight-medium">
                    {{
                      props.row.examNumber !== null ? props.row.examNumber : "-"
                    }}
                  </div>
                </template>

                <template v-else-if="col.name === 'organizationName'">
                  <div
                    v-if="
                      props.row.orgName !== null ||
                      props.row.positionPath !== null
                    "
                  >
                    <div class="col-4">
                      <div class="text-weight-medium">
                        {{
                          props.row.orgName !== null ? props.row.orgName : "-"
                        }}
                        {{
                          props.row.organizationShortName !== null
                            ? `(${props.row.organizationShortName})`
                            : ""
                        }}
                      </div>
                      <div class="text-weight-light">
                        {{
                          props.row.positionPath !== null
                            ? props.row.positionPath
                            : "-"
                        }}
                        {{
                          props.row.positionNumber !== null
                            ? `(${props.row.positionNumber})`
                            : ""
                        }}
                      </div>
                    </div>
                  </div>
                  <div v-else>
                    <div class="col-4">
                      <div class="text-weight-medium">-</div>
                    </div>
                  </div>
                </template>
                <template v-else-if="col.name === 'positionCandidate'">
                  <div
                    class="text-weight-medium"
                    v-if="props.row.positionCandidate == null"
                  >
                    -
                  </div>
                  <div class="text-weight-medium" v-else>
                    {{ props.row.positionCandidate }}
                  </div>
                </template>
                <template
                  v-else-if="col.name === 'reportingDate' && col.value !== '-'"
                >
                  <div class="text-weight-medium">
                    {{ props.row.reportingDate }}
                  </div>
                </template>
                <template v-else-if="col.name === 'bmaOfficer'">
                  <div class="text-weight-medium">
                    {{
                      props.row.bmaOfficer !== null ? props.row.bmaOfficer : "-"
                    }}
                  </div>
                </template>
                <template v-else-if="col.name === 'draft'">
                  <div class="text-weight-medium">
                    {{ props.row.draft }}
                  </div>
                </template>
                <template v-else-if="col.name === 'statusName'">
                  <div class="text-weight-medium">
                    {{ props.row.statusName }}
                  </div>
                </template>
              </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>
      </q-card-section>

      <q-card-actions align="right" class="bg-white text-teal">
        <q-btn
          label="ส่งรายชื่อ"
          @click="savelist"
          :disable="checkSelected"
          color="public"
        />
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

<style lang="scss" scoped>
.custom-input {
  font-size: 16px;
}

.my-list-link {
  border-radius: 5px;

  font-weight: 600;
  border: 1px solid #00aa86;
}

.q-table p {
  margin-bottom: 0;
  color: #818181;
}

.img-info {
  width: 30px !important;
  height: 30px !important;
  border-radius: 50%;
  object-fit: cover;
  margin-right: 10px;
}
</style>
