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

import http from "@/plugins/http";
import config from "@/app.config";
import { useDevelopmentDataStore } from "@/modules/15_development/store/developmentStore";
import { useCounterMixin } from "@/stores/mixin";

import type { QTableProps } from "quasar";
import type { DataOption } from "@/modules/15_development/interface/index/Main";
import type {
  FormGroupRelate,
  FormGroupTargetPlannedGoal,
} from "@/modules/15_development/interface/request/Main";
import type {
  ResGroup,
  ResLevel,
  ResPlannedGoals,
  ResPeople,
  ResActualGoals,
} from "@/modules/15_development/interface/response/Main";

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

/**
 * use
 */
const $q = useQuasar();
const store = useDevelopmentDataStore();
const route = useRoute();
const projectId = ref<string>(route.params.id.toLocaleString());
const { showLoader, hideLoader, messageError, success, dialogConfirm } =
  useCounterMixin();

/**
 * props
 */
const props = defineProps({
  prevStep: { type: Function, required: true },
  nextStep: { type: Function, required: true },
});

const checkRoutePermission = ref<boolean>(
  route.name == "developmentDetailPage"
);

const plannedGoals = ref<ResPlannedGoals[]>([]);
const plannedGoalsData = ref<ResPlannedGoals[]>([]);
const plannedPeoples = ref<ResPeople[]>([]);
const actualGoals = ref<ResActualGoals[]>([]);
const actualPeoples = ref<ResPeople[]>([]);

const groupTargetData = reactive({
  targetData: [{}],
});

const isEdit = ref<boolean>(false);
const editId = ref<string>("");
const modalGroupTarget = ref<boolean>(false);
const newModalGroupTarget = ref<boolean>(false);
const modalRelate = ref<boolean>(false);
const isTarget = ref<string>("");

const posTypeOp = ref<DataOption[]>([]);
const posLevelOp = ref<DataOption[]>([]);
const posTypeMain = ref<ResGroup[]>([]);

const formGroupTarget = reactive<FormGroupTargetPlannedGoal>({
  groupTarget: "",
  groupTargetSub: "",
  position: "",
  posType: null,
  posLevel: null,
  type: null,
  amount: null,
  positions: [
    {
      position: "",
      posTypeId: null,
      posLevelId: null,
    },
  ],
});

const formGroupRelate = reactive<FormGroupRelate>({
  relate: "",
  amount: null,
});

/** เพิ่ม object ให้ตัวแปร */
const addGroupTargetData = async () => {
  formGroupTarget.positions.push({
    position: "",
    posTypeId: null,
    posLevelId: null,
  });
};

const peoplesOp = ref<DataOption[]>([
  { id: "OPERATOR", name: "เจ้าหน้าที่ดําเนินการ" },
  { id: "LECTURER", name: "วิทยากร" },
  { id: "OBSERVER", name: "ผู้สังเกตการณ์" },
]);

const groupOp = ref<DataOption[]>([
  { id: "OFFICER", name: "ข้าราชการกรุงเทพมหานคร" },
  { id: "PERSONNEL", name: "บุคลากรกรุงเทพมหานคร" },
  { id: "OUTSIDERS", name: "บุคคลภายนอก" },
]);

const groupSubOp = ref<DataOption[]>([
  { id: "OFFICER", name: "ข้าราชการกรุงเทพมหานครสามัญ" },
  { id: "TEACHER", name: "ข้าราชการครู" },
  { id: "EMPLOYEE", name: "กรุงเทพมหานคร(ลูกจ้างประจำ)" },
  { id: "EMPLOYEETEMP", name: "กรุงเทพมหานคร(ลูกจ้างชั่วคราว)" },
  { id: "EDUCATIONAL", name: "บุคลากรทางการศึกษากรุงเทพมหานคร" },
]);

const columnsPlannedGoals = ref<QTableProps["columns"]>([
  {
    name: "groupTarget",
    align: "left",
    label: "กลุ่มเป้าหมาย ",
    sortable: true,
    field: "groupTarget",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (val) => convertNameGoals(val),
  },
  {
    name: "groupTargetSub",
    align: "left",
    label: "กลุ่มเป้าหมายย่อย",
    sortable: true,
    field: "groupTargetSub",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (val) => convertNameSubGoals(val),
  },
  {
    name: "posTypePlannedId",
    align: "left",
    label: "ตำแหน่ง",
    sortable: true,
    field: "posTypePlannedId",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "amount",
    align: "left",
    label: "จำนวน(คน)",
    sortable: true,
    field: "amount",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);

const columnsActualGoals = ref<QTableProps["columns"]>([
  {
    name: "groupTarget",
    align: "left",
    label: "กลุ่มเป้าหมาย ",
    sortable: true,
    field: "groupTarget",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (val) => convertNameGoals(val),
  },
  {
    name: "groupTargetSub",
    align: "left",
    label: "กลุ่มเป้าหมายย่อย",
    sortable: true,
    field: "groupTargetSub",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (val) => convertNameSubGoals(val),
  },
  {
    name: "posTypeActualId",
    align: "left",
    label: "ตำแหน่ง",
    sortable: true,
    field: "posTypeActualId",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "amount",
    align: "left",
    label: "จำนวน(คน)",
    sortable: true,
    field: "amount",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (val) => Number(val),
  },
]);

const columnsRelated = ref<QTableProps["columns"]>([
  {
    name: "groupTarget",
    align: "left",
    label: "ผู้เกี่ยวข้อง ",
    sortable: true,
    field: "groupTarget",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (val) => convertNamePeoples(val),
  },

  {
    name: "amount",
    align: "left",
    label: "จำนวน(คน)",
    sortable: true,
    field: "amount",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (val) => Number(val),
  },
]);

/** function เรียกข้อมูลประเภทตำแหน่ง*/
function fetchType() {
  if (posTypeMain.value.length === 0) {
    http
      .get(config.API.orgPosType)
      .then((res) => {
        const data = res.data.result;
        posTypeMain.value = data;
        posTypeOp.value = data.map((e: ResGroup) => ({
          id: e.id,
          name: e.posTypeName,
        }));
      })
      .catch((err) => {
        messageError($q, err);
      });
  }
}

/** ดึงข้อมูล */
async function fetchData(id: string) {
  showLoader();
  await http
    .get(config.API.developmentMainTab("tab2", id))
    .then(async (res) => {
      const data = res.data.result;
      actualGoals.value = data.actualGoals;
      actualPeoples.value = data.actualPeoples;
      plannedGoals.value = data.plannedGoals;
      plannedGoalsData.value = data.plannedGoals;
      plannedPeoples.value = data.plannedPeoples;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/** เปิด dialog */
function onClickOpenDialog(type: string, target: string) {
  isTarget.value = target;
  if (type === "group") {
    if (target === "planned") {
      (formGroupTarget.positions = [
        {
          position: "",
          posTypeId: null,
          posLevelId: null,
        },
      ]),
        (newModalGroupTarget.value = true);
    } else {
      modalGroupTarget.value = true;
    }
  } else {
    modalRelate.value = true;
  }
}

/** เพิ่ม/แก้ไขกลุ่มเป้าหมาย */
function onSubmitGroup() {
  dialogConfirm($q, async () => {
    showLoader();
    if (isTarget.value === "planned") {
      await http
        .put(
          config.API.developmentMainTab(
            isEdit.value ? "tab2_1_edit" : "tab2_1_add",
            isEdit.value ? editId.value : projectId.value
          ),
          {
            groupTarget: formGroupTarget.groupTarget,
            groupTargetSub: formGroupTarget.groupTargetSub,
            positions:
              formGroupTarget.groupTarget !== "OUTSIDERS"
                ? formGroupTarget.positions.map((v) => ({
                    position: v.position ? v.position : "",
                    posTypePlannedId: v.posTypeId ? v.posTypeId : null,
                    posLevelPlannedId: v.posLevelId ? v.posLevelId : null,
                  }))
                : [],
            type:
              formGroupTarget.groupTarget === "OUTSIDERS"
                ? formGroupTarget.type
                : "",
            amount: formGroupTarget.amount,
          }
        )
        .then(() => {
          success($q, "บันทึกข้อมูลสำเร็จ");
        })
        .catch((err) => {
          messageError($q, err);
        })
        .finally(() => {
          hideLoader();
        });
    } else {
      await http
        .put(
          config.API.developmentMainTab(
            isEdit.value ? "tab2_3_edit" : "tab2_3_add",
            isEdit.value ? editId.value : projectId.value
          ),
          {
            groupTarget: formGroupTarget.groupTarget,
            groupTargetSub: formGroupTarget.groupTargetSub,
            position: formGroupTarget.position,
            posTypeActualId: formGroupTarget.posType
              ? formGroupTarget.posType
              : null,
            posLevelActualId: formGroupTarget.posLevel
              ? formGroupTarget.posLevel
              : null,
            type: formGroupTarget.type,
            amount: formGroupTarget.amount,
          }
        )
        .then(() => {
          success($q, "บันทึกข้อมูลสำเร็จ");
        })
        .catch((err) => {
          messageError($q, err);
        })
        .finally(() => {
          hideLoader();
        });
    }
    setTimeout(() => {
      fetchData(projectId.value);
      onClickCloseDialog();
    }, 100);
  });
}

/**  เพิ่มผู้เกี่ยวข้อง */
function onSubmitRelate() {
  dialogConfirm($q, async () => {
    showLoader();
    if (isTarget.value === "planned") {
      await http
        .put(
          config.API.developmentMainTab(
            isEdit.value ? "tab2_2_edit" : "tab2_2_add",
            isEdit.value ? editId.value : projectId.value
          ),
          {
            groupTarget: formGroupRelate.relate,
            amount: formGroupRelate.amount,
          }
        )
        .then(async () => {
          await fetchData(projectId.value);
          onClickCloseDialog();
          success($q, "บันทึกข้อมูลสำเร็จ");
        })
        .catch((err) => {
          messageError($q, err);
        })
        .finally(() => {
          hideLoader();
        });
    } else {
      await http
        .put(
          config.API.developmentMainTab(
            isEdit.value ? "tab2_4_edit" : "tab2_4_add",
            isEdit.value ? editId.value : projectId.value
          ),
          {
            groupTarget: formGroupRelate.relate,
            amount: formGroupRelate.amount,
          }
        )
        .then(async () => {
          await fetchData(projectId.value);
          onClickCloseDialog();
          success($q, "บันทึกข้อมูลสำเร็จ");
        })
        .catch((err) => {
          messageError($q, err);
        })
        .finally(() => {
          hideLoader();
        });
    }
  });
}

/** clear form */
function cleanFormData() {
  formGroupTarget.groupTarget = "";
  formGroupTarget.groupTargetSub = "";
  formGroupTarget.position = "";
  formGroupTarget.posType = null;
  formGroupTarget.posLevel = null;
  formGroupTarget.type = "";
  formGroupTarget.amount = null;
  formGroupRelate.relate = "";
  formGroupRelate.amount = null;
  isEdit.value = false;
}

/** ปิด dialog */
function onClickCloseDialog() {
  newModalGroupTarget.value = false;
  modalGroupTarget.value = false;
  groupTargetData.targetData = [{}];
  modalRelate.value = false;
  cleanFormData();
  fetchType();
  // fetchData(projectId.value);
}

/**
 * map ช้อมูลตาม option id
 * @param id id
 */
function updatePosTypeName(id: string) {
  const posLevel = posTypeMain.value.find((e: ResGroup) => e.id === id);
  posLevelOp.value =
    posLevel?.posLevels.map((e: ResLevel) => ({
      id: e.id,
      name: e.posLevelName.toString(),
    })) ?? [];
  formGroupTarget.posLevel = "";
}

/**
 * กลุ่มเป้าหมาย
 * @param val ข้อมูล กลุ่มเป้าหมาย
 */
function updateGroupTarget(val: string) {
  if (val === "OUTSIDERS") {
    formGroupTarget.groupTargetSub = "NONE";
    formGroupTarget.position = "";
    formGroupTarget.posType = null;
    formGroupTarget.posLevel = null;
  } else formGroupTarget.groupTargetSub = "";
}

/** หาชื่อ ตาม id */
function convertNameGoals(id: string) {
  const data = groupOp.value.find((e: DataOption) => e.id === id);
  return data && data?.name;
}

/** หาชื่อ ตาม id */
function convertNameSubGoals(id: string) {
  const data = groupSubOp.value.find((e: DataOption) => e.id === id);
  return data && data?.name;
}

/** หาชื่อ ตาม id */
function convertNamePeoples(id: string) {
  const data = peoplesOp.value.find((e: DataOption) => e.id === id);
  return data && data?.name;
}

/** ลบข้อมูลออกตัวตัวแปร จาก ลำดับ */
function deleteTargetData(index: any) {
  formGroupTarget.positions.splice(index, 1);
}

function onOpenDialog(data: any) {
  isEdit.value = true;
  isTarget.value = "planned";
  editId.value = data.id;
  formGroupTarget.type = data.type;
  formGroupTarget.groupTarget = data.groupTarget;
  formGroupTarget.groupTargetSub = data.groupTargetSub;
  formGroupTarget.amount = data.amount;
  formGroupTarget.positions = (
    plannedGoalsData.value.find((item: any) => item.id === data.id)?.position ||
    []
  ).map((pos: any) => ({
    position: pos.position,
    posTypeId: pos.posTypeId || null,
    posLevelId: pos.posLevelId || null,
  }));
  newModalGroupTarget.value = true;
}

/** ดึงข้อมูลเมื่อคอมโพเนนต์โหลดเสร็จสมบูรณ์  */
onMounted(() => {
  fetchType();
  fetchData(projectId.value);
});
</script>
<template>
  <!-- CARD เป้าหมายตามแผน -->
  <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="store.projectStatus !== 'FINISH' && !checkRoutePermission"
        flat
        round
        dense
        icon="add"
        color="primary"
      >
        <q-menu>
          <q-list style="min-width: 100px">
            <q-item
              clickable
              v-close-popup
              @click="
                cleanFormData();
                isEdit = false;
                onClickOpenDialog('group', 'planned');
              "
            >
              <q-item-section>กลุ่มเป้าหมาย</q-item-section>
            </q-item>
            <q-item
              clickable
              v-close-popup
              @click="
                isEdit = false;
                onClickOpenDialog('relate', 'planned');
              "
            >
              <q-item-section>ผู้เกี่ยวข้อง</q-item-section>
            </q-item>
            <q-separator />
          </q-list>
        </q-menu>
        <q-tooltip>เพิ่ม</q-tooltip>
      </q-btn>
    </div>
    <div class="col-12"><q-separator /></div>
    <div class="row col-12 q-col-gutter-md q-pa-md">
      <div class="col-12">
        <d-table
          for="table"
          :columns="columnsPlannedGoals"
          :rows="plannedGoals"
          row-key="id"
          flat
          bordered
          dense
          class="custom-header-table"
          hide-pagination
        >
          <template v-slot:header="props">
            <q-tr :props="props">
              <q-th auto-width />
              <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" class="vertical-top">
              <q-td>
                <q-btn
                  v-if="
                    store.projectStatus !== 'FINISH' && !checkRoutePermission
                  "
                  round
                  flat
                  color="primary"
                  icon="mdi-pencil-outline"
                  size="14px"
                  @click="onOpenDialog(props.row)"
                >
                  <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 === 'posTypePlannedId'">
                  <div
                    v-if="props.row.groupTarget !== 'OUTSIDERS'"
                    v-for="row in props.row.position"
                  >
                    {{ `- ${row.position}`
                    }}{{
                      row.posType !== null || row.posLevel !== null
                        ? ` (${row.posType ? row.posType : ""}${
                            row.posLevel ? " " + row.posLevel : ""
                          })`
                        : ""
                    }}
                  </div>
                  <div v-else>
                    {{ props.row.type ? props.row.type : "-" }}
                  </div>
                </div>
                <div v-else class="table_ellipsis">
                  {{ col.value ? col.value : "-" }}
                </div>
              </q-td>
            </q-tr>
          </template>
        </d-table>
      </div>

      <div class="col-12">
        <d-table
          for="table"
          ref="table"
          :columns="columnsRelated"
          :rows="plannedPeoples"
          row-key="id"
          flat
          bordered
          dense
          class="custom-header-table"
          hide-pagination
        >
          <template v-slot:header="props">
            <q-tr :props="props">
              <q-th auto-width />
              <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>
                <q-btn
                  v-if="
                    store.projectStatus !== 'FINISH' && !checkRoutePermission
                  "
                  round
                  flat
                  color="primary"
                  icon="mdi-pencil-outline"
                  size="14px"
                  @click="
                    () => {
                      isEdit = true;
                      isTarget = 'planned';
                      editId = props.row.id;
                      formGroupRelate.relate = props.row.groupTarget;
                      formGroupRelate.amount = props.row.amount;
                      modalRelate = true;
                    }
                  "
                >
                  <q-tooltip>แก้ไขข้อมูล</q-tooltip></q-btn
                >
              </q-td>
              <q-td v-for="col in props.cols" :key="col.name" :props="props">
                <div class="table_ellipsis">
                  {{ col.value ? col.value : "-" }}
                </div>
              </q-td>
            </q-tr>
          </template>
        </d-table>
      </div>
    </div>
  </q-card>

  <!--CARD เป้าหมายตามจริง -->
  <q-card
    v-if="store.projectStatus === 'FINISH'"
    bordered
    style="border: 1px solid #d6dee1"
    class="q-mt-md"
  >
    <div class="text-weight-medium bg-grey-1 q-py-sm q-px-md">
      เป้าหมายตามจริง
      <q-btn
        v-if="!checkRoutePermission"
        flat
        round
        dense
        icon="add"
        color="primary"
      >
        <q-menu>
          <q-list style="min-width: 100px">
            <q-item
              clickable
              v-close-popup
              @click="onClickOpenDialog('group', 'actual')"
            >
              <q-item-section>กลุ่มเป้าหมาย</q-item-section>
            </q-item>
            <q-item
              clickable
              v-close-popup
              @click="onClickOpenDialog('relate', 'actual')"
            >
              <q-item-section>ผู้เกี่ยวข้อง</q-item-section>
            </q-item>
            <q-separator />
          </q-list>
        </q-menu>
        <q-tooltip>เพิ่ม</q-tooltip>
      </q-btn>
    </div>
    <div class="col-12"><q-separator /></div>
    <div class="row col-12 q-col-gutter-md q-pa-md">
      <div class="col-12">
        <d-table
          for="table"
          ref="table"
          :columns="columnsActualGoals"
          :rows="actualGoals"
          row-key="id"
          flat
          bordered
          dense
          class="custom-header-table"
          hide-pagination
        >
          <template v-slot:header="props">
            <q-tr :props="props">
              <q-th auto-width />
              <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>
                <q-btn
                  v-if="!checkRoutePermission"
                  round
                  flat
                  color="primary"
                  icon="mdi-pencil-outline"
                  size="14px"
                  @click="
                    () => {
                      isEdit = true;
                      isTarget = 'actual';
                      editId = props.row.id;
                      formGroupTarget.type = props.row.type;
                      formGroupTarget.groupTarget = props.row.groupTarget;
                      formGroupTarget.groupTargetSub = props.row.groupTargetSub;
                      formGroupTarget.amount = props.row.amount;
                      formGroupTarget.position = props.row.position;
                      formGroupTarget.posType = props.row.posTypeId;
                      formGroupTarget.posLevel = props.row.posLevelId;
                      modalGroupTarget = true;
                    }
                  "
                >
                  <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 === 'posTypeActualId'">
                  <div v-if="props.row.groupTarget !== 'OUTSIDERS'">
                    {{ `- ${props.row.position}`
                    }}{{
                      props.row.posType !== null || props.row.posLevel !== null
                        ? ` (${props.row.posType ? props.row.posType : ""}${
                            props.row.posLevel ? " " + props.row.posLevel : ""
                          })`
                        : ""
                    }}
                  </div>
                  <div v-else>
                    {{ props.row.type ? props.row.type : "-" }}
                  </div>
                </div>
                <div v-else class="table_ellipsis">
                  {{ col.value ? col.value : "-" }}
                </div>
                <div v-else class="table_ellipsis">
                  {{ col.value ? col.value : "-" }}
                </div>
              </q-td>
            </q-tr>
          </template>
        </d-table>
      </div>

      <div class="col-12">
        <d-table
          for="table"
          ref="table"
          :columns="columnsRelated"
          :rows="actualPeoples"
          row-key="id"
          flat
          bordered
          dense
          class="custom-header-table"
          hide-pagination
        >
          <template v-slot:header="props">
            <q-tr :props="props">
              <q-th auto-width />
              <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>
                <q-btn
                  v-if="!checkRoutePermission"
                  round
                  flat
                  color="primary"
                  icon="mdi-pencil-outline"
                  size="14px"
                  @click="
                    () => {
                      isEdit = true;
                      isTarget = 'actual';
                      editId = props.row.id;
                      formGroupRelate.relate = props.row.groupTarget;
                      formGroupRelate.amount = props.row.amount;
                      modalRelate = true;
                    }
                  "
                >
                  <q-tooltip>แก้ไขข้อมูล</q-tooltip></q-btn
                >
              </q-td>
              <q-td v-for="col in props.cols" :key="col.name" :props="props">
                <div class="table_ellipsis">
                  {{ col.value ? col.value : "-" }}
                </div>
              </q-td>
            </q-tr>
          </template>
        </d-table>
      </div>
    </div>
  </q-card>

  <q-card v-if="!checkRoutePermission" bordered>
    <div class="text-center q-pa-sm">
      <q-btn
        rounded
        label="ก่อนหน้า"
        icon="mdi-chevron-left"
        id="onSubmit"
        color="public"
        class="q-mr-xs"
        style="width: 120px"
        @click="props.prevStep()"
      >
      </q-btn>
      <q-btn
        rounded
        label="ถัดไป"
        icon-right="mdi-chevron-right"
        id="onSubmit"
        color="public"
        class="q-ml-xs"
        style="width: 120px"
        @click="props.nextStep()"
      >
      </q-btn>
    </div>
  </q-card>

  <q-dialog v-model="modalGroupTarget" persistent>
    <q-card style="width: 700px">
      <q-form greedy @submit.prevent @validation-success="onSubmitGroup">
        <DialogHeader
          :tittle="isEdit ? 'แก้ไขกลุ่มเป้าหมาย' : 'เพิ่มกลุ่มเป้าหมาย'"
          :close="onClickCloseDialog"
        />
        <q-separator />
        <q-card-section class="q-pa-md">
          <div class="row col-12 q-col-gutter-sm">
            <div class="col-xs-6 col-sm-6 col-md-6">
              <q-select
                dense
                outlined
                v-model="formGroupTarget.groupTarget"
                :options="groupOp"
                label="กลุ่มเป้าหมาย"
                hide-bottom-space
                option-label="name"
                option-value="id"
                map-options
                emit-value
                lazy-rules
                class="inputgreen"
                @update:model-value="updateGroupTarget"
                :rules="[
                (val:string) =>
                  !!val || `${'กรุณาเลือกกลุ่มเป้าหมาย'}`,
              ]"
              />
            </div>
            <div
              class="col-xs-6 col-sm-6 col-md-6"
              v-if="formGroupTarget.groupTarget !== 'OUTSIDERS'"
            >
              <q-select
                dense
                outlined
                class="inputgreen"
                v-model="formGroupTarget.groupTargetSub"
                :options="
                  formGroupTarget.groupTarget === 'OFFICER'
                    ? groupSubOp.filter(
                        (v) =>
                          v.id === 'OFFICER' ||
                          v.id === 'TEACHER' ||
                          v.id === 'EDUCATIONAL'
                      )
                    : groupSubOp.slice(2, 5)
                "
                label="กลุ่มเป้าหมายย่อย"
                hide-bottom-space
                lazy-rules
                option-label="name"
                option-value="id"
                map-options
                emit-value
                :rules="[
                (val:string) =>
                  !!val || `${'กรุณาเลือกกลุ่มเป้าหมายย่อย'}`,
              ]"
              />
            </div>

            <div
              class="col-xs-6 col-sm-4 col-md-4"
              v-if="formGroupTarget.groupTarget !== 'OUTSIDERS'"
            >
              <q-select
                dense
                outlined
                hide-bottom-space
                lazy-rules
                class="inputgreen"
                v-model="formGroupTarget.posType"
                :options="posTypeOp"
                option-label="name"
                option-value="id"
                emit-value
                map-options
                input-class="text-red"
                label="ประเภทตำแหน่ง"
                clearable
                @update:model-value="updatePosTypeName"
              />
            </div>
            <div
              class="col-xs-6 col-sm-4 col-md-4"
              v-if="formGroupTarget.groupTarget !== 'OUTSIDERS'"
            >
              <q-select
                dense
                outlined
                hide-bottom-space
                lazy-rules
                class="inputgreen"
                v-model="formGroupTarget.posLevel"
                :options="
                  posTypeMain.find((v) => formGroupTarget.posType === v.id)
                    ?.posLevels || []
                "
                option-label="posLevelName"
                option-value="id"
                emit-value
                map-options
                input-class="text-red"
                label="ระดับตำแหน่ง"
                clearable
              />
            </div>
            <div
              class="col-xs-6 col-sm-4 col-md-4"
              v-if="formGroupTarget.groupTarget !== 'OUTSIDERS'"
            >
              <q-input
                outlined
                dense
                hide-bottom-space
                class="inputgreen"
                v-model="formGroupTarget.position"
                label="ตำแหน่ง"
                :rules="[
                (val:string) =>
                  !!val || `${'กรุณากรอกตำแหน่ง'}`,
              ]"
              />
            </div>
            <div
              class="col-xs-6 col-sm-6 col-md-8"
              v-if="formGroupTarget.groupTarget === 'OUTSIDERS'"
            >
              <q-input
                outlined
                dense
                class="inputgreen"
                hide-bottom-space
                v-model="formGroupTarget.type"
                label="ประเภท(กลุ่มอาชีพ คุณสมบัติ)"
                :rules="[
              (val:string) =>
                !!val || `${'กรุณากรอกประเภท(กลุ่มอาชีพ คุณสมบัติ)'}`,
            ]"
              />
            </div>
            <div class="col-xs-6 col-sm-6 col-md-4">
              <q-input
                outlined
                dense
                hide-bottom-space
                class="inputgreen"
                v-model="formGroupTarget.amount"
                label="จำนวน(คน)"
                mask="#"
                reverse-fill-mask
                :rules="[
              (val:string) =>
                !!val || `${'กรุณากรอกจำนวน(คน)'}`,
            ]"
              />
            </div>
          </div>
        </q-card-section>
        <q-separator />
        <div class="text-right q-pa-sm">
          <q-btn
            dense
            unelevated
            label="บันทึก"
            id="onSubmit"
            type="submit"
            color="public"
            class="q-px-md"
          >
            <q-tooltip>บันทึกข้อมูล</q-tooltip>
          </q-btn>
        </div>
      </q-form>
    </q-card>
  </q-dialog>

  <q-dialog v-model="newModalGroupTarget" persistent>
    <q-card style="width: 700px">
      <q-form greedy @submit.prevent @validation-success="onSubmitGroup">
        <DialogHeader
          :tittle="isEdit ? 'แก้ไขกลุ่มเป้าหมาย' : 'เพิ่มกลุ่มเป้าหมาย'"
          :close="onClickCloseDialog"
        />
        <q-separator />
        <q-card-section class="q-pa-md">
          <div class="row col-12 q-col-gutter-sm">
            <div class="col-xs-6 col-sm-6 col-md-6">
              <q-select
                dense
                outlined
                v-model="formGroupTarget.groupTarget"
                :options="groupOp"
                label="กลุ่มเป้าหมาย"
                hide-bottom-space
                option-label="name"
                option-value="id"
                map-options
                emit-value
                lazy-rules
                class="inputgreen"
                @update:model-value="updateGroupTarget"
                :rules="[
                (val:string) =>
                  !!val || `${'กรุณาเลือกกลุ่มเป้าหมาย'}`,
              ]"
              />
            </div>
            <div
              class="col-xs-6 col-sm-6 col-md-6"
              v-if="formGroupTarget.groupTarget !== 'OUTSIDERS'"
            >
              <q-select
                dense
                outlined
                class="inputgreen"
                v-model="formGroupTarget.groupTargetSub"
                :options="
                  formGroupTarget.groupTarget === 'OFFICER'
                    ? groupSubOp.filter(
                        (v) =>
                          v.id === 'OFFICER' ||
                          v.id === 'TEACHER' ||
                          v.id === 'EDUCATIONAL'
                      )
                    : groupSubOp.slice(2, 5)
                "
                label="กลุ่มเป้าหมายย่อย"
                hide-bottom-space
                lazy-rules
                option-label="name"
                option-value="id"
                map-options
                emit-value
                :rules="[
                (val:string) =>
                  !!val || `${'กรุณาเลือกกลุ่มเป้าหมายย่อย'}`,
              ]"
              />
            </div>
            <div
              class="col-xs-6 col-sm-6 col-md-8"
              v-if="formGroupTarget.groupTarget === 'OUTSIDERS'"
            >
              <q-input
                outlined
                dense
                class="inputgreen"
                hide-bottom-space
                v-model="formGroupTarget.type"
                label="ประเภท(กลุ่มอาชีพ คุณสมบัติ)"
                :rules="[
              (val:string) =>
                !!val || `${'กรุณากรอกประเภท(กลุ่มอาชีพ คุณสมบัติ)'}`,
            ]"
              />
            </div>
            <div class="col-xs-6 col-sm-6 col-md-4">
              <q-input
                outlined
                dense
                hide-bottom-space
                class="inputgreen"
                v-model="formGroupTarget.amount"
                label="จำนวน(คน)"
                mask="#"
                reverse-fill-mask
                :rules="[
              (val:string) =>
                !!val || `${'กรุณากรอกจำนวน(คน)'}`,
            ]"
              />
            </div>
            <div
              class="col-12 row items-center"
              v-if="formGroupTarget.groupTarget !== 'OUTSIDERS'"
            >
              <div class="text-weight-bold">เพิ่ม</div>
              <q-btn
                flat
                round
                color="primary"
                icon="add"
                size="14px"
                @click="addGroupTargetData()"
              >
                <q-tooltip> เพิ่มข้อมูล </q-tooltip>
              </q-btn>
            </div>
            <div
              v-for="(items, index) in formGroupTarget.positions"
              class="col-12 row q-col-gutter-sm"
            >
              <div
                class="col"
                v-if="formGroupTarget.groupTarget !== 'OUTSIDERS'"
              >
                <q-select
                  dense
                  outlined
                  class="inputgreen"
                  v-model="items.posTypeId"
                  :options="posTypeOp"
                  option-label="name"
                  option-value="id"
                  emit-value
                  map-options
                  input-class="text-red"
                  label="ประเภทตำแหน่ง"
                  clearable
                  @update:model-value="updatePosTypeName"
                />
              </div>
              <div
                class="col"
                v-if="formGroupTarget.groupTarget !== 'OUTSIDERS'"
              >
                <q-select
                  dense
                  outlined
                  class="inputgreen"
                  v-model="items.posLevelId"
                  :options="
                    posTypeMain.find((v) => items.posTypeId === v.id)
                      ?.posLevels || []
                  "
                  option-label="posLevelName"
                  option-value="id"
                  emit-value
                  map-options
                  input-class="text-red"
                  label="ระดับตำแหน่ง"
                  clearable
                />
              </div>
              <div
                class="col"
                v-if="formGroupTarget.groupTarget !== 'OUTSIDERS'"
              >
                <q-input
                  outlined
                  dense
                  hide-bottom-space
                  class="inputgreen"
                  v-model="items.position"
                  label="ตำแหน่ง"
                  :rules="[
                (val:string) =>
                  !!val || `${'กรุณากรอกตำแหน่ง'}`,
              ]"
                />
              </div>
              <div
                class="col-1 q-mt-sm"
                v-if="formGroupTarget.groupTarget !== 'OUTSIDERS'"
              >
                <q-btn
                  flat
                  dense
                  size="12px"
                  round
                  color="red"
                  icon="mdi-delete"
                  @click="deleteTargetData(index)"
                >
                  <q-tooltip>ลบข้อมูล</q-tooltip>
                </q-btn>
              </div>
            </div>
          </div>
        </q-card-section>
        <q-separator />
        <q-card-actions align="right">
          <q-btn label="บันทึก" color="secondary" type="submit"
            ><q-tooltip>บันทึกข้อมูล</q-tooltip></q-btn
          >
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>

  <q-dialog v-model="modalRelate" persistent>
    <q-card style="width: 400px">
      <q-form greedy @submit.prevent @validation-success="onSubmitRelate">
        <DialogHeader
          :tittle="isEdit ? 'แก้ไขผู้เกี่ยวข้อง' : 'เพิ่มผู้เกี่ยวข้อง'"
          :close="onClickCloseDialog"
        />
        <q-separator />
        <q-card-section class="q-pa-sm">
          <div class="row col-12 q-col-gutter-sm">
            <div class="col-xs-6 col-sm-12 col-md-12">
              <q-select
                dense
                outlined
                class="inputgreen"
                v-model="formGroupRelate.relate"
                :options="peoplesOp"
                label="ผู้เกี่ยวข้อง"
                hide-bottom-space
                lazy-rules
                option-label="name"
                option-value="id"
                map-options
                emit-value
                :rules="[
                (val:string) =>
                  !!val || `${'กรุณาเลือกผู้เกี่ยวข้อง'}`,
              ]"
              />
            </div>
            <div class="col-xs-6 col-sm-12 col-md-12">
              <q-input
                outlined
                dense
                hide-bottom-space
                class="inputgreen"
                v-model="formGroupRelate.amount"
                label="จำนวน(คน)"
                mask="#"
                reverse-fill-mask
                :rules="[
            (val:string) =>
              !!val || `${'กรุณากรอกจำนวน(คน)'}`,
          ]"
              />
            </div>
          </div>
        </q-card-section>
        <q-separator />
        <div class="text-right q-pa-sm">
          <q-btn
            dense
            unelevated
            label="บันทึก"
            id="onSubmit"
            type="submit"
            color="public"
            class="q-px-md"
          >
            <q-tooltip>บันทึกข้อมูล</q-tooltip>
          </q-btn>
        </div>
      </q-form>
    </q-card>
  </q-dialog>
</template>

<style scoped></style>
