<script setup lang="ts">
import { ref, onMounted, watch, reactive } 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 myForm = ref<any>();
const files = ref<any>(null);
const mixin = useCounterMixin(); //เรียกฟังก์ชันกลาง
const $q = useQuasar(); // show dialog

const { messageError, showLoader, hideLoader, dateText, success } = 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",
  "number",
  "idCard",
  "positionNumber",
  "organizationName",
  "reportingDate",
  "bmaOfficer",
  "statusName",
]);

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: "number",
    align: "center",
    label: "ลำดับที่สอบได้",
    sortable: true,
    field: "number",
    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: "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: "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 getTable = async () => {
  showLoader();
  await http
    .get(config.API.personalList(examIdString))
    .then(async (res: any) => {
      rowsAll.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,
          organizationName: data.organizationName + ' ' + data.organizationShortName + ' ' + data.positionNumber + ' ' + data.positionPath,
          orgName: data.organizationName,
          organizationShortName: data.organizationShortName,
          positionNumber: data.positionNumber,
          positionPath: data.positionPath,
          reportingDate: dateText(new Date(data.reportingDate)),
          number: data.number,
          bmaOfficer:
            data.bmaOfficer == "OFFICER"
              ? "ขรก.กทม. สามัญ"
              : data.bmaOfficer == "EMPLOYEE_PERM"
                ? "ลูกจ้างประจำ"
                : data.bmaOfficer == "EMPLOYEE_TEMP"
                  ? "ลูกจ้างชั่วคราว"
                  : data.bmaOfficer == null
                    ? "บุคคลภายนอก"
                    : "-",
          statusId: data.statusId,
          statusName:
            data.statusId == "UN-CONTAIN"
              ? "ยังไม่บรรจุ"
              : data.statusId == "PREPARE-CONTAIN"
                ? "เตรียมบรรจุ"
                : data.statusId == "CONTAIN"
                  ? "บรรจุแล้ว"
                  : data.statusId == "DISCLAIM"
                    ? "สละสิทธิ์"
                    : "-",
          deferment: data.deferment,
        };

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

      rows.value = roleAdmin ? rowsAll.value : rowsAll.value.filter((x: any) => x.statusId != 'CONTAIN');
    })
    .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) {
      showLoader();
      const formData = new FormData();
      formData.append("personalId", personalId.value);
      formData.append("note", userNote.value);
      formData.append("files", files.value[0]);

      await http
        .post(config.API.deferment(), formData)
        .then((res) => {
          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) {
      showLoader();
      const dataPost = {
        note: userNote.value,
        personId: personalId.value,
      };

      // console.log("save disclaim===>", dataPost);

      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 openAppointModal = (pid: string) => {
  appointModal.value = true;
  personalId.value = pid;
};

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

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

const clickClose = async () => {
  userNote.value = "";
  if (editRow.value == true) {
    $q.dialog({
      title: `ข้อมูลมีการแก้ไข`,
      message: `ยืนยันที่จะปิดโดยไม่บันทึกใช่หรือไม่?`,
      cancel: "ยกเลิก",
      ok: "ยืนยัน",
      persistent: true,
    }).onOk(async () => {
      modalDefermentDisclaim.value = false;
      modalwaitInfo.value = false;
      modal.value = false;
      files.value = null;
    });
  } else {
    modalDefermentDisclaim.value = false;
    modalwaitInfo.value = false;
    modal.value = false;
  }
};

onMounted(async () => {
  if (keycloak.tokenParsed != null) {
    roleAdmin.value = await keycloak.tokenParsed.role.includes("placement1");
    console.log("roleAdmin===>", roleAdmin);
  }
  await getTable();
});

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');
  }
});

</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" :history="true" :boss="true"
      :saveNoDraft="true" :role-admin="roleAdmin">
      <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">
              <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 === 'number'">
              <div class="text-weight-medium">
                {{ props.row.number !== null ? props.row.number : "-" }}
              </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 === '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 === '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'" 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" />

  <!-- 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>
</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>
