<script setup lang="ts">
import { ref, reactive, watch } from "vue";
import http from "@/plugins/http";
import config from "@/app.config";
import { useQuasar } from "quasar";
import { useRouter, useRoute } from "vue-router";
import { useCounterMixin } from "@/stores/mixin";
import { useDisciplineResultStore } from "@/modules/11_discipline/store/ResultStore";
import { useDisciplineMainStore } from "@/modules/11_discipline/store/main";
import DialogHistory from "@/modules/11_discipline/components/4_Result/DialogHistory.vue";
import PopupPersonal from "@/components/Dialogs/PopupPersonalNew.vue";

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

const modalPersonal = ref<boolean>(false);
const personId = ref<string>("");

const countNum = ref<number>(1);
const mainStore = useDisciplineMainStore();
const modalPerson = ref<boolean>(false);
const isReadonly = ref<boolean>(false); // อ่านได้อย่างเดียว
const dataStore = useDisciplineResultStore();
const mixin = useCounterMixin();
const {
  hideLoader,
  dialogConfirm,
  success,
  messageError,
  showLoader,
  dialogRemove,
  downloadRenameFileByLink
} = mixin;
const router = useRouter();
const route = useRoute();
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>("");

/** รับ 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: new Date().getFullYear(),
});

/** 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.orgByid(activeId))
    .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 () => {
    await http
      .put(config.API.listResultById(id.value), formData)
      .then(() => {
        isSave.value = false;
        success($q, "บันทึกข้อมูลสำเร็จ");
        props.fetchData();
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(async () => {});
  });
}

async function fetchDatadetail() {
  formData.resultDescription = props.data.resultDescription;
}
/**
 * เช็คข้อมูลจาก 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;
    }
  }
);

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((res) => {
      success($q, "อัปโหลดไฟล์สำเร็จ");
      countNum.value = 2;
      props.fetchData();
      // router.push(`/discipline/complaints`);
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      hideLoader();
      formData.file = null;
    });
}

function downloadFile(link: string) {
  window.open(link, "_blank");
}

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((res) => {
      success($q, `ลบไฟล์สำเร็จ`);
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      props.fetchData();
    });
}

function openDetial(id: string) {
  personalId.value = id;
  modalHistory.value = true;
}

function closeDetail() {
  modalHistory.value = false;
  personalId.value = "";
}

function onclickViewinfo(id: string) {
  modalPersonal.value = true;
  personId.value = id;
}

function updatemodalPersonal(modal: boolean) {
  modalPersonal.value = modal;
}
</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"
                      :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="info"
                              icon="mdi-eye"
                              @click="onclickViewinfo(props.row.personId)"
                            >
                              <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()
                                  : ""
                              }}
                            </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
                  menu-class-name="modalfix"
                  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"
              v-if="!checkRoutePermisson"
            >
              <div class="col-12 row">
                <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="add"
                      icon="mdi-upload"
                      @click="uploadFile"
                      ><q-tooltip>อัปโหลดไฟล์</q-tooltip></q-btn
                    >
                  </template>
                </q-file>
              </div>
            </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-outline"
                    @click="deleteFile(data.id)"
                    ><q-tooltip>ลบไฟล์</q-tooltip></q-btn
                  >
                </q-item>
              </q-list>
            </div>
            <div class="col-12 q-pa-sm" v-else>
              <q-card class="q-pa-md" bordered> ไม่มีรายการเอกสาร </q-card>
            </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>

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

  <DialogHistory
    :modal="modalHistory"
    :close="closeDetail"
    :person-id="personalId"
  />
</template>
