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

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

import type {
  FormData,
  FormRef,
  DataOption,
  FaultTypeOption,
} from "@/modules/11_discipline/interface/request/result";

import DialogHistory from "@/modules/11_discipline/components/4_Result/DialogHistory.vue";
import PopupPersonal from "@/components/Dialogs/PopupPersonalNew.vue";
import DialogHeader from "@/components/DialogHeader.vue";

const mainStore = useDisciplineMainStore();

const isEmpType = ref<string>("");
const dataStore = useDisciplineResultStore();
const mixin = useCounterMixin();
const {
  hideLoader,
  dialogConfirm,
  success,
  messageError,
  showLoader,
  dialogRemove,
  downloadRenameFileByLink,
  dialogMessageNotify,
} = mixin;
const route = useRoute();

const modalPersonal = ref<boolean>(false);
const personId = ref<string>("");
const countNum = ref<number>(1);
const isReadonly = ref<boolean>(false); // อ่านได้อย่างเดียว

const checkRoutePermisson = ref<boolean>(
  route.name == "disciplineResultDetail"
);
const $q = useQuasar();
const id = ref<string>(route.params.id as string);
const isSave = ref<boolean>(false); // มีการแก้ไขรอบันทึก
const respondentType = ref<string>("");
const organization = ref<DataOption>();
const organizationId = ref<string>("");
const organizationName = ref<string>("");
const consideredAgency = ref<string>("");
const organizationOption = ref<DataOption[]>([]);
/** ตัวแปร ref สำหรับแสดง validate */
const detailRef = ref<Object | null>(null);
const modalHistory = ref<boolean>(false);
const personalId = ref<string>("");
const nameFault = ref<string>("");
const modalFault = ref<boolean>(false);
const remark = ref<string>("");

const idRow = ref<string>("");
const checkValue = ref<FaultTypeOption[]>(
  JSON.parse(JSON.stringify(mainStore.checkValueFaultT))
);
const offense = ref<string>("");
const offenseOp = ref<DataOption[]>([
  {
    id: "มาตรา 82",
    name: "มาตรา 82",
  },
  {
    id: "มาตรา 83",
    name: "มาตรา 83",
  },
  {
    id: "มาตรา 85",
    name: "มาตรา 85",
  },
]);

/** รับ props มาจากหน้าหลัก */
const props = defineProps({
  data: {
    type: Object,
    default: null,
  },
  onSubmit: {
    type: Function,
    default: () => "",
  },
  fetchData: {
    type: Function,
    default: () => "",
  },
});

/** ข้อมูล v-model ของฟอร์ม */
const formData = reactive<FormData>({
  resultDescription: "",
  disciplineType: "",
  titleType: "",
  oc: "",
  file: null,
  disciplineDisciplinary_DocResults: [],
  year: calculateFiscalYear(new Date()),
});

/** maping ref เข้าตัวแปรเพื่อเตรียมตรวจสอบ */
const objectdisciplinary: FormRef = {
  resultDescription: detailRef,
};

/** function เรียกรายชื่อหน่วยงาน*/
/** ดึงข้อมูล active */
async function getActive() {
  showLoader();
  await http
    .get(config.API.activeOrganization)
    .then((res) => {
      getOc(res.data.result.activeId);
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

async function getOc(activeId: string) {
  showLoader();
  await http
    .get(config.API.orgByIdSystem(activeId, route.meta.Key as string))
    .then(async (res) => {
      organizationOption.value = await res.data.result.map((item: any) => ({
        id: item.orgTreeId,
        name: item.orgName,
      }));
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

async function selectComplainant(val: string) {
  organizationId.value = "";
  consideredAgency.value = "";
}

/**
 * ฟังก์ชั่นสำหรับบันทึกข้อมูล ระบบจะแสดง dialog ให้ยืนยันการบันทึก
 * หากยืนยันจะส่งข้อมูลไปบันทึกที่ api
 * หากยกเลิกจะกลับไปหน้าฟอร์ม
 */
function onSubmit() {
  dialogConfirm($q, async () => {
    showLoader();
    await http
      .put(config.API.listResultById(id.value), formData)
      .then(async () => {
        await props.fetchData();
        isSave.value = false;
        success($q, "บันทึกข้อมูลสำเร็จ");
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

async function fetchDatadetail() {
  formData.resultDescription = props.data.resultDescription;
}

function inputEdit(val: boolean) {
  return {
    "full-width cursor-pointer ": val,
    "full-width cursor-pointer inputgreen": !val,
  };
}

/** ฟังก์ชั่นเช็คการแก้ไขฟอร์มแล้วไม่ได้กดบันทึก */
function changeFormData() {
  isSave.value = true;
}

/**เมื่อเริ่มโหลดหน้า
 * ส่งข้อมูลจำลองไปยัง store
 */
function uploadFile() {
  /** uploadFile */
  const Data = new FormData();
  Data.append("file", formData.file);
  showLoader();
  http
    .put(config.API.upLoadFileResult(id.value), Data)
    .then(async () => {
      await props.fetchData();
      countNum.value = 2;
      success($q, "อัปโหลดไฟล์สำเร็จ");
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      hideLoader();
      formData.file = null;
    });
}

/** ลบไฟล์ */
function deleteFile(id: string) {
  dialogRemove($q, () => confirmDelete(id));
}

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

/** เปิดรายละเอียด */
function openDetial(id: string) {
  personalId.value = id;
  modalHistory.value = true;
}

/** เปิดรายละเอียด */
function onclickViewinfo(id: string, type: string) {
  modalPersonal.value = true;
  personId.value = id;
  isEmpType.value = type;
}

function updatemodalPersonal(modal: boolean) {
  modalPersonal.value = modal;
}

function onFault(data: any) {
  idRow.value = data.id;
  nameFault.value = data.name;
  modalFault.value = true;
  personalId.value = data.personId;
  remark.value = data.remark ?? "";
  if (data.offense !== null) {
    checkValue.value = JSON.parse(data.offense);
  } else {
    checkValue.value = JSON.parse(JSON.stringify(mainStore.checkValueFaultT));
  }
}

function close() {
  idRow.value = "";
  modalFault.value = false;
  personalId.value = "";
  remark.value = "";
  checkValue.value = JSON.parse(JSON.stringify(mainStore.checkValueFaultT));
}

function onFaultSubmit() {
  if (checkValue.value.some((item) => item.value)) {
    dialogConfirm($q, () => {
      showLoader();
      http
        .put(config.API.disciplineFault(idRow.value), {
          offense: JSON.stringify(checkValue.value),
          remark: remark.value,
        })
        .then(async () => {
          await props.fetchData();
          success($q, "ระบุฐานความผิด สำเร็จ");
          close();
        })
        .catch((e) => {
          messageError($q, e);
        })
        .finally(() => {
          hideLoader();
        });
    });
  } else {
    dialogMessageNotify($q, "กรุณาเลือกอย่างน้อย 1 มาตรา");
  }
}

/**
 * เช็คข้อมูลจาก props
 * เมื่อมีข้อมูล
 * เก็บข้อมูลลง formData
 */
watch(
  () => props.data,
  async () => {
    if (countNum.value === 1) {
      respondentType.value = props.data.respondentType;
      formData.oc = props.data.resultOc;
      formData.disciplineType = props.data.resultDisciplineType;
      formData.titleType = props.data.resultTitleType;
      formData.disciplineDisciplinary_DocResults =
        props.data.disciplineDisciplinary_DocResults;
      formData.year = props.data.resultYear ?? 0;
      mainStore.rowsAdd = props.data.persons;
      await fetchDatadetail();
      await getActive();

      organizationId.value = props.data.organizationId;
      organizationName.value = props.data.organization;
      organization.value = {
        id: props.data.organizationId,
        name: props.data.organization,
      };
    } else if (countNum.value === 2) {
      formData.disciplineDisciplinary_DocResults =
        props.data.disciplineDisciplinary_DocResults;
    }
  }
);
</script>

<template>
  <div class="row col-12 bg-white">
    <div v-if="isSave" class="col-12">
      <q-banner
        inline-actions
        bordered
        rounded
        class="bg-red-1 text-red border-orange q-ma-md"
      >
        <q-icon name="mdi-information-outline" size="20px" /> แจ้งเตือน
        ยังไม่ได้บันทึกข้อมูล
      </q-banner>
      <q-separator />
    </div>

    <q-form
      greedy
      @submit.prevent
      @validation-success="onSubmit"
      class="col-12 row"
    >
      <div class="col-12 row">
        <div class="col-sm-12 col-md-9 row no-wrap">
          <div class="col-12 q-pa-md">
            <div class="row col-12 q-col-gutter-md">
              <div class="col-xs-12 col-sm-4">
                <q-select
                  readonly
                  for="SelectrespondentType"
                  v-model="respondentType"
                  ref="respondentTypeRef"
                  dense
                  outlined
                  label="ผู้ถูกร้องเรียน"
                  option-value="id"
                  option-label="name"
                  emit-value
                  use-input
                  map-options
                  hide-bottom-space
                  :options="dataStore.complainantoptions"
                  @update:model-value="selectComplainant(respondentType)"
                  @filter="(inputValue: any,
                doneFn: Function) => dataStore.filterSelector(inputValue, doneFn, 'filterrespondentType'
                )"
                >
                  <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-xs-12 col-sm-4"
                v-if="respondentType === 'ORGANIZATION'"
                id="organizationId"
              >
                <q-select
                  readonly
                  for="inputOffice"
                  name="organizationId"
                  ref="organizationIdRef"
                  dense
                  hide-bottom-space
                  outlined
                  option-label="name"
                  option-value="id"
                  map-options
                  v-model="organization"
                  :options="organizationOption"
                  label="หน่วยงานที่ถูกร้องเรียน"
                />
              </div>
              <div class="row col-12" v-if="respondentType === 'PERSON'">
                <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"
                  >
                    ผู้ถูกร้องเรียน
                  </div>
                  <div class="col-12"><q-separator /></div>
                  <div class="col-xs-12 q-pa-sm">
                    <d-table
                      ref="table"
                      :columns="mainStore.columnsRespondent?.filter((item:any)=>item.name !== 'isSend' && item.name !== 'remarkReject' && item.name !== 'disciplineRejectDoc')"
                      :rows="mainStore.rowsAdd"
                      row-key="idcard"
                      flat
                      bordered
                      :paging="true"
                      dense
                      class="custom-header-table"
                      :visible-columns="mainStore.visibleColumnsRespondent"
                    >
                      <template v-slot:header="props">
                        <q-tr :props="props">
                          <q-th auto-width></q-th>
                          <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">
                          <td>
                            <q-btn
                              dense
                              flat
                              round
                              color="edit"
                              icon="edit"
                              @click="onFault(props.row)"
                            >
                              <q-tooltip>ระบุฐานความผิด</q-tooltip>
                            </q-btn>
                            <q-btn
                              dense
                              flat
                              round
                              color="info"
                              icon="mdi-eye"
                              @click="
                                onclickViewinfo(
                                  props.row.personId,
                                  props.row.profileType
                                )
                              "
                            >
                              <q-tooltip>ดูข้อมูลในทะเบียนประวัติ</q-tooltip>
                            </q-btn>
                            <q-btn
                              dense
                              flat
                              round
                              color="deep-purple"
                              icon="mdi-history"
                              @click="openDetial(props.row.personId)"
                            >
                              <q-tooltip>ประวัติ</q-tooltip>
                            </q-btn>
                          </td>
                          <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 === 'organization'"
                              class="table_ellipsis"
                            >
                              {{ props.row.organization }}
                            </div>
                            <div v-else-if="col.name === 'salary'">
                              {{
                                props.row.salary
                                  ? props.row.salary.toLocaleString()
                                  : "0"
                              }}
                            </div>
                            <div v-else-if="col.name === 'profileType'">
                              {{
                                props.row.profileType
                                  ? mainStore.convertType(props.row.profileType)
                                  : "-"
                              }}
                            </div>
                            <div v-else>
                              {{ col.value ?? "-" }}
                            </div>
                          </q-td>
                        </q-tr>
                      </template>
                    </d-table>
                  </div>
                </q-card>
              </div>
              <div class="col-12">
                <q-input
                  :readonly="checkRoutePermisson"
                  :class="inputEdit(isReadonly)"
                  type="textarea"
                  dense
                  outlined
                  ref="detailRef"
                  v-model="formData.resultDescription"
                  for="#detail"
                  label="สรุปผลการพิจารณา"
                  hide-bottom-space
                  @update:model-value="changeFormData()"
                />
              </div>
              <div class="col-3">
                <q-input
                  :readonly="checkRoutePermisson"
                  v-model="formData.disciplineType"
                  dense
                  :class="inputEdit(isReadonly)"
                  outlined
                  label="ประเภทวินัย"
                />
              </div>
              <div class="col-3">
                <q-input
                  :readonly="checkRoutePermisson"
                  v-model="formData.titleType"
                  dense
                  outlined
                  :class="inputEdit(isReadonly)"
                  label="ประเภทของเรื่อง"
                />
              </div>
              <div class="col-4">
                <q-input
                  :readonly="checkRoutePermisson"
                  v-model="formData.oc"
                  dense
                  outlined
                  :class="inputEdit(isReadonly)"
                  label="หน่วยงาน/ส่วนราชการ"
                />
              </div>
              <div class="col-2">
                <datepicker
                  v-model="formData.year"
                  class="col-2"
                  :locale="'th'"
                  autoApply
                  :readonly="checkRoutePermisson"
                  year-picker
                  :enableTimePicker="false"
                >
                  <template #year="{ year }">{{ year + 543 }}</template>
                  <template #year-overlay-value="{ value }">{{
                    parseInt(value + 543)
                  }}</template>
                  <template #trigger>
                    <q-input
                      dense
                      :class="inputEdit(isReadonly)"
                      :readonly="checkRoutePermisson"
                      outlined
                      :model-value="
                        formData.year === 0 ? null : Number(formData.year) + 543
                      "
                      :label="`${'ปีงบประมาณ'}`"
                    >
                      <template v-slot:prepend>
                        <q-icon
                          name="event"
                          class="cursor-pointer"
                          style="color: var(--q-primary)"
                        >
                        </q-icon>
                      </template>
                      <template
                        v-if="!checkRoutePermisson && formData.year"
                        v-slot:append
                      >
                        <q-icon
                          name="cancel"
                          @click.stop.prevent="formData.year = 0"
                          class="cursor-pointer"
                        />
                      </template>
                    </q-input>
                  </template>
                </datepicker>
              </div>
            </div>
          </div>
          <div class="row"><q-separator vertical /></div>
        </div>

        <!-- อัปโหลดไฟล์ -->
        <div 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" v-if="!checkRoutePermisson">
                <q-file
                  for="inputFiles"
                  class="col-12"
                  outlined
                  dense
                  v-model="formData.file"
                  @added="uploadFile"
                  label="ไฟล์เอกสารหลักฐาน"
                  hide-bottom-space
                  accept=".pdf,.xlsx,.docx,.png,.jpg"
                  clearable
                >
                  <template v-slot:prepend>
                    <q-icon name="attach_file" color="primary" />
                  </template>
                  <template v-slot:after>
                    <q-btn
                      v-if="formData.file"
                      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.disciplineDisciplinary_DocResults.length > 0"
                class="col-xs-12 row"
              >
                <q-list class="full-width" bordered separator>
                  <q-item
                    v-for="data in formData.disciplineDisciplinary_DocResults"
                    :key="data.id"
                    clickable
                    v-ripple
                  >
                    <q-item-section>{{ data.fileName }}</q-item-section>
                    <q-space />
                    <q-btn
                      size="12px"
                      flat
                      round
                      dense
                      color="blue"
                      icon="mdi-download"
                      @click="
                        downloadRenameFileByLink(data.pathName, data.fileName)
                      "
                      ><q-tooltip>ดาวน์โหลดไฟล์</q-tooltip></q-btn
                    >
                    <q-btn
                      v-if="!checkRoutePermisson"
                      size="12px"
                      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="!checkRoutePermisson"><q-separator /></div>
        <div class="row col-12 q-pa-sm" v-if="!checkRoutePermisson">
          <q-space />
          <q-btn
            for="ButtonOnSubmit"
            id="formSubmit"
            color="secondary"
            label="บันทึก"
            type="submit"
            ><q-tooltip>บับทึกข้อมูล</q-tooltip></q-btn
          >
        </div>
      </div>
    </q-form>
  </div>

  <q-dialog v-model="modalFault" persistent>
    <q-card class="col-12" style="width: 40vw">
      <q-form greedy @submit.prevent @validation-success="onFaultSubmit">
        <DialogHeader
          :tittle="`ระบุฐานความผิดของ ${nameFault}`"
          :close="close"
        />
        <q-separator />

        <q-card-section class="scroll" style="max-height: 70vh">
          <div class="row q-col-gutter-sm">
            <div class="col-12">
              <q-card
                bordered
                flat
                style="max-height: 500px; overflow-y: scroll"
                class="q-pa-sm"
              >
                <div
                  v-for="(items, index) in checkValue"
                  :class="`full-width `"
                  :key="items.id"
                >
                  <div
                    :class="`row border_bottom q-py-xs ${
                      items.subId !== 0
                        ? ''
                        : checkValue.some((i) => i.subId === items.id)
                        ? 'bg-grey-2'
                        : 'bg-grey-3'
                    }`"
                    :style="index == 0 ? 'border-top: 1px solid #d8d8d8;' : ''"
                  >
                    <div class="col-1 text-center">
                      <q-checkbox
                        v-if="items.status_select == 1"
                        v-model="items.value"
                        dense
                        :true-value="true"
                        :false-value="false"
                      />
                    </div>
                    <div
                      :class="items.subId == 0 ? `col-11` : `col-11 q-pl-lg`"
                    >
                      {{ items.title }}
                    </div>
                  </div>
                </div>
                <!-- <div class="row">
                  <div class="col-1">
                    <q-checkbox
                      v-model="checkValue"
                      dense
                      :true-value="true"
                      :false-value="false"
                    />
                  </div>
                  <div class="col-11"></div>
                </div> -->
              </q-card>
            </div>
            <div class="col-12">
              <q-input
                label="หมายเหตุ"
                v-model="remark"
                outlined
                dense
                type="textarea"
              >
              </q-input>
            </div>
          </div>
        </q-card-section>
        <q-separator />

        <q-card-actions align="right">
          <q-btn label="บันทึก" color="secondary" type="submit"
            ><q-tooltip>บันทึกข้อมูล</q-tooltip></q-btn
          >
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>

  <PopupPersonal
    :modal="modalPersonal"
    :id="personId"
    :type="isEmpType"
    @update:modal="updatemodalPersonal"
  />

  <DialogHistory v-model:modal="modalHistory" v-model:person-id="personalId" />
</template>

<style scoped>
.border_bottom {
  border-bottom: 1px solid #d8d8d8;
  border-radius: 0;
  border-left: 1px solid #d8d8d8;
  border-right: 1px solid #d8d8d8;
}
</style>
