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

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

import type {
  FormAppointData,
  OpfillterTypeSt,
  MemBerType,
  PersonsAppointData,
} from "@/modules/05_placement/interface/request/Main";

import DialogHeader from "@/components/DialogHeader.vue";

const $q = useQuasar(); //ใช้ noti quasar
const route = useRoute();
const router = useRouter();
const mixin = useCounterMixin();
const {
  dialogRemove,
  showLoader,
  hideLoader,
  messageError,
  dialogConfirm,
  success,
} = mixin;
const checkRoutePermisson = ref<boolean>(
  route.name == "probationAppointDetail"
);

const id = ref<string>(route.params.id as string);
const profileId = ref<string>("");
const isSave = ref<boolean>(false);
const isDirector = ref<boolean>(false);
const isAct = ref<boolean>(false);

const topic = ref<string>("");
const status = ref<string>("");
const filterKeyword = ref<string>("");

const rows = ref<PersonsAppointData[]>([]);
const modal = ref<boolean>(false);
const member = ref<string>("");
const selected = ref<MemBerType[]>([]);

const total = ref<number>(0);
const totalList = ref<number>(1);
const pagination = ref({
  sortBy: "createdAt",
  descending: true,
  page: 1,
  rowsPerPage: 10,
});

const countRowLength = computed(() => {
  return selected.value.length + rows.value.length == 4
    ? true
    : selected.value.length == 2
    ? true
    : false;
});

const findPerson = computed(() => {
  const roles = ["chairman", "committee", "caregiver"];
  return roles.every((role) => rows.value.some((row) => row.role === role));
});

const textAlert = computed(() => {
  const roles = [
    { key: "chairman", label: "ประธาน" },
    { key: "committee", label: "ผู้บังคับบัญชา" },
    { key: "caregiver", label: "ผู้ดูแล" },
  ];

  const missingRoles = roles
    .filter((role) => !rows.value.some((row) => row.role === role.key))
    .map((role) => role.label);

  return missingRoles.length > 0
    ? `กรุณาเพิ่มรายชื่อ : ${missingRoles.join(", ")}`
    : "";
});

const optionsTypeMain = ref<OpfillterTypeSt[]>([]);
const optionsType = ref<OpfillterTypeSt[]>([
  { id: "chairman", value: "ประธาน" },
  { id: "committee", value: "ผู้บังคับบัญชา" },
  { id: "caregiver", value: "ผู้ดูแล" },
]);

const rowsDirector = ref<MemBerType[]>([]);

const visibleColumns = ref<string[]>([
  "no",
  "posNo",
  "role",
  "name",
  "position",
  "positionType",
  "actFullName",
]);
const visibleColumnsMemberBase = ref<string[]>([
  // "no",
  "posNo",
  "name",
  "position",
  "posLevel",
  "posType",
  "positionSign",
]);
/** หัวตาราง */
const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: false,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "posNo",
    align: "left",
    label: "เลขที่ตำแหน่ง",
    sortable: true,
    field: "posNo",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "role",
    align: "left",
    label: "บทบาท",
    sortable: true,
    field: "role",
    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",
    format(val, row) {
      return `${row.positionType ? row.positionType : ""} ${
        row.positionLevel ? "(" + row.positionLevel + ")" : ""
      }`;
    },
  },
  // {
  //   name: "actFullName",
  //   align: "left",
  //   label: "รักษาการแทน",
  //   sortable: true,
  //   field: "actFullName",
  //   headerStyle: "font-size: 14px",
  //   style: "font-size: 14px",
  // },
]);

const baseColumnsMember = ref<QTableProps["columns"]>([
  // {
  //   name: "no",
  //   align: "left",
  //   label: "ลำดับ",
  //   sortable: false,
  //   field: "no",
  //   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: "posNo",
    align: "left",
    label: "เลขที่ตำแหน่ง",
    sortable: true,
    field: "posNo",
    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: "posType",
    align: "left",
    label: "ตำแหน่งประเภท",
    sortable: true,
    field: "posType",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format(val, row) {
      return `${row.posType ? row.posType : ""} ${
        row.posLevel ? "(" + row.posLevel + ")" : ""
      }`;
    },
  },
  {
    name: "positionSign",
    align: "left",
    label: "ตำแหน่งใต้ลายเซ็น",
    sortable: true,
    field: "positionSign",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);

const columnsMember = computed(() => {
  if (isAct.value) {
    const actColumns = JSON.parse(JSON.stringify(baseColumnsMember.value));
    const posNoCol = actColumns.find((col: any) => col.name === "posNo");
    if (posNoCol) {
      posNoCol.label = "เลขที่ตำแหน่งรักษาการแทน";
    }
    return actColumns;
  }
  return baseColumnsMember.value;
});

const visibleColumnsMember = computed(() => {
  if (isAct.value || isDirector.value) {
    return ["name", "posNo", "positionSign"];
  }
  return ["name", "posNo", "position", "posLevel", "posType"];
});

/** เพิ่ม  คณะกรรมการ */
function onAdd() {
  modal.value = true;
}

function close() {
  isAct.value = false;
  isDirector.value = false;
  modal.value = false;
  member.value = "";
  selected.value = [];
  rowsDirector.value = [];
}

function updatePagination(newPagination: any) {
  pagination.value.page = 1;
  pagination.value.rowsPerPage = newPagination.rowsPerPage;
}

function onAddPerson() {
  changeFormData();
  const data = selected.value.map((item: MemBerType) => ({
    profileId: item.id,
    name: `${item.prefix}${item.firstName} ${item.lastName}`,
    citizenId: item.citizenId,
    prefix: item.prefix,
    firstName: item.firstName,
    lastName: item.lastName,
    position: item.position,
    positionType: item.posType,
    positionLevel: item.posLevel,
    actFullName: item.actFullName,
    posNo: item.posNo,
    role: member.value,
    rootId: item.orgRootId,
  }));

  rows.value.push(...data);
  const roleOrder: Record<"chairman" | "committee" | "caregiver", number> = {
    chairman: 0,
    committee: 1,
    caregiver: 2,
  };

  rows.value.sort((a, b) => {
    return (
      roleOrder[a.role as keyof typeof roleOrder] -
      roleOrder[b.role as keyof typeof roleOrder]
    );
  });

  close();
}

async function getPerson() {
  showLoader();
  await http
    .post(config.API.probationCommanderDirector, {
      profileId: profileId.value,
      isAct: isAct.value,
      isDirector: isDirector.value,
      pageSize: pagination.value.rowsPerPage,
      page: pagination.value.page,
      keyword: filterKeyword.value.trim(),
    })
    .then(async (res) => {
      const data = await res.data.result.data;
      const dataTotal = await res.data.result.total;
      rowsDirector.value = data.filter(
        (item: MemBerType) =>
          !rows.value.some((i: PersonsAppointData) => i.profileId == item.id)
      );
      totalList.value = Math.ceil(dataTotal / pagination.value.rowsPerPage);
      total.value = dataTotal;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

function onDelete(id: string) {
  changeFormData();
  rows.value = rows.value.filter((row) => row.profileId !== id);
}

function convertText(val: string) {
  switch (val) {
    case "chairman":
      return "ประธาน";
    case "committee":
      return "ผู้บังคับบัญชา";
    case "caregiver":
      return "ผู้ดูแล";
    default:
      "-";
  }
}

// ตัวแปรสำหรับเก็บค่าก่อนหน้า
const topicCheck = ref<string>(topic.value);
const rowsCheck = ref<PersonsAppointData[]>(rows.value);
function changeFormData() {
  if (topic.value !== topicCheck.value || rows.value !== rowsCheck.value) {
    isSave.value = true;
  } else {
    isSave.value = false;
  }

  topicCheck.value = topic.value;
  rowsCheck.value = rows.value;
}

function onSubmit() {
  const body = {
    topic: topic.value,
    persons: rows.value.map(({ ...newData }) => newData),
  };

  dialogConfirm($q, async () => {
    showLoader();
    await http
      .put(config.API.appointMain + `/${id.value}`, body)
      .then(async () => {
        await getData();
        success($q, "บันทึกข้อมูลสำเร็จ");
        isSave.value = false;
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

/** ดึงข้อมูลหลัก */
async function getData() {
  showLoader();
  await http
    .get(config.API.appointMain + `/${id.value}`)
    .then(async (res) => {
      const data = await res.data.result;
      topic.value = data.topic;
      status.value = data.status;
      profileId.value = data.profileId;
      rows.value = data.directors.map((item: any) => ({
        profileId: item.profileId,
        name: item.name,
        citizenId: item.citizenId,
        prefix: item.prefix,
        firstName: item.firstName,
        lastName: item.lastName,
        position: item.position,
        positionType: item.positionType,
        positionLevel: item.positionLevel,
        posNo: item.posNo,
        actFullName: item.actFullName,
        role: item.role,
      }));
      const roleOrder: Record<"chairman" | "committee" | "caregiver", number> =
        {
          chairman: 0,
          committee: 1,
          caregiver: 2,
        };

      rows.value.sort((a, b) => {
        return (
          roleOrder[a.role as keyof typeof roleOrder] -
          roleOrder[b.role as keyof typeof roleOrder]
        );
      });
      hideLoader();
    })
    .catch((e) => {
      messageError($q, e);
      hideLoader();
    })
    .finally(() => {});
}

async function onDirector() {
  pagination.value.page = 1;
  isAct.value = false;
  await getPerson();
  selected.value = [];
}

async function onAct() {
  pagination.value.page = 1;
  isDirector.value = false;
  await getPerson();
  selected.value = [];
}

watch(
  () => modal.value,
  () => {
    if (modal.value) {
      filterKeyword.value = "";
      optionsTypeMain.value = optionsType.value;
      const optionData = optionsType.value;
      const caregiverCount = rows.value.filter(
        (i) => i.role === "caregiver"
      ).length;

      optionsTypeMain.value = optionData.filter(
        (item: OpfillterTypeSt) =>
          !rows.value.some(
            (i) =>
              (i.role === "chairman" && item.id === "chairman") ||
              (i.role === "committee" && item.id === "committee")
          ) && !(item.id === "caregiver" && caregiverCount >= 2)
      );

      getPerson();
    }
  }
);

watch(
  () => pagination.value.rowsPerPage,
  async () => {
    await getPerson();
  }
);

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.go(-1)"
    />
    {{
      checkRoutePermisson ? "รายละเอียด" : ""
    }}แต่งตั้งคณะกรรมการประเมินผลการทดลองปฏิบัติหน้าที่ราชการ
  </div>
  <q-card flat>
    <q-form greedy @submit.prevent @validation-success="onSubmit">
      <div class="row q-col-gutter-sm q-pa-sm">
        <div v-if="isSave" class="col-12 q-pt-none">
          <q-banner
            inline-actions
            bordered
            rounded
            dense
            class="bg-red-1 text-red border-orange"
          >
            <q-icon name="mdi-information-outline" size="20px" /> แจ้งเตือน
            ยังไม่ได้บันทึกข้อมูล
          </q-banner>
        </div>
        <div class="col-12">
          <q-input
            dense
            outlined
            label="หัวข้อ"
            :readonly="checkRoutePermisson"
            v-model="topic"
            class="inputgreen"
            hide-bottom-space
            @update:model-value="changeFormData"
            :rules="[(val:string) => !!val || `${'กรุณากรอกหัวข้อ'}`,]"
          ></q-input>
        </div>
        <div class="col-12">
          <q-card bordered 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"
            >
              คณะกรรมการ
              <q-btn
                v-if="!checkRoutePermisson && rows.length !== 4"
                size="12px"
                flat
                round
                dense
                color="primary"
                class="q-ml-sm"
                @click="onAdd"
                icon="mdi-plus"
              >
                <q-tooltip>เพิ่มคณะกรรมการ</q-tooltip>
              </q-btn>
            </div>
            <q-separator />
            <div class="q-pa-sm">
              <d-table
                ref="table"
                :columns="columns"
                :rows="rows"
                row-key="profileId"
                flat
                :visible-columns="visibleColumns"
                bordered
                dense
                hide-pagination
              >
                <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"
                    >
                      <span class="text-weight-medium">{{ col.label }}</span>
                    </q-th>
                  </q-tr>
                </template>
                <template v-slot:body="props">
                  <q-tr :props="props">
                    <q-td auto-width>
                      <q-btn
                        v-if="!checkRoutePermisson"
                        flat
                        round
                        dense
                        icon="delete"
                        color="red"
                        @click="onDelete(props.row.profileId)"
                      >
                        <q-tooltip>ลบข้อมูล</q-tooltip>
                      </q-btn>
                    </q-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 == 'role'">
                        {{ props.row.role ? convertText(props.row.role) : "-" }}
                      </div>
                      <div v-else>
                        {{ col.value ? col.value : "-" }}
                      </div>
                    </q-td>
                  </q-tr>
                </template>
              </d-table>
            </div>
          </q-card>
        </div>
      </div>
      <q-separator v-if="!checkRoutePermisson" />
      <q-card-actions align="right" v-if="!checkRoutePermisson">
        <span class="q-mr-sm text-red" v-if="!findPerson"
          ><q-icon name="mdi-alert-circle-outline"></q-icon>
          {{ textAlert }}</span
        >
        <q-btn
          label="บันทึก"
          color="secondary"
          type="submit"
          :disable="!findPerson"
          ><q-tooltip>บันทึก</q-tooltip></q-btn
        >
      </q-card-actions>
    </q-form>
  </q-card>

  <q-dialog v-model="modal" persistent>
    <q-card class="col-12" style="width: 80%">
      <q-form greedy @submit.prevent @validation-success="onAddPerson">
        <DialogHeader tittle="เพิ่มคณะกรรมการ" :close="close" />
        <q-separator />
        <q-card-section>
          <div class="row q-col-gutter-sm">
            <div class="col-2">
              <q-select
                v-model="member"
                outlined
                dense
                label="บทบาท"
                :options="optionsTypeMain"
                option-value="id"
                option-label="value"
                map-options
                emit-value
                @update:model-value="selected = []"
              >
              </q-select>
            </div>
            <div class="col-12">
              <div class="row">
                <!-- <div class="col-2"></div> -->
                <q-checkbox
                  keep-color
                  v-model="isDirector"
                  label="แสดงเฉพาะผู้อำนวยการ/หัวหน้า"
                  color="primary"
                  @update:model-value="onDirector"
                >
                  <q-tooltip>แสดงเฉพาะผู้อำนวยการ/หัวหน้า </q-tooltip>
                </q-checkbox>
                <q-checkbox
                  keep-color
                  v-model="isAct"
                  label="แสดงเฉพาะรักษาการแทน"
                  color="primary"
                  @update:model-value="onAct"
                >
                  <q-tooltip>แสดงเฉพาะรักษาการแทน </q-tooltip>
                </q-checkbox>
                <q-space />
                <q-input
                  class="col-xs-12 col-sm-3 col-md-2 q-mr-sm"
                  standout
                  dense
                  v-model="filterKeyword"
                  ref="filterRef"
                  outlined
                  placeholder="ค้นหา"
                  @keydown.enter.prevent="(pagination.page = 1), getPerson()"
                >
                  <template v-slot:append>
                    <q-icon name="search" />
                  </template>
                </q-input>

                <q-select
                  v-model="visibleColumnsMember"
                  multiple
                  outlined
                  dense
                  options-dense
                  :display-value="$q.lang.table.columns"
                  emit-value
                  map-options
                  :options="columnsMember"
                  option-value="name"
                  style="min-width: 140px"
                  class="col-xs-12 col-sm-3 col-md-2"
                />
              </div>
            </div>

            <div class="col-12">
              <d-table
                ref="table"
                :columns="columnsMember"
                :rows="rowsDirector"
                row-key="key"
                flat
                :visible-columns="visibleColumnsMember"
                bordered
                :paging="true"
                dense
                :selection="
                  member == 'chairman' || member == 'committee'
                    ? 'single'
                    : 'multiple'
                "
                v-model:selected="selected"
                :rows-per-page-options="[10, 25, 50, 100]"
                @update:pagination="updatePagination"
              >
                <template v-slot:header-selection="scope"> </template>

                <template v-slot:body="props">
                  <q-tr :props="props">
                    <td class="text-center">
                      <q-checkbox
                        keep-color
                        :disable="
                          !member || (props.selected == false && countRowLength)
                        "
                        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'">
                        {{
                          (pagination.page - 1) * pagination.rowsPerPage +
                          props.rowIndex +
                          1
                        }}
                      </div>

                      <div v-else-if="col.name == 'name'">
                        {{
                          props.row.firstName
                            ? `${props.row.prefix}${props.row.firstName} ${props.row.lastName}`
                            : "-"
                        }}
                      </div>
                      <div v-else>
                        {{ col.value ? col.value : "-" }}
                      </div>
                    </q-td>
                  </q-tr>
                </template>

                <template v-slot:pagination="scope">
                  ทั้งหมด {{ total.toLocaleString() }} รายการ
                  <q-pagination
                    v-model="pagination.page"
                    active-color="primary"
                    color="dark"
                    :max="Number(totalList)"
                    size="sm"
                    boundary-links
                    direction-links
                    :max-pages="5"
                    @update:model-value="getPerson()"
                  ></q-pagination>
                </template>
              </d-table>
            </div>
          </div>
        </q-card-section>
        <q-separator />

        <q-card-actions align="right">
          <q-btn
            label="เพิ่มรายชื่อ"
            color="secondary"
            type="submit"
            :disable="selected.length == 0"
            ><q-tooltip>เพิ่มรายชื่อ</q-tooltip></q-btn
          >
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>
