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

import config from "@/app.config";
import http from "@/plugins/http";
import { useRouter } from "vue-router";
import { useCounterMixin } from "@/stores/mixin";
import { useRoute } from "vue-router";
import { calculateFiscalYear } from "@/utils/function";

import type {
  DataOption,
  typeOp,
  NewPagination,
  tableType,
} from "@/modules/14_KPI/interface/index/Main";

import DialogHeader from "@/components/DialogHeader.vue";
import PopupPersonal from "@/components/Dialogs/PopupPersonalNew.vue";

const $q = useQuasar();
const router = useRouter();
const route = useRoute();
const mixin = useCounterMixin();
const {
  showLoader,
  hideLoader,
  messageError,
  dialogConfirm,
  dialogMessageNotify,
  findOrgName,
} = mixin;

const total = ref<number>(0);
const maxPage = ref<number>(1);
const searchRules = ref<boolean>(false);
const selected = ref<any[]>([]);
const personId = ref<string>("");
const modalPersonal = ref<boolean>(false);
const rows = ref<tableType[]>([]);
const type = ref<string>("citizenId");
const search = ref<string>("");
const typeOps = ref<typeOp[]>([
  { id: "citizenId", name: "เลขประจำตัวประชาชน" },
  { id: "fullName", name: "ชื่อ-นามสกุล" },
]);

const modalDialog = defineModel<boolean>("modal", { required: true });
const yearDialog = ref<number | any>(calculateFiscalYear(new Date())); //ปีงบประมาณ
const roundDialgOp = ref<DataOption[]>([]);
const isRoundClose = ref<boolean>(false);

const formRound = reactive({
  kpiPeriodId: { id: "", name: "", isClosed: false },
  profileId: "",
  prefix: "",
  firstName: "",
  lastName: "",
  evaluatorId: "",
  commanderId: "",
  commanderHighId: "",
  position: "",
  posLevelName: "",
  posTypeName: "",
  posExecutiveName: "",
});

const FILTER_TYPES = {
  EVALUATOR: "evaluatorIdOp",
  COMMANDER: "commanderIdOp",
  COMMANDER_HIGH: "commanderHighOp",
} as const;

const evaluatorIdOp = ref<DataOption[]>([]);
const commanderIdOp = ref<DataOption[]>([]);
const commanderHighOp = ref<DataOption[]>([]);

const evaluatorIdMainOp = ref<DataOption[]>([]);
const commanderIdMainOp = ref<DataOption[]>([]);
const commanderHighMainOp = ref<DataOption[]>([]);

/** หัวข้อที่เเสดงในตารางผู้ถูกร้องเรียน */
const visibleColumnsRespondent = ref<string[]>([
  "no",
  // "idcard",
  "name",
  // "posNo",
  "position",
  "positionType",
  // "positionLevel",
  // "salary",
  "organization",
]);

const query = reactive({
  page: 1,
  pageSize: 10,
});
const columnsRespondent = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: false,
    field: (row) =>
      (query.page - 1) * query.pageSize + rows.value.indexOf(row) + 1,
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "name",
    align: "left",
    label: "ชื่อ-นามสกุล",
    sortable: true,
    field: "name",
    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",
  },
  {
    name: "positionType",
    align: "left",
    label: "ตำแหน่งประเภท",
    sortable: true,
    field: "positionType",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "organization",
    align: "left",
    label: "สังกัด",
    sortable: true,
    field: "organization",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);

/** ปิด popup และ clear ค่า */
function onCloseDialog() {
  modalDialog.value = false;
  formRound.kpiPeriodId = { id: "", name: "", isClosed: false };
  yearDialog.value = calculateFiscalYear(new Date());
  rows.value = [];
  formRound.evaluatorId = "";
  formRound.commanderId = "";
  formRound.commanderHighId = "";
  selected.value = [];
  search.value = "";
  type.value = "citizenId";
  roundDialgOp.value = [];
  evaluatorIdMainOp.value = [];
  commanderIdMainOp.value = [];
  commanderHighMainOp.value = [];
  isRoundClose.value = false;
}

/** ดึงข้อมูลตามรอบการประเมิน */
function fetchRoundOption() {
  showLoader();
  http
    .get(
      config.API.kpiPeriod +
        `?page=${1}&pageSize=${10}&keyword=${""}&year=${yearDialog.value}`
    )
    .then((res) => {
      const data = res.data.result.data;
      const list = data.map((e: any) => ({
        id: e.id,
        name:
          e.durationKPI === "OCT"
            ? "รอบที่ 2 ตุลาคม"
            : e.durationKPI === "APR"
            ? "รอบที่ 1 เมษายน"
            : "",
        isClosed: !e.isActive,
      }));

      roundDialgOp.value = list;
      formRound.kpiPeriodId = { id: "", name: "", isClosed: false };
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * ฟิลเตอร์ตาม input
 * @param val ค่าจาก input
 * @param update function Quasar
 * @param refData เเยกประเภท
 */
function filterOption(val: string, update: Function, refData: string) {
  const filterConfig = {
    [FILTER_TYPES.EVALUATOR]: {
      sourceData: evaluatorIdMainOp.value,
      targetRef: evaluatorIdOp,
      excludeIds: [formRound.commanderId, formRound.commanderHighId],
    },
    [FILTER_TYPES.COMMANDER]: {
      sourceData: commanderIdMainOp.value,
      targetRef: commanderIdOp,
      excludeIds: [formRound.evaluatorId, formRound.commanderHighId],
    },
    [FILTER_TYPES.COMMANDER_HIGH]: {
      sourceData: commanderHighMainOp.value,
      targetRef: commanderHighOp,
      excludeIds: [formRound.evaluatorId, formRound.commanderId],
    },
  };

  const config = filterConfig[refData as keyof typeof filterConfig];

  if (!config) return;

  // กรองข้อมูลโดยเอา excludeIds ออก
  const filteredData = config.sourceData.filter(
    (item: DataOption) => !config.excludeIds.includes(item.id)
  );

  update(() => {
    config.targetRef.value = filteredData.filter((item: DataOption) =>
      item.name.toLowerCase().includes(val.toLowerCase())
    );
  });
}

/** เช็ครอบการประเมินที่ปิดรอบ */
function checkClosed() {
  isRoundClose.value = formRound.kpiPeriodId.isClosed;
}

/** ค้นหาตัวชี้วัดตาม ค่า input */
async function searchInput(check: boolean) {
  selected.value = [];
  yearDialog.value = calculateFiscalYear(new Date());
  formRound.kpiPeriodId = { id: "", name: "", isClosed: false };
  formRound.evaluatorId = "";
  formRound.commanderId = "";
  formRound.commanderHighId = "";
  if (check) {
    searchRules.value = check;

    showLoader();
    const body = {
      fieldName: type.value,
      keyword: search.value.trim(),
      system: (route.meta?.Key as string) || undefined,
    };
    await http
      .post(
        config.API.orgSearchPersonal() +
          `?page=${query.page}&pageSize=${query.pageSize}`,
        body
      )
      .then((res) => {
        const data = res.data.result;
        maxPage.value = Math.ceil(data.total / query.pageSize);
        total.value = data.total;

        rows.value = data.data;
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      });
  }
  setTimeout(() => {
    searchRules.value = false;
  }, 100);
}

/** update เมื่อเปลี่ยน option */
function updateSelect() {
  search.value = "";
}

/** ดึงข้อมูล ผู้ประเมิน */
function getOrgOp(check: boolean, id: string) {
  yearDialog.value = calculateFiscalYear(new Date());
  formRound.kpiPeriodId = { id: "", name: "", isClosed: false };
  formRound.evaluatorId = "";
  formRound.commanderId = "";
  formRound.commanderHighId = "";

  if (check == false) {
    http
      .get(config.API.Kpiorg + `/${id}`)
      .then((res) => {
        const data = res.data.result;
        evaluatorIdMainOp.value = data.caregiver.map((i: any) => ({
          id: i.id,
          name: `${i.prefix ? i.prefix : ""}${i.firstName ? i.firstName : ""} ${
            i.lastName ? i.lastName : ""
          }`,
        }));
        commanderIdMainOp.value = data.commander.map((i: any) => ({
          id: i.id,
          name: `${i.prefix ? i.prefix : ""}${i.firstName ? i.firstName : ""} ${
            i.lastName ? i.lastName : ""
          }`,
        }));
        commanderHighMainOp.value = data.chairman.map((i: any) => ({
          id: i.id,
          name: `${i.prefix ? i.prefix : ""}${i.firstName ? i.firstName : ""} ${
            i.lastName ? i.lastName : ""
          }`,
        }));
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(() => {});
  } else {
    evaluatorIdMainOp.value = [];
    commanderIdMainOp.value = [];
    commanderHighMainOp.value = [];
  }
}

/** บันทึกข้อมูล */
function onSubmit() {
  if (selected.value.length == 0) {
    dialogMessageNotify($q, "กรุณาเลือกรายชื่อผู้ประเมิน");
  } else {
    const dataProfile = selected.value[0];
    dialogConfirm($q, () => {
      showLoader();
      http
        .post(config.API.kpiEvaluationUser, {
          kpiPeriodId: formRound.kpiPeriodId.id,
          profileId: dataProfile.id,
          evaluatorId: formRound.evaluatorId,
          commanderId:
            formRound.commanderId == "" ? null : formRound.commanderId,
          commanderHighId:
            formRound.commanderHighId == "" ? null : formRound.commanderHighId,
        })
        .then((res) => {
          const id = res.data.result;
          redirectViewDetail(id);
          onCloseDialog();
        })
        .catch((err) => {
          messageError($q, err);
        })
        .finally(() => {
          hideLoader();
        });
    });
  }
}

/** เปิด/ปิด popup  */
function updatemodalPersonal(modal: boolean) {
  modalPersonal.value = modal;
}

/** route ไปหน้ารายละเอียด */
function redirectViewDetail(id: string) {
  router.push(`/KPI-list/${id}`);
}

/**
 * function อัปเดท paging
 * @param initialPagination ข้อมูล pagination
 */
async function updatePagination(initialPagination: NewPagination) {
  query.page = 1;
  query.pageSize = initialPagination.rowsPerPage;
}

/**
 * class input
 * @param val
 */
function classInput(val: boolean) {
  return {
    "full-width cursor-pointer ": val,
    "full-width cursor-pointer inputgreen": !val,
  };
}

watch(
  () => modalDialog.value,
  (n) => {
    if (n == true) {
      fetchRoundOption();
    }
  }
);

watch(
  () => query.pageSize,
  () => {
    searchInput(true);
  }
);
</script>
<template>
  <q-dialog v-model="modalDialog" persistent>
    <q-card :style="$q.screen.gt.xs ? 'min-width: 90vw' : 'width: 100vw'">
      <q-form greedy @submit.prevent @validation-success="onSubmit">
        <DialogHeader :tittle="'สร้างแบบประเมินผลฯ'" :close="onCloseDialog" />
        <q-separator />
        <q-card-section class="q-pa-none scroll" style="max-height: 80vh">
          <div class="row q-col-gutter-sm">
            <!-- รายชื่อ -->
            <div class="col-12 col-md-9">
              <div class="row q-pa-md q-col-gutter-sm">
                <div class="col-12 col-sm-6 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-6 col-md-9">
                  <q-input
                    v-model="search"
                    outlined
                    hide-bottom-space
                    dense
                    label="คำค้น"
                    @keydown.enter.prevent="(query.page = 1), searchInput(true)"
                  >
                    <template v-slot:after>
                      <q-btn
                        outline
                        color="primary"
                        icon="search"
                        label="ค้นหา"
                        class="full-width q-py-sm q-px-md"
                        @click="(query.page = 1), searchInput(true)"
                      >
                      </q-btn>
                    </template>
                  </q-input>
                </div>
                <div class="col-12 q-pt-sm">
                  <d-table
                    ref="table"
                    :columns="columnsRespondent"
                    :rows="rows"
                    row-key="id"
                    flat
                    bordered
                    selection="single"
                    :rows-per-page-options="[10, 25, 50, 100]"
                    v-model:selected="selected"
                    :paging="true"
                    dense
                    :visible-columns="visibleColumnsRespondent"
                    @update:pagination="updatePagination"
                  >
                    <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" class="cursor-pointer">
                        <q-td>
                          <q-checkbox
                            keep-color
                            color="primary"
                            dense
                            v-model="props.selected"
                            @click="getOrgOp(props.selected, props.row.id)"
                          />
                        </q-td>
                        <q-td
                          v-for="col in props.cols"
                          :key="col.name"
                          :props="props"
                        >
                          <div v-if="col.name == 'positionType'">
                            {{
                              props.row.positionTypeName
                                ? props.row.positionTypeName
                                : ""
                            }}{{
                              props.row.positionLevelName
                                ? ` (${props.row.positionLevelName})`
                                : "-"
                            }}
                          </div>
                          <div
                            v-else-if="col.name == 'organization'"
                            class="table_ellipsis"
                          >
                            {{ findOrgName(props.row) }}
                          </div>
                          <div v-else>
                            {{ col.value ?? "-" }}
                          </div>
                        </q-td>
                      </q-tr>
                    </template>
                    <template v-slot:pagination="scope">
                      ทั้งหมด {{ total }} รายการ
                      <q-pagination
                        v-model="query.page"
                        active-color="primary"
                        color="dark"
                        :max="Number(maxPage)"
                        size="sm"
                        boundary-links
                        direction-links
                        :max-pages="5"
                        @update:model-value="searchInput(true)"
                      ></q-pagination>
                    </template>
                  </d-table>
                </div>
              </div>
            </div>

            <!-- form  -->
            <div class="col-12 col-md-3 bg-grey-2">
              <div class="row q-pa-md q-col-gutter-sm">
                <div class="col-12">
                  <datepicker
                    :readonly="selected.length === 0"
                    menu-class-name="modalfix"
                    v-model="yearDialog"
                    :locale="'th'"
                    autoApply
                    year-picker
                    :enableTimePicker="false"
                    @update:model-value="fetchRoundOption()"
                    :class="classInput(false)"
                  >
                    <template #year="{ year }">{{ year + 543 }}</template>
                    <template #year-overlay-value="{ value }">{{
                      parseInt(value + 543)
                    }}</template>
                    <template #trigger>
                      <q-input
                        :disable="selected.length === 0"
                        dense
                        lazy-rules
                        outlined
                        bg-color="white"
                        hide-bottom-space
                        :model-value="!!yearDialog ? yearDialog + 543 : null"
                        :label="`${'ปีงบประมาณ'}`"
                        :rules="[
                      (val:string) =>
                        !!val || `${'กรุณาเลือกปีงบประมาณ'}`,
                    ]"
                      >
                        <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-12">
                  <q-select
                    :disable="selected.length === 0"
                    :class="classInput(false)"
                    :readonly="yearDialog === null"
                    v-model="formRound.kpiPeriodId"
                    outlined
                    label="รอบการประเมิน"
                    dense
                    option-label="name"
                    option-value="id"
                    bg-color="white"
                    :options="roundDialgOp"
                    hide-bottom-space
                    lazy-rules
                    :rules="[
                      (val:string) => !!val || `${'กรุณาเลือกรอบการประเมิน'}`,
                    ]"
                    @update:model-value="checkClosed"
                  />
                </div>

                <div class="col-12">
                  <q-select
                    :disable="selected.length === 0"
                    :class="classInput(false)"
                    v-model="formRound.evaluatorId"
                    outlined
                    label="ผู้ประเมิน"
                    dense
                    option-label="name"
                    option-value="id"
                    :options="evaluatorIdOp"
                    bg-color="white"
                    emit-value
                    map-options
                    hide-bottom-space
                    lazy-rules
                    :rules="[
                  (val:string) =>
                    !!val || `${'กรุณาเลือกผู้ประเมิน'}`,
                ]"
                    use-input
                    hide-selected
                    fill-input
                    @filter="(inputValue:string,
                    doneFn:Function) => filterOption(inputValue, doneFn,'evaluatorIdOp'
                    ) "
                  >
                    <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-12">
                  <q-select
                    :disable="selected.length === 0"
                    :class="classInput(false)"
                    v-model="formRound.commanderId"
                    outlined
                    label="ผู้บังคับบัญชาเหนือขึ้นไป"
                    dense
                    option-label="name"
                    bg-color="white"
                    option-value="id"
                    :options="commanderIdOp"
                    emit-value
                    map-options
                    use-input
                    hide-selected
                    fill-input
                    @filter="(inputValue:string,
                    doneFn:Function) => filterOption(inputValue, doneFn,'commanderIdOp'
                    ) "
                  >
                    <template v-if="formRound.commanderId" v-slot:append>
                      <q-icon
                        name="cancel"
                        @click.stop.prevent="formRound.commanderId = ''"
                        class="cursor-pointer"
                      />
                    </template>
                    <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-12">
                  <q-select
                    :disable="selected.length === 0"
                    :class="classInput(false)"
                    v-model="formRound.commanderHighId"
                    outlined
                    label="ผู้บังคับบัญชาเหนือขึ้นไปอีกชั้นหนึ่ง"
                    dense
                    bg-color="white"
                    option-label="name"
                    option-value="id"
                    :options="commanderHighOp"
                    emit-value
                    map-options
                    use-input
                    hide-selected
                    fill-input
                    @filter="(inputValue:string,
                    doneFn:Function) => filterOption(inputValue, doneFn,'commanderHighOp'
                    ) "
                  >
                    <template v-if="formRound.commanderHighId" v-slot:append>
                      <q-icon
                        name="cancel"
                        @click.stop.prevent="formRound.commanderHighId = ''"
                        class="cursor-pointer"
                      />
                    </template>
                    <template v-slot:no-option>
                      <q-item>
                        <q-item-section class="text-grey">
                          ไม่มีข้อมูล
                        </q-item-section>
                      </q-item>
                    </template>
                  </q-select>
                </div>
              </div>
            </div>
          </div>
        </q-card-section>
        <q-separator />
        <q-card-actions align="right" class="bg-white text-teal">
          <q-space />

          <div v-if="isRoundClose" class="text-red q-px-sm">
            รอบการประเมินนี้ปิดแล้ว
          </div>
          <q-btn
            :disable="isRoundClose || selected.length === 0"
            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"
    @update:modal="updatemodalPersonal"
  />
</template>
