import { defineStore } from "pinia";
import { ref } from "vue";

import { useCounterMixin } from "@/stores/mixin";
import type {
  DataResponse,
  DataRow,
} from "../interface/response/personal/personal";

const { date2Thai, onSearchDataTable } = useCounterMixin();

export const usePersonalDataStore = defineStore("PersonalData", () => {
  const row = ref<DataRow[]>([]); // ข้อมูลในตาราง
  const rowMain = ref<DataRow[]>([]); // ข้อมูลในตาราง
  const currentTab = ref<string>("list_prefix"); // Tab ปัจจุบัน

  /**
   * บันทึกข้อมูลลงใน  row.value
   * @param data ข้อมูลรายการจาก API
   */
  async function save(data: DataResponse[]) {
    row.value = [];
    rowMain.value = [];
    const list = data.map((e) => ({
      ...e,
      createdAt: e.createdAt ? date2Thai(e.createdAt, false, true) : "-",
      lastUpdatedAt: e.lastUpdatedAt
        ? date2Thai(e.lastUpdatedAt, false, true)
        : "-",
    }));

    row.value = list;
    rowMain.value = list;
  }

  function onSearchData(keyword: string, columns: any = []) {
    row.value = onSearchDataTable(keyword, rowMain.value, columns);
  }

  return {
    save,
    row,
    currentTab,
    onSearchData,
  };
});
