<script setup lang="ts">
import { ref, reactive, watch, onMounted } from "vue";
import { useQuasar } from "quasar";
import { useRoute, useRouter } from "vue-router";
import type { QTableProps } from "quasar";

import http from "@/plugins/http";
import config from "@/app.config";
import { useCounterMixin } from "@/stores/mixin";
import { useAppealComplainStore } from "@/modules/11_discipline/store/AppealComplainStore";
import { useDisciplineMainStore } from "@/modules/11_discipline/store/Main";
import { calculateFiscalYear } from "@/utils/function";

import type {
  MyObjectAppealRef,
  HistoryStatusType,
} from "@/modules/11_discipline/interface/response/appealComplain";

import DialogAddPersonal from "@/components/Dialogs/AddPersonal.vue";
import DialogHistory from "@/modules/11_discipline/components/8_AppealComplain/dialog/DialogEditStatus.vue";

const isReadonly = ref<boolean>(false); // อ่านได้อย่างเดียว
const mainStore = useDisciplineMainStore();
const route = useRoute();
const checkRoutePermission = ref<boolean>(route.name == "appealComplainDetail");
/** รับ props มาจากหน้าหลัก */
const props = defineProps({
  data: {
    type: Object,
    default: null,
  },
  onSubmit: {
    type: Function,
    default: () => "",
  },
  getData: {
    type: Function,
    default: () => "",
  },
});

const $q = useQuasar();
const modalHistory = ref<boolean>(false);
const statusCheck = ref<string>("");
const modalPerson = ref<boolean>(false);
const mixin = useCounterMixin();
const {
  dialogConfirm,
  dialogRemove,
  showLoader,
  success,
  messageError,
  dialogMessageNotify,
  hideLoader,
  downloadRenameFileByLink,
} = mixin;
const dataStore = useAppealComplainStore();

const modalEdit = ref<boolean>(false);

const historyStatusOb = reactive<HistoryStatusType[]>([
  {
    status: "",
    createdFullName: "",
    createdAt: new Date(),
  },
]);

const formData = reactive<any>({
  profileId: "xx",
  title: "",
  description: "",
  caseType: "",
  caseNumber: "",
  type: "",
  file: null,
  disciplineComplaint_Appeal_Docs: [],
  historyStatus: historyStatusOb,
  year: calculateFiscalYear(new Date()).toString(),
});

/** ตัวแปร validate */
const typeRef = ref<Object | null>(null);
const titleRef = ref<Object | null>(null);
const descriptionRef = ref<Object | null>(null);
const caseTypeRef = ref<Object | null>(null);
const caseNumberRef = ref<Object | null>(null);

const objectAppeal: MyObjectAppealRef = {
  type: typeRef,
  title: titleRef,
  description: descriptionRef,
  caseTypeRef: caseTypeRef,
  caseNumberRef: caseNumberRef,
};

const option = ref<any[]>(dataStore.typeOptions);
const optionStatus = ref<any[]>(dataStore.statusOptionsEdit);

/** หัวข้อที่เเสดงในตารางผู้ถูกร้องเรียน */
const visibleColumns = ref<string[]>([
  "no",
  "profileType",
  "citizenId",
  "fullname",
  "oc",
  "position",
]);
/** หัวตารางผู้ถูกร้องเรียน */
const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "center",
    label: "ลำดับ",
    sortable: false,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "profileType",
    align: "left",
    label: "ประเภทตำแหน่ง",
    sortable: true,
    field: "profileType",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "citizenId",
    align: "left",
    label: "เลขประจำตัวประชาชน",
    sortable: true,
    field: "citizenId",
    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: "oc",
    align: "left",
    label: "หน่วยงาน",
    sortable: true,
    field: "oc",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "position",
    align: "left",
    label: "ตำแหน่ง",
    sortable: true,
    field: "position",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);

/*** ฟังก์ชั่นสำหรับ validate ฟอร์ม */
function validateForm() {
  const hasError = [];
  for (const key in objectAppeal) {
    if (Object.prototype.hasOwnProperty.call(objectAppeal, key)) {
      const property = objectAppeal[key];
      if (property.value && typeof property.value.validate === "function") {
        const isValid = property.value.validate();
        hasError.push(isValid);
      }
    }
  }

  if (hasError.every((result) => result === true)) {
    if (dataStore.rowsAdd.length > 0) {
      onSubmit();
    } else {
      dialogMessageNotify(
        $q,
        "กรุณาเพิ่มผู้ยื่นอุทธรณ์/ร้องทุกข์ อย่างน้อย 1 บุคคล"
      );
    }
  } else {
  }
}

function toggleModal() {
  modalPerson.value = !modalPerson.value;
}

async function addPerson(data: any, type?: string) {
  dataStore.rowsAdd = data.map((item: any) => ({
    profileId: item.personId,
    fullname: item.name,
    citizenId: item.idcard,
    oc: item.organization,
    position: item.position,
    profileType: item.profileType
      ? item.profileType
      : type == "officer"
      ? "OFFICER"
      : "EMPLOYEE",
  }));
}

/**
 * ส่งค่า css ออกไปตามเงื่อนไข
 * @param val true/false
 */
function inputEdit(val: boolean) {
  return {
    "full-width cursor-pointer inputgreen ": val,
    "full-width cursor-pointer inputgreen": !val,
  };
}

/** อัปโหลดเอกสาร */
function uploadFile() {
  /** uploadFile */
  const Data = new FormData();
  Data.append("file", formData.file);
  showLoader();
  http
    .put(config.API.appealUpLoadFile(formData.id), Data)
    .then((res) => {
      props.getData();
      success($q, "อัปโหลดไฟล์สำเร็จ");
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      hideLoader();
      formData.file = null;
    });
}

/**
 * เปิดไฟล์เอกสาร
 * @param link link ของไฟล์
 */
function downloadFile(link: string) {
  window.open(link, "_blank");
}

/**
 * ลบไฟลืจาก id
 * @param id id ของไฟล์
 */
function deleteFile(id: string) {
  dialogRemove($q, () => confirmDelete(id));
}

/**
 * ยืนยัน ลบ ไฟล์
 * @param id id file
 */
function confirmDelete(id: string) {
  showLoader();
  http
    .delete(config.API.appealDeleteFile(formData.id, id))
    .then((res) => {
      success($q, `ลบไฟล์สำเร็จ`);
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      props.getData();
    });
}

watch(props.data, async () => {
  if (props.data !== null) {
    isReadonly.value = true;

    formData.id = props.data.id;
    formData.title = props.data.title;
    formData.description = props.data.description;
    formData.status = props.data.status;
    statusCheck.value = props.data.status;
    formData.type = props.data.type;
    formData.year = props.data.year;
    formData.caseType = props.data.caseType;
    formData.caseNumber = props.data.caseNumber;
    formData.fullname = props.data.fullname;
    formData.citizenId = props.data.citizenId;
    formData.profileId = props.data.profileId;
    formData.lastUpdatedAt = props.data.lastUpdatedAt;
    formData.historyStatus = props.data.historyStatus;
    formData.disciplineComplaint_Appeal_Docs =
      props.data.disciplineComplaint_Appeal_Docs;
    dataStore.getRow([
      {
        profileId: props.data.profileId,
        fullname: props.data.fullname,
        citizenId: props.data.citizenId,
        oc: props.data.oc,
        position: props.data.position,
        profileType: props.data.profileType,
      },
    ]);
  }
});

/** ปิด popup */
function close() {
  modalHistory.value = false;
}

/** เปิด pop up history */
function historyStatus() {
  modalHistory.value = true;
}

/** save ข้อมูล */
function onSubmit() {
  dialogConfirm($q, async () => {
    const dataRow = dataStore.rowsAdd;
    const data = {
      profileId: dataRow[0].profileId,
      citizenId: dataRow[0].citizenId,
      fullname: dataRow[0].fullname,
      title: formData.title,
      description: formData.description,
      type: formData.type,
      year: formData.year,
      caseType: formData.caseType,
      caseNumber: formData.caseNumber,
      file: formData.file,
      oc: dataRow[0].oc,
      position: dataRow[0].position,
      profileType: dataRow[0].profileType,
      status: formData.status,
    };
    props.onSubmit(data);
  });
}

/**
 * function ค้นหาข้อมูลใน option
 * @param val คำค้นหา
 * @param update function
 */
function filterOptionFn(val: string, update: Function) {
  update(() => {
    option.value = dataStore.typeOptions.filter(
      (e: any) => e.name.search(val) !== -1
    );
  });
}

/**
 * function ค้นหาข้อมูลใน option
 * @param val คำค้นหา
 * @param update function
 */
function filterOptionFnStatus(val: string, update: Function) {
  update(() => {
    optionStatus.value = dataStore.statusOptionsEdit.filter(
      (e: any) => e.name.search(val) !== -1
    );
  });
}

onMounted(() => {
  dataStore.columns = columns.value;
  dataStore.visibleColumns = visibleColumns.value;
});
</script>

<template>
  <div class="row q-col-gutter-xs">
    <form @submit.prevent="validateForm" class="col-12 row">
      <q-card bordered class="col-12 row">
        <div class="col-12 row">
          <div
            :class="
              isReadonly == true ? 'col-sm-12 col-md-9 row no-wrap' : 'col-12'
            "
          >
            <div class="col-12 q-pa-md">
              <div class="q-gutter-y-sm">
                <div class="row q-gutter-x-sm">
                  <div class="col-3">
                    <q-select
                      :readonly="checkRoutePermission"
                      ref="typeRef"
                      :class="inputEdit(isReadonly)"
                      v-model="formData.type"
                      label="ประเภท"
                      dense
                      outlined
                      emit-value
                      hide-selected
                      fill-input
                      map-options
                      lazy-rules
                      option-label="name"
                      option-value="id"
                      :options="option"
                      :rules="[(val:string) => !!val || `${'กรุณาเลือกประเภท'}`]"
                      hide-bottom-space
                      use-input
                      @filter="filterOptionFn"
                      ><template v-slot:no-option>
                        <q-item>
                          <q-item-section class="text-grey">
                            ไม่มีข้อมูล
                          </q-item-section>
                        </q-item>
                      </template></q-select
                    >
                  </div>
                  <div class="col-3" v-if="isReadonly">
                    <q-select
                      :readonly="checkRoutePermission"
                      ref="statusRef"
                      v-model="formData.status"
                      :class="inputEdit(isReadonly)"
                      label="สถานะ"
                      dense
                      bg-color="white"
                      outlined
                      hide-selected
                      fill-input
                      emit-value
                      lazy-rules
                      :rules="[(val:string) => !!val || `${'กรุณาเลือกสถานะ'}`]"
                      map-options
                      hide-bottom-space
                      option-label="name"
                      option-value="id"
                      :options="optionStatus"
                      use-input
                      @filter="filterOptionFnStatus"
                      ><template v-slot:no-option>
                        <q-item>
                          <q-item-section class="text-grey">
                            ไม่มีข้อมูล
                          </q-item-section>
                        </q-item>
                      </template></q-select
                    >
                  </div>
                  <div class="col-2 self-center" v-if="isReadonly">
                    <q-btn
                      size="16px"
                      flat
                      round
                      dense
                      color="info"
                      class="q-ml-sm"
                      icon="mdi-history"
                      @click="historyStatus"
                    >
                      <q-tooltip>ประวัติแก้ไขสถานะ</q-tooltip>
                    </q-btn>
                  </div>
                </div>
                <div class="row col-12">
                  <q-card
                    bordered
                    class="row col-12"
                    style="border: 1px solid #d6dee1"
                  >
                    <div
                      class="col-xs-12 col-sm-12 text-weight-medium bg-grey-1 q-py-xs q-px-md"
                    >
                      ผู้ยื่นอุทธรณ์/ร้องทุกข์
                      <q-btn
                        v-if="!isReadonly"
                        flat
                        round
                        dense
                        color="primary"
                        class="q-ml-sm"
                        icon="mdi-plus"
                        @click="toggleModal"
                      >
                        <q-tooltip>เพิ่มผู้ยื่นอุทธรณ์/ร้องทุกข์</q-tooltip>
                      </q-btn>
                    </div>
                    <div class="col-12"><q-separator /></div>
                    <div class="col-xs-12 q-pa-sm">
                      <q-table
                        ref="table"
                        :columns="dataStore.columns"
                        :rows="dataStore.rowsAdd"
                        row-key="idcard"
                        flat
                        bordered
                        dense
                        hide-bottom
                        class="custom-header-table"
                        :visible-columns="dataStore.visibleColumns"
                      >
                        <template v-slot:header="props">
                          <q-tr :props="props">
                            <q-th
                              v-for="col in props.cols"
                              :key="col.name"
                              :props="props"
                              style="color: #000000; font-weight: 500"
                            >
                              <span class="text-weight-medium">{{
                                col.label
                              }}</span>
                            </q-th>
                          </q-tr>
                        </template>
                        <template v-slot:body="props">
                          <q-tr :props="props">
                            <q-td
                              v-for="col in props.cols"
                              :key="col.name"
                              :props="props"
                            >
                              <div v-if="col.name == 'no'">
                                {{ props.rowIndex + 1 }}
                              </div>
                              <div
                                v-else-if="col.name === 'oc'"
                                class="table_ellipsis"
                              >
                                {{ props.row.oc }}
                              </div>
                              <div v-else-if="col.name === 'profileType'">
                                {{
                                  props.row.profileType
                                    ? mainStore.convertType(
                                        props.row.profileType
                                      )
                                    : "-"
                                }}
                              </div>
                              <div v-else>
                                {{ col.value ? col.value : "-" }}
                              </div>
                            </q-td>
                          </q-tr>
                        </template>
                      </q-table>
                    </div>
                  </q-card>
                </div>

                <div class="row col-12">
                  <div class="col-12" id="title">
                    <q-input
                      :readonly="checkRoutePermission"
                      ref="titleRef"
                      dense
                      :class="inputEdit(isReadonly)"
                      outlined
                      hide-bottom-space
                      v-model="formData.title"
                      lazy-rules
                      :rules="[
                        (val:string) => !!val || 'กรุณากรอกเรื่องอุทธรณ์/ร้องทุกข์',
                      ]"
                      label="เรื่องอุทธรณ์/ร้องทุกข์"
                    />
                  </div>
                </div>

                <div class="col-xs-12 col-sm-12" id="detail">
                  <q-input
                    :readonly="checkRoutePermission"
                    ref="descriptionRef"
                    dense
                    :class="inputEdit(isReadonly)"
                    outlined
                    hide-bottom-space
                    v-model="formData.description"
                    lazy-rules
                    :rules="[
                      (val:string) => !!val || 'กรุณากรอกรายละเอียดอุทธรณ์/ร้องทุกข์',
                    ]"
                    label="รายละเอียดอุทธรณ์/ร้องทุกข์"
                    type="textarea"
                    rows="5"
                  />
                </div>
                <div class="row q-gutter-x-sm">
                  <div class="col-3">
                    <datepicker
                      :readonly="checkRoutePermission"
                      v-model="formData.year"
                      class="col-2"
                      :locale="'th'"
                      autoApply
                      year-picker
                      :enableTimePicker="false"
                    >
                      <template #year="{ year }">{{ year + 543 }}</template>
                      <template #year-overlay-value="{ value }">{{
                        parseInt(value + 543)
                      }}</template>
                      <template #trigger>
                        <q-input
                          dense
                          :readonly="checkRoutePermission"
                          :class="inputEdit(isReadonly)"
                          outlined
                          :model-value="Number(formData.year) + 543"
                          :label="`${'ปีงบประมาณ'}`"
                        >
                          <template v-slot:prepend>
                            <q-icon
                              name="event"
                              class="cursor-pointer"
                              style="color: var(--q-primary)"
                            >
                            </q-icon>
                          </template>
                        </q-input>
                      </template>
                    </datepicker>
                  </div>

                  <div class="col-3">
                    <q-input
                      ref="caseTypeRef"
                      :readonly="checkRoutePermission"
                      :class="inputEdit(isReadonly)"
                      v-model="formData.caseType"
                      dense
                      outlined
                      lazy-rules
                      :rules="[(val:string) => !!val || 'กรุณากรอกประเภทคดี']"
                      hide-bottom-space
                      label="ประเภทคดี"
                    />
                  </div>
                  <div class="col-3">
                    <q-input
                      ref="caseNumberRef"
                      :readonly="checkRoutePermission"
                      :class="inputEdit(isReadonly)"
                      v-model="formData.caseNumber"
                      dense
                      outlined
                      lazy-rules
                      :rules="[(val:string) => !!val || 'กรุณากรอกเลขที่คดี']"
                      label="เลขที่คดี"
                      hide-bottom-space
                    />
                  </div>
                </div>
              </div>
            </div>
            <div class="row"><q-separator vertical /></div>
          </div>
          <!-- อัปโหลดไฟล์ -->
          <div v-if="isReadonly" class="col-sm-12 col-md-3 q-pa-md">
            <q-card
              bordered
              class="row col-12"
              style="border: 1px solid #d6dee1"
            >
              <div class="col-12 text-weight-medium bg-grey-1 q-py-sm q-px-md">
                อัปโหลดไฟล์เอกสารหลักฐาน
              </div>
              <div class="col-12"><q-separator /></div>
              <div class="row col-12 q-col-gutter-y-sm q-pa-sm">
                <div class="col-12 row">
                  <q-file
                    for="inputFiles"
                    :readonly="checkRoutePermission"
                    class="col-12"
                    outlined
                    dense
                    v-model="formData.file"
                    @added="uploadFile"
                    label="ไฟล์เอกสารหลักฐาน"
                    hide-bottom-space
                    accept=".pdf,.xlsx,.docx"
                    clearable
                  >
                    <template v-slot:prepend>
                      <q-icon name="attach_file" color="primary" />
                    </template>
                    <template v-slot:after>
                      <q-btn
                        v-if="formData.file && isReadonly"
                        size="14px"
                        flat
                        round
                        dense
                        color="primary"
                        icon="mdi-upload"
                        @click="uploadFile"
                        ><q-tooltip>อัปโหลดไฟล์</q-tooltip></q-btn
                      >
                    </template>
                  </q-file>
                </div>

                <div
                  v-if="formData.disciplineComplaint_Appeal_Docs.length > 0"
                  class="col-xs-12 row"
                >
                  <q-list
                    v-for="data in formData.disciplineComplaint_Appeal_Docs"
                    :key="data.id"
                    class="full-width"
                    bordered
                    separator
                  >
                    <q-item clickable v-ripple>
                      <q-item-section>{{ data.fileName }}</q-item-section>
                      <q-space />
                      <q-btn
                        flat
                        round
                        dense
                        color="blue"
                        icon="mdi-download"
                        @click="
                          downloadRenameFileByLink(data.pathName, data.fileName)
                        "
                        ><q-tooltip>ดาวน์โหลดไฟล์</q-tooltip></q-btn
                      >
                      <q-btn
                        v-if="!checkRoutePermission"
                        flat
                        round
                        dense
                        color="red"
                        class="q-ml-sm"
                        icon="mdi-delete"
                        @click="deleteFile(data.id)"
                        ><q-tooltip>ลบไฟล์</q-tooltip></q-btn
                      >
                    </q-item>
                  </q-list>
                </div>
                <div class="col-12" v-else>
                  <q-card class="q-pa-md" bordered> ไม่มีรายการเอกสาร </q-card>
                </div>
              </div>
            </q-card>
          </div>
          <div class="col-12" v-if="!checkRoutePermission"><q-separator /></div>
          <div v-if="!checkRoutePermission" class="row col-12 q-pa-sm">
            <q-space />
            <q-btn id="onSubmit" type="submit" label="บันทึก" color="secondary"
              ><q-tooltip>บันทึกข้อมูล</q-tooltip></q-btn
            >
          </div>
        </div>
      </q-card>
    </form>
  </div>

  <DialogAddPersonal
    title="ผู้ยื่นอุทธรณ์/ร้องทุกข์"
    v-model:modal="modalPerson"
    btn-title="เพิ่มรายชื่อผู้ยื่นอุทธรณ์/ร้องทุกข์"
    :save="addPerson"
    :selected-data="mainStore.rowsAdd"
    selecetSwitch="single"
    :system="(route.meta?.Key as string) || undefined"
  />

  <DialogHistory
    :modal="modalHistory"
    :close="close"
    :data="formData.historyStatus"
  />
</template>

<style scoped lang="scss">
.icon-color {
  color: #4154b3;
}
.custom-header-table {
  height: auto;
  .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>
