<script setup lang="ts">
import { ref, onMounted, reactive, watch } 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,
  NewPagination,
} 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 rows = ref<any>([]);
const editStatus = ref<boolean>(false);
const groupName = ref<any>();
const position = ref<any>();
const competency = ref<any>();

const groupNameOp = ref<DataOption[]>([]);
const groupNameOpMain = ref<DataOption[]>([]);
const positionOp = ref<DataOption[]>([]);
const positionMainOp = ref<DataOption[]>([]);
const competencyOp = ref<DataOption[]>([]);
const competencyOpMain = ref<DataOption[]>([]);

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"]);

const formQuery = reactive({
  page: 1,
  pageSize: 10,
  keyword: "",
});
const totalList = ref<number>(1); //จำนวนข้อมูลรายการ

/** ดึงข้อมูล */
async function getData() {
  showLoader();
  http
    .get(
      config.API.kpiLink +
        `?page=${formQuery.page}&pageSize=${formQuery.pageSize}&keyword=${formQuery.keyword}`
    )
    .then((res) => {
      const data = res.data.result;
      totalList.value = Math.ceil(res.data.result.total / formQuery.pageSize);
      rows.value = data.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+`?pageSize=50`)
    .then(async (res) => {
      const dataOp = res.data.result.data;
      const uniqueNames = new Set();
      const filteredData = dataOp
        .filter((item: any) => {
          if (!uniqueNames.has(item.id)) {
            uniqueNames.add(item.nameGroupKPI);
            return true;
          }
          return false;
        })
        .map((item: any) => ({
          id: item.id,
          name: item.nameGroupKPI,
        }));

      groupNameOpMain.value = filteredData;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/** ดึงข้อมูล */
async function getCompetency() {
  showLoader();
  await http
    .get(config.API.kpiCapacity + `?type=GROUP&pageSize=50`)
    .then(async (res) => {
      const dataOp = res.data.result.data;
      const uniqueNames = new Set();
      const filteredData = dataOp
        .filter((item: any) => {
          if (!uniqueNames.has(item.id)) {
            uniqueNames.add(item.name);
            return true;
          }
          return false;
        })
        .map((item: any) => ({
          id: item.id,
          name: item.name,
        }));

      competencyOpMain.value = filteredData;
    })
    .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) => ({
        id:i.id,
        name:i.name
      }));
    })
    .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.map((i:any)=> i.id)
  };
  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 = null;
  competency.value = null;
}

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 filterOptionGroup(val: any, update: Function) {
  update(() => {
    groupNameOp.value = groupNameOpMain.value.filter(
      (v: any) => v.name.indexOf(val) > -1
    );
  });
}

/**
 * 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
    );
  });
}

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

/**
 * function updatePagination
 * @param newPagination ข้อมูล Pagination ใหม่
 */
function updatePagination(newPagination: NewPagination) {
  formQuery.page = 1;
  formQuery.pageSize = newPagination.rowsPerPage;
}
function fetchNewList() {
  formQuery.page = 1;
  getData();
}

watch(
  () => formQuery.pageSize,
  () => {
    fetchNewList();
  }
);

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="formQuery.keyword"
        label="ค้นหา"
        @keyup.enter="fetchNewList()"
      >
        <template v-slot:append>
          <q-icon v-if="formQuery.keyword == ''" name="search" />
          <q-icon
            v-if="formQuery.keyword !== ''"
            name="clear"
            class="cursor-pointer"
            @click="(formQuery.keyword = ''), fetchNewList()"
          /> </template
      ></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"
    row-key="id"
    flat
    bordered
    dense
    class="custom-header-table"
    :visible-columns="visibleColumns"
    :separator="'cell'"
    :rows-per-page-options="[10, 25, 50, 100]"
    @update:pagination="updatePagination"
  >
    <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>
    <template v-slot:pagination="scope">
      <q-pagination
        v-model="formQuery.page"
        active-color="primary"
        color="dark"
        :max="Number(totalList)"
        size="sm"
        boundary-links
        direction-links
        :max-pages="5"
        @update:model-value="getData"
      ></q-pagination>
    </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"
                use-input
                @filter="(inputValue:any,doneFn:Function) => filterOptionGroup(inputValue, doneFn) "
                hide-bottom-space
                lazy-rules
                :rules="[(val:string) => !!val || `${'กรุณาเลือกกลุ่มงาน'}`,]"
                >
                <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
                v-model="position"
                label="ตำแหน่ง"
                outlined
                multiple
                emit-value
                map-options
                class="inputgreen"
                option-label="name"
                option-value="name"
                :options="positionOp"
                :rules="[(val:string) => !!val || `${'กรุณาเลือกตำแหน่ง'}`,]"
                hide-bottom-space
                lazy-rules
                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
                multiple
                map-options
                option-label="name"
                option-value="id"
                :rules="[(val:string) => !!val || `${'กรุณาเลือกสมรรถนะประจำกลุ่ม'}`,]"
                hide-bottom-space
                lazy-rules
                :options="competencyOp"
                use-input
                @filter="(inputValue:any,doneFn:Function) => filterOptionCompetency(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>
        </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>
