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

import http from "@/plugins/http";
import config from "@/app.config";
import { useCounterMixin } from "@/stores/mixin";

import type { QTableProps } from "quasar";
import type {
  requestSendNoti,
  DataCopyOrder,
} from "@/modules/06_retirement/interface/response/Deceased";

import DialogOrgSelectOneStep from "@/components/Dialogs/DialogOrgSelectOneStep.vue";

/** Use */
const router = useRouter();
const route = useRoute();
const $q = useQuasar();
const mixin = useCounterMixin(); //เรียกฟังก์ชันกลาง
const {
  dialogRemove,
  messageError,
  showLoader,
  hideLoader,
  success,
  dialogConfirm,
  onSearchDataTable,
} = mixin;

/** props*/
const props = defineProps({
  next: {
    type: Function,
    default: () => console.log("not function"),
  },
  previous: {
    type: Function,
    default: () => console.log("not function"),
  },
});
const profileId = ref<string>(route.params.id.toString());
const next = () => props.next();

/**ตัวแปร */
const myForm = ref<QForm | null>(null);
const filterRef = ref<QInput>();
const filter = ref<string>("");
const modalSelectOrg = ref<boolean>(false);

const selectedModal = ref<any[]>([]);
const rows = ref<DataCopyOrder[]>([]);
const rowsMain = ref<DataCopyOrder[]>([]);
const editRows = ref<DataCopyOrder[]>([]);

/** selcet OPtion */
const optionSelect = ref<any>([
  { id: 1, name: "อีเมล" },
  { id: 2, name: "กล่องข้อความ" },
]);
/** คอลัมน์ที่แสดง */
const visibleColumns = ref<String[]>([
  "no",
  "idCard",
  "name",
  "position",
  "unit",
  "send",
]);

/** คอลัมน์ */
const columns = ref<QTableProps["columns"]>([
  { name: "no", align: "left", label: "ลำดับ", field: "no", sortable: true },
  {
    name: "idCard",
    align: "left",
    label: "เลขประจำตัวประชาชน",
    field: "idCard",
    sortable: true,
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "name",
    align: "left",
    label: "ชื่อ-นามสกุล",
    field: "name",
    sortable: true,
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "position",
    align: "left",
    label: "ตำแหน่ง",
    field: "position",
    sortable: true,
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "unit",
    align: "left",
    label: "หน่วยงาน",
    field: "unit",
    sortable: true,
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "send",
    align: "left",
    label: "ช่องทางการส่งสำเนา",
    field: "send",
    sortable: true,
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);

/** เรียกข้อมูลจาก api */
async function getData() {
  showLoader();
  await http
    .get(config.API.detailByidDeceased(profileId.value))
    .then(async (res) => {
      const data = await res.data.result;
      let list: DataCopyOrder[] = [];
      data.map((r: any) => {
        let selectCopyOrder = [];
        if (r.isSendMail) {
          selectCopyOrder.push(1);
        }
        if (r.isSendInbox) {
          selectCopyOrder.push(2);
        }

        list.push({
          id: r.id,
          personalId: r.profileId ?? "",
          name: `${r.prefix}${r.firstName} ${r.lastName}`,
          idCard: r.citizenId ?? "",
          position: r.positionName ?? "",
          unit: r.organizationName ?? "-",
          send: "",
          mutiselect: selectCopyOrder,
        });
      });
      if (editRows.value.length > 0) {
        list.map((r: DataCopyOrder) => {
          editRows.value.map((e: DataCopyOrder) => {
            if (r.personalId == e.personalId) {
              r.mutiselect = e.mutiselect;
            }
          });
        });
      }
      rows.value = list;
      rowsMain.value = list;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 *ฟังก์ชั่น Save
 */
async function saveData() {
  showLoader();
  const persons = selectedModal.value.map((item) => ({
    profileId: item.profileId,
  }));
  const dataToSend = { Persons: persons };
  await http
    .put(config.API.detailByidDeceased(profileId.value), dataToSend)
    .then(async (res) => {
      await getData();
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      hideLoader();
    });
}

/**
 * class จัดรูปแบบแสดงระหว่างข้อมูลที่แก้ไขหรือแสดงเฉยๆ
 * @param val ข้อมูล input สำหรับแก้ไขหรือไม่
 */
function getClass(val: boolean) {
  return {
    "full-width inputgreen cursor-pointer": val,
    "full-width cursor-pointer": !val,
  };
}

/**
 * กดปุ่มเพิ่มด้านบน table
 */
function clickAdd() {
  modalSelectOrg.value = true;
  if (myForm.value !== null) {
    myForm.value.reset();
  }
}

/**
 * ลบข้อมูล
 */
function clickDelete(id: string) {
  dialogRemove($q, async () => {
    showLoader();
    await http
      .delete(config.API.detailByidDeceased(id))
      .then(async () => {
        await getData();
        success($q, "ลบข้อมูลสำเร็จ");
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(async () => {
        hideLoader();
      });
  });
}

/**
 * Save ข้อมูล
 */
async function saveDataCopyOrder() {
  if (myForm.value !== null) {
    myForm.value.validate().then(async (result: boolean) => {
      if (result) {
        dialogConfirm(
          $q,
          () => fetchSaveCopyOrder(),
          "ยืนยันการส่งหนังสือเวียน",
          "ต้องการยืนยันการส่งหนังสือเวียนหรือไม่"
        );
      }
    });
  }
}
//อัพเดทข้อมูลหลัง Save
async function fetchSaveCopyOrder() {
  let list: requestSendNoti[] = [];
  rowsMain.value.map((r: DataCopyOrder) => {
    list.push({
      profileId: r.personalId,
      isSendMail: r.mutiselect.includes(1),
      isSendInbox: r.mutiselect.includes(2),
      isSendNotification: true,
    });
  });
  showLoader();
  await http
    .put(config.API.notiDeceased(profileId.value), { Persons: list })
    .then(async () => {
      await getData();
      next();
      success($q, "บันทึกข้อมูลสำเร็จ");
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

function updateData(row: DataCopyOrder) {
  editRows.value.push(row);
}

async function onSearch() {
  rows.value = onSearchDataTable(
    filter.value,
    rowsMain.value,
    columns.value ? columns.value : []
  );
}

/** Hook */
onMounted(async () => {
  await getData();
});
</script>

<template>
  <div class="toptitle text-dark col-12 row items-center">
    <q-btn
      icon="mdi-arrow-left"
      unelevated
      round
      dense
      flat
      color="primary"
      class="q-mr-sm"
      @click="router.push(`/retirement/deceased/${profileId}`)"
    />
    ส่งหนังสือเวียน
  </div>
  <div class="bg-white">
    <div class="q-py-md q-pl-md" style="height: 68vh; overflow-y: scroll">
      <div class="col-12 row q-py-sm items-center">
        <q-btn flat round color="primary" @click="clickAdd" icon="mdi-plus">
          <q-tooltip>เพิ่มข้อมูล</q-tooltip>
        </q-btn>
        <q-space />
        <div class="items-center" style="display: flex">
          <!-- ค้นหาข้อความใน table -->
          <q-input
            standout
            dense
            v-model="filter"
            ref="filterRef"
            outlined
            placeholder="ค้นหา"
            class="q-ml-sm"
            @keydown.enter="onSearch"
          >
            <template v-slot:append>
              <q-icon name="search" />
            </template>
          </q-input>
          <!-- แสดงคอลัมน์ใน table -->
          <q-select
            v-model="visibleColumns"
            :display-value="$q.lang.table.columns"
            multiple
            outlined
            dense
            :options="columns"
            options-dense
            option-value="name"
            map-options
            emit-value
            style="min-width: 140px"
            class="gt-xs q-ml-sm"
          />
        </div>
      </div>
      <q-form ref="myForm">
        <d-table
          :rows="rows"
          :columns="columns"
          :visible-columns="visibleColumns"
          row-key="idCard"
        >
          <template v-slot:header="props">
            <q-tr :props="props">
              <q-th v-for="col in props.cols" :key="col.name" :props="props">
                <span class="text-weight-medium">{{ col.label }}</span>
              </q-th>
              <q-th auto-width />
            </q-tr>
          </template>
          <template v-slot:body="props">
            <q-tr :props="props" class="cursor-pointer">
              <q-td key="no" :props="props">
                {{ props.rowIndex + 1 }}
              </q-td>
              <q-td key="idCard" :props="props">
                {{ props.row.idCard }}
              </q-td>
              <q-td key="name" :props="props">
                {{ props.row.name }}
              </q-td>
              <q-td key="position" :props="props">
                {{ props.row.position }}
              </q-td>
              <q-td key="unit" :props="props">
                {{ props.row.unit }}
              </q-td>
              <q-td key="send" :props="props">
                <q-select
                  :class="getClass(true)"
                  hide-bottom-space
                  multiple
                  :outlined="true"
                  dense
                  lazy-rules
                  v-model="props.row.mutiselect"
                  :rules="[(val:string) => !!val || `${'กรุณาเลือกช่องทางการส่งสำเนา'}`,(val:string) => val.length > 0 || `${'กรุณาเลือกช่องทางการส่งสำเนา'}`]"
                  :label="`${'เลือกช่องทางการส่งสำเนา'}`"
                  emit-value
                  map-options
                  option-label="name"
                  :options="optionSelect"
                  option-value="id"
                  input-debounce="0"
                  color="primary"
                  @update:model-value="() => updateData(props.row)"
                >
                  <template v-slot:no-option>
                    <q-item>
                      <q-item-section class="text-black">
                        ไม่พบข้อมูลที่ค้นหา
                      </q-item-section>
                    </q-item>
                  </template>
                </q-select>
              </q-td>
              <q-td auto-width>
                <q-btn
                  dense
                  size="12px"
                  flat
                  round
                  color="red"
                  @click="clickDelete(props.row.id)"
                  icon="mdi-delete"
                >
                  <q-tooltip>ลบข้อมูล</q-tooltip>
                </q-btn>
              </q-td>
            </q-tr>
          </template>
        </d-table>
      </q-form>
    </div>
    <q-separator />
    <div class="flex justify-end q-pa-sm q-gutter-sm">
      <q-btn
        dense
        unelevated
        label="ส่งหนังสือเวียน"
        color="public"
        @click="saveDataCopyOrder"
        class="q-px-md"
      >
      </q-btn>
    </div>
  </div>

  <DialogOrgSelectOneStep
    v-model:modal="modalSelectOrg"
    :title="'เลือกรายชื่อตามหน่วยงาน'"
    v-model:selectedModal="selectedModal"
    :saveData="saveData"
  />
</template>
