<script setup lang="ts">
import { ref, watch } from "vue";
import { useQuasar } from "quasar";
import http from "@/plugins/http";
import config from "@/app.config";

import { useCounterMixin } from "@/stores/mixin";
import type { ResponsePreson } from "@/interface/response/listPerson";
import { useDisciplineMainStore } from "@/modules/11_discipline/store/main";

const mainStore = useDisciplineMainStore();

const $q = useQuasar();
const mixin = useCounterMixin();
const { dialogMessageNotify, showLoader, hideLoader } = mixin;

interface typeOp {
  id: string;
  name: string;
}

interface tableType {
  personId: string;
  idcard: string;
  prefix: string;
  firstName: string;
  lastName: string;
  position: string;
  positionLevel: string;
  organization: string;
  salary: string;
  name: string;
}

const rows = ref<tableType[]>([]);
const type = ref<string>("idcard");
const search = ref<string>("");
const selected = ref<any>([]);

const typeOps = ref<typeOp[]>([
  { id: "idcard", name: "เลขประจำตัวประชาชน" },
  { id: "firstname", name: "ชื่อ" },
  { id: "lastname", name: "นามสกุล" },
]);

/** รับค่ามาจาก หน้าหลัก */
const props = defineProps({
  modal: {
    type: Boolean,
    default: false,
    required: true,
  },
  btnTitle: {
    type: String,
    default: "เพิ่ม",
  },
  title: {
    type: String,
    default: "",
  },
  desc: {
    type: String,
    default: "",
  },
  selectedData: {
    type: Array,
    default: [],
  },
  close: {
    type: Function,
    default: () => console.log("not function"),
    required: true,
  },
  save: {
    type: Function,
    default: () => console.log("not function"),
    required: true,
  },
  selecetSwitch: {
    type: String,
    default: "multiple",
  },
});

/**ส่งค่ากลับหน้าหลัก */
const emit = defineEmits(["returnData"]);

/** ปิด dialog */
async function close() {
  console.log("close");
  props.close();
}

/** เปิด dialog ยืนยัน */
function savePost() {
  if (selected.value.length != 0) {
    // dialogConfirm($q, () => saveData());
    saveData();
  } else {
    dialogMessageNotify($q, "กรุณาเลือกอย่างน้อย 1 รายการ");
  }
}

/** save data หลังจาก ยืนยัน */
function saveData() {
  props.save();
  emit("returnData", selected.value);
}

const searchRef = ref<any>(null);
/** input ค้นหา */
async function searchInput() {
  searchRef.value.validate();
  if (!searchRef.value.hasError) {
    showLoader();
    const body = {
      fieldName: type.value,
      keyword: search.value,
    };
    await http
      .post(config.API.orgSearchPersonal(), body)
      .then((res) => {
        const data = res.data.result;
        const list = data.map((e: any) => ({
          personId: e.id,
          idcard: e.idcard,
          prefix: e.prefix,
          firstName: e.firstName,
          lastName: e.lastName,
          name: `${e.prefix}${e.firstName}  ${e.lastName}`,
          posNo: e.posNo ?? "-",
          position: e.position ?? "-",
          positionLevel: e.positionLevelName ?? "-",
          salary: e.salary ?? "-",
          organization: e.organization ?? "-",
          phone: e.phone ?? "-",
          email: e.email ?? "-",
          root: e.root,
          rootId: e.rootId,
          rootShortName: e.rootShortName,
          child1: e.child1,
          child1Id: e.child1Id,
          child1ShortName: e.child1ShortName,
          child2: e.child2,
          child2Id: e.child2Id,
          child2ShortName: e.child2ShortName,
          child3: e.child3,
          child3Id: e.child3Id,
          child3ShortName: e.child3ShortName,
          child4: e.child4,
          child4Id: e.child4Id,
          child4ShortName: e.child4ShortName,
          posMasterNo: e.posMasterNo,
          posTypeId: e.posTypeId,
          posTypeName: e.posTypeName,
          posLevelId: e.posLevelId,
          posLevelName: e.posLevelName,
        }));

        rows.value = list;
      })
      .catch((err) => {
        console.log(err);
      })
      .finally(() => {
        hideLoader();
      });
  }
}

/** update เมื่อเปลี่ยน option */
function updateSelect() {
  search.value = "";
}
watch(
  () => props.selectedData,
  () => {
    if (props.selectedData) {
      selected.value = props.selectedData;
    }
  }
);
</script>

<template>
  <q-dialog v-model="props.modal" persistent>
    <q-card style="min-width: 60vw">
      <q-toolbar>
        <q-toolbar-title class="text-subtitle2 text-bold">{{
          props.title
        }}</q-toolbar-title>
        <q-btn
          icon="close"
          unelevated
          round
          dense
          @click="close"
          style="color: #ff8080; background-color: #ffdede"
        />
      </q-toolbar>
      <q-separator />
      <q-card-section class="q-pa-md">
        <div class="row col-12 q-col-gutter-sm items-start">
          <div class="col-12 col-sm-5 col-md-3">
            <q-select
              label="ค้นหาจาก"
              v-model="type"
              :options="typeOps"
              emit-value
              dense
              @update:model-value="updateSelect"
              map-options
              outlined
              option-label="name"
              option-value="id"
            />
          </div>

          <div class="col-12 col-sm-7 col-md-9">
            <q-input
              ref="searchRef"
              v-model="search"
              outlined
              clearable
              dense
              label="คำค้น"
              :rules="[(val) => !!val || `กรุณากรอกคำค้น`]"
            >
              <template v-slot:after>
                <q-btn
                  color="primary"
                  icon="search"
                  label="ค้นหา"
                  outline
                  class="full-width q-py-sm q-px-md"
                  @click="searchInput()"
                >
                </q-btn>
              </template>
            </q-input>
          </div>
        </div>

        <div class="full-width">
          <d-table
            ref="table"
            :columns="mainStore.columnsRespondent"
            :rows="rows"
            row-key="personId"
            flat
            bordered
            :paging="true"
            dense
            class="custom-header-table"
            :visible-columns="mainStore.visibleColumnsRespondent"
            :selection="props.selecetSwitch"
            v-model:selected="selected"
          >
            <template v-slot:header-selection="scope">
              <q-checkbox
                keep-color
                color="primary"
                dense
                v-model="scope.checkBox"
              />
            </template>
            <template v-slot:header="props">
              <q-tr :props="props">
                <q-th class="text-center">
                  <q-checkbox
                    keep-color
                    color="primary"
                    dense
                    v-model="props.selected"
                  />
                </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" class="cursor-pointer">
                <td class="text-center">
                  <q-checkbox
                    keep-color
                    color="primary"
                    dense
                    v-model="props.selected"
                  />
                </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-if="col.name === 'fullName'">
                    {{ props.prefix }}
                  </div>
                  <div v-else-if="col.name === 'salary'">
                    {{ props.row.salary.toLocaleString() }}
                  </div>
                  <div v-else>
                    {{ col.value }}
                  </div>
                </q-td>
              </q-tr>
            </template>
          </d-table>
        </div>
      </q-card-section>
      <q-separator />

      <div class="row justify-end q-px-md q-py-sm items-center">
        <q-btn
          dense
          color="public"
          id="onSubmit"
          class="q-px-md q-py-xs"
          @click="savePost"
        >
          <!-- <q-icon left name="add" /> -->
          <div>{{ props.btnTitle }}</div>
          <!-- icon="mdi-content-save-outline" -->
          <q-tooltip>{{ props.btnTitle }}</q-tooltip>
        </q-btn>
      </div>
    </q-card>
  </q-dialog>
</template>
