<script setup lang="ts">
import { useCounterMixin } from "@/stores/mixin";
import { useQuasar } from "quasar";
import type { QTableProps } from "quasar";
import config from "@/app.config";
import http from "@/plugins/http";
import { reactive, ref, onMounted, watch } from "vue";
import DialogHeader from "@/components/DialogHeader.vue";
import PopupPersonal from "@/components/Dialogs/PopupPersonalNew.vue";
import type {
  DataOption,
  typeOp,
  NewPagination,
  tableType,
  FormData,
} from "@/modules/14_KPI/interface/index/Main";
import { useRouter } from "vue-router";

const searchRules = ref<boolean>(false);
const selected = ref<any[]>([]);
const personId = ref<string>("");
const modalPersonal = ref<boolean>(false);
const searchRef = ref<any>(null);
const rows = ref<tableType[]>([]);
const type = ref<string>("citizenId");
const search = ref<string>("");
const typeOps = ref<typeOp[]>([
  { id: "citizenId", name: "เลขประจำตัวประชาชน" },
  { id: "firstname", name: "ชื่อ" },
  { id: "lastname", name: "นามสกุล" },
]);
const $q = useQuasar();
const mixin = useCounterMixin();
const {
  showLoader,
  hideLoader,
  messageError,
  date2Thai,
  dialogConfirm,
  dialogMessageNotify,
  findOrgName,
  findPosMasterNo,
} = mixin;

const router = useRouter();

const modalDialog = defineModel<boolean>("modal", { required: true });
const yearDialog = ref<number | any>(new Date().getFullYear());
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 evaluatorIdOp = ref<DataOption[]>([]);
const commanderIdOp = ref<DataOption[]>([]);
const commanderHighOp = ref<DataOption[]>([]);

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

/**
 * ข้อมูลทั้งก้อน form
 */
const formData = reactive<FormData>({
  personalId: "",
  prefix: "",
  firstname: "",
  lastname: "",
  position: "",
  phone: "",
  email: "",
  qualification: "",
});

function onCloseDialog() {
  modalDialog.value = false;
  formRound.kpiPeriodId = { id: "", name: "", isClosed: false };
  yearDialog.value = new Date().getFullYear();
  rows.value = [];
  formRound.evaluatorId = "";
  formRound.commanderId = "";
  formRound.commanderHighId = "";
  selected.value = [];
  search.value = "";
  type.value = "citizenId";
}
/** หัวข้อที่เเสดงในตารางผู้ถูกร้องเรียน */
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",
  },
]);

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();
    });
}

function filterOption(val: any, update: Function, refData: string) {
  switch (refData) {
    case "evaluatorIdOp":
      update(() => {
        evaluatorIdOp.value = evaluatorIdMainOp.value.filter(
          (v: any) => v.name.indexOf(val) > -1
        );
      });
      break;
    case "commanderIdOp":
      update(() => {
        commanderIdOp.value = commanderIdMainOp.value.filter(
          (v: any) => v.name.indexOf(val) > -1
        );
      });
      break;
    case "commanderHighOp":
      update(() => {
        commanderHighOp.value = commanderHighMainOp.value.filter(
          (v: any) => v.name.indexOf(val) > -1
        );
      });
      break;
    default:
      break;
  }
}

function checkClosed() {
  isRoundClose.value = formRound.kpiPeriodId.isClosed;
}

const total = ref<number>(0);
const maxPage = ref<number>(1);

async function searchInput(check: boolean) {
  if (check) {
    searchRules.value = check;
    searchRef.value.validate();
    if (!searchRef.value.hasError) {
      showLoader();
      const body = {
        fieldName: type.value,
        keyword: search.value,
      };
      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) {
  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();
        });
    });
  }
}

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

function redirectViewDetail(id: string) {
  router.push(`/KPI-list/${id}`);
}

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

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

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
                    ref="searchRef"
                    v-model="search"
                    outlined
                    clearable
                    hide-bottom-space
                    dense
                    label="คำค้น"
                    :rules="[
                      (val) => !!val || !searchRules || `กรุณากรอกคำค้น`,
                    ]"
                  >
                    <template v-slot:after>
                      <q-btn
                        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>
            <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
                    menu-class-name="modalfix"
                    v-model="yearDialog"
                    :locale="'th'"
                    autoApply
                    year-picker
                    :enableTimePicker="false"
                    @update:model-value="fetchRoundOption()"
                  >
                    <template #year="{ year }">{{ year + 543 }}</template>
                    <template #year-overlay-value="{ value }">{{
                      parseInt(value + 543)
                    }}</template>
                    <template #trigger>
                      <q-input
                        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
                    :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) => !!val.id || `${'กรุณาเลือกรอบการประเมิน'}`,
                    ]"
                    @update:model-value="checkClosed"
                  />
                </div>

                <div class="col-12">
                  <q-select
                    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
                    @filter="(inputValue:any,
                    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
                    v-model="formRound.commanderId"
                    outlined
                    label="ผู้บังคับบัญชาเหนือขึ้นไป"
                    dense
                    option-label="name"
                    bg-color="white"
                    option-value="id"
                    :options="commanderIdOp"
                    emit-value
                    map-options
                    use-input
                    @filter="(inputValue:any,
                    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
                    v-model="formRound.commanderHighId"
                    outlined
                    label="ผู้บังคับบัญชาเหนือขึ้นไปอีกชั้นหนึ่ง"
                    dense
                    bg-color="white"
                    option-label="name"
                    option-value="id"
                    :options="commanderHighOp"
                    emit-value
                    map-options
                    use-input
                    @filter="(inputValue:any,
                    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  class="text-red q-px-sm">
            รอบการประเมินนี้ปิดแล้ว
          </div>
          <q-btn
            :disable="isRoundClose"
            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>
