<script setup lang="ts">
import { ref, onMounted } from "vue";
import type { QTableProps } from "quasar";
import { useCounterMixin } from "@/stores/mixin";
import { useQuasar } from "quasar";
import { useRouter } from "vue-router";

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

import type { DataOption } from "@/modules/14_KPI/interface/index/Main";
import type { ListGroup } from "@/modules/14_KPI/interface/request/Main";
import http from "@/plugins/http";
import config from "@/app.config";

const id = ref<string>("");
const modal = ref<boolean>(false);
const router = useRouter();
const rows = ref<any>([]);
const editStatus = ref<boolean>(false);
const groupName = ref<any>();
const position = ref<any>(null);
const competency = ref<any>(null);

const groupNameOp = ref<DataOption[]>([
  {
    id: "ID1",
    name: "กลุ่ม 1",
  },
  {
    id: "ID2",
    name: "กลุ่ม 2",
  },
]);
const positionOp = ref<DataOption[]>([]);
const positionMainOp = ref<DataOption[]>([]);
const competencyOp = ref<DataOption[]>([
  {
    id: "ID1",
    name: "สมรรถนะ 1",
  },
  {
    id: "ID2",
    name: "สมรรถนะ 2",
  },
]);

const columns = ref<QTableProps["columns"]>([
  {
    name: "groupName",
    align: "left",
    label: "กลุ่มงาน",
    sortable: true,
    field: "groupName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "positions",
    align: "left",
    label: "ตำแหน่ง",
    sortable: true,
    field: "positions",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "capacitys",
    align: "left",
    label: "สมรรถนะประจำกลุ่มงาน",
    sortable: true,
    field: "capacitys",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);

const $q = useQuasar();
const mixin = useCounterMixin();
const {
  dialogRemove,
  messageError,
  showLoader,
  hideLoader,
  success,
  dialogConfirm,
} = mixin;

const competencyType = ref<string>("ID1");
const filterKeyword = ref<string>("");

const visibleColumns = ref<string[]>(["groupName", "positions", "capacitys"]);

/** ดึงข้อมูล */
async function getData() {
  showLoader();
  http
    .get(config.API.kpiLink)
    .then((res) => {
      const data = res.data.result.data;
      rows.value = data;
    })
    .finally(() => {
      hideLoader();
    });
}

async function deleteData(id: string) {
  await http
    .delete(config.API.kpiLink + `/${id}`)
    .then(() => {
      success($q, "ลบข้อมูลสำเร็จ");
      close();
      getData();
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/** ดึงข้อมูล */
async function getListGroup() {
  showLoader();
  await http
    .get(config.API.kpiGroup)
    .then(async (res) => {
      const data = res.data.result.data;
      groupNameOp.value = data.map((item: ListGroup) => ({
        id: item.id,
        name: item.nameGroupKPI,
      }));
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/** ดึงข้อมูล */
async function getCompetency() {
  showLoader();
  await http
    .get(config.API.kpiCapacity + `?type=GROUP`)
    .then(async (res) => {
      const data = res.data.result.data;
      competencyOp.value = data.map((item: any) => ({
        id: item.id,
        name: item.name,
      }));
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/** เปลี่ยนเป็นหน้าเพิ่มข้อมูล */
function onAdd() {
  getOptions();
  getListGroup();
  getCompetency();
  modal.value = true;
}

async function onEdit(data: any) {
  id.value = data;
  await getOptions();
  await getListGroup();
  await getCompetency();
  await getDataEdit(id.value);
  modal.value = true;
  editStatus.value = true;
}

function getDataEdit(id: string) {
  showLoader();
  http
    .get(config.API.kpiLink + `/${id}`)
    .then((res) => {
      const data = res.data.result;
      groupName.value = {
        id: data.groupId,
        name: data.groupName,
      };
      position.value = data.positions.map((i: any) => i.name);
      competency.value = data.capacitys.map((i: any) => i.id);
    })
    .finally(() => {
      hideLoader();
    });
}

function onSubmit() {
  const url = editStatus.value
    ? config.API.kpiLink + `/${id.value}`
    : config.API.kpiLink;
  const body = {
    kpiGroupId: groupName.value.id,
    positions: position.value,
    kpiCapacityIds: competency.value,
  };
  dialogConfirm($q, () => {
    http[editStatus.value ? "put" : "post"](url, body)
      .then(() => {
        success($q, "บันทึกสำเร็จ");
        close();
        getData();
      })
      .finally(() => {});
  });
}

function close() {
  modal.value = false;
  editStatus.value = false;
  groupName.value = "";
  position.value = [];
  competency.value = [];
}

function getOptions() {
  http.get(config.API.orgSalaryPosition).then((res) => {
    const dataOp = res.data.result;
    const uniqueNames = new Set();
    const filteredData = dataOp
      .filter((item: any) => {
        if (!uniqueNames.has(item.positionName)) {
          uniqueNames.add(item.positionName);
          return true;
        }
        return false;
      })
      .map((item: any) => ({
        id: item.positionName,
        name: item.positionName,
      }));

    positionMainOp.value = filteredData;
  });
}

/**
 * function ต้นหาข้อมูลของ Option
 * @param val ค่าที่ต้องการฟิลเตอร์
 * @param update  อัพเดทค่า
 * @param refData ดาต้าที่ต้องการฟิลเตอร์
 */
function filterOption(val: any, update: Function) {
  update(() => {
    positionOp.value = positionMainOp.value.filter(
      (v: any) => v.name.indexOf(val) > -1
    );
  });
}

onMounted(async () => {
  getData();
});
</script>

<template>
  <q-toolbar style="padding: 0">
    <q-btn flat round color="primary" icon="add" @click="onAdd()">
      <q-tooltip> เพิ่มข้อมูล </q-tooltip>
    </q-btn>
    <q-space />
    <div class="row q-gutter-sm">
      <q-input outlined dense v-model="filterKeyword" label="ค้นหา"></q-input>
      <q-select
        v-model="visibleColumns"
        multiple
        outlined
        dense
        options-dense
        :display-value="$q.lang.table.columns"
        emit-value
        map-options
        :options="columns"
        option-value="name"
        options-cover
        style="min-width: 150px"
      >
      </q-select>
    </div>
  </q-toolbar>

  <d-table
    ref="table"
    :columns="columns"
    :rows="rows"
    :filter="filterKeyword"
    row-key="id"
    flat
    bordered
    :paging="true"
    dense
    class="custom-header-table"
    :visible-columns="visibleColumns"
    :separator="'cell'"
    :rows-per-page-options="[10, 25, 50, 100]"
  >
    <template v-slot:header="props">
      <q-tr :props="props">
        <q-th v-for="col in props.cols" :key="col.name" :props="props">
          <span class="text-weight-medium">{{ col.label }}</span>
        </q-th>
        <q-th auto-width />
      </q-tr>
    </template>
    <template v-slot:body="props">
      <q-tr :props="props" class="cursor-pointer">
        <q-td v-for="col in props.cols" :key="col.id" class="vertical-top">
          <div v-if="col.name == 'positions'">
            <div v-if="col.value.length !== 0">
              <div v-for="(pos, index) in col.value" :key="pos.id">
                {{ pos ? `- ${pos.name}` : "-" }}
              </div>
            </div>
            <div v-else>-</div>
          </div>
          <div v-else-if="col.name == 'capacitys'">
            <div v-if="col.value.length !== 0">
              <div v-for="competency in col.value" :key="competency.id">
                {{ competency ? `- ${competency.name}` : "-" }}
              </div>
            </div>
            <div v-else>-</div>
          </div>
          <div v-else>
            {{ col.value ? col.value : "-" }}
          </div>
        </q-td>
        <q-td auto-width>
          <q-btn
            color="edit"
            flat
            dense
            round
            class="q-mr-xs"
            size="12px"
            icon="edit"
            clickable
            @click="onEdit(props.row.id)"
          >
            <q-tooltip>แก้ไขข้อมูล</q-tooltip>
          </q-btn>
          <q-btn
            color="red"
            flat
            dense
            round
            size="12px"
            icon="mdi-delete"
            clickable
            @click.stop="
              dialogRemove($q, async () => await deleteData(props.row.id))
            "
            v-close-popup
          >
            <q-tooltip>ลบข้อมูล</q-tooltip>
          </q-btn>
        </q-td>
      </q-tr>
    </template>
  </d-table>

  <q-dialog v-model="modal" persistent>
    <q-card flat bordered style="min-width: 80vh">
      <q-form greedy @submit.prevent @validation-success="onSubmit">
        <Header
          :tittle="
            editStatus ? 'แก้ไขกลุ่มงานและตำแหน่ง' : 'เพิ่มกลุ่มงานและตำแหน่ง'
          "
          :close="close"
        />
        <q-separator />
        <q-card-section>
          <div class="row q-col-gutter-sm">
            <div class="col-4">
              <q-select
                dense
                v-model="groupName"
                label="กลุ่มงาน"
                outlined
                class="inputgreen"
                map-options
                option-label="name"
                option-value="id"
                :options="groupNameOp"
              />
            </div>
            <div class="col-4">
              <q-select
                dense
                v-model="position"
                label="ตำแหน่ง"
                outlined
                multiple
                emit-value
                map-options
                class="inputgreen"
                option-label="name"
                option-value="name"
                :options="positionOp"
                use-input
                @filter="(inputValue:any,doneFn:Function) => filterOption(inputValue, doneFn) "
              >
                <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-4">
              <q-select
                dense
                class="inputgreen"
                v-model="competency"
                label="สมรรถนะประจำกลุ่ม"
                outlined
                emit-value
                multiple
                map-options
                option-label="name"
                option-value="id"
                :options="competencyOp"
              />
            </div>
          </div>
        </q-card-section>
        <q-separator />
        <q-card-actions align="right" class="bg-white text-teal">
          <q-btn
            type="submit"
            for="#submitForm"
            unelevated
            dense
            class="q-px-md items-center"
            color="public"
            label="บันทึก"
          />
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>
