import { defineStore } from "pinia";
import { ref } from "vue";
import { useCounterMixin } from "@/stores/mixin";

import type { QTableProps } from "quasar";
import type {
  InvestigatefactsDataRowType,
  DataOption,
  DataNumberOption,
} from "@/modules/11_discipline/interface/index/Main";
import type {
  ListData,
  ocListType,
} from "@/modules/11_discipline/interface/response/investigate";
import { useDisciplineMainStore } from "@/modules/11_discipline/store/Main";
const mainStore = useDisciplineMainStore();

const mixin = useCounterMixin();
const { date2Thai } = mixin;
const organizationIdOp = ref<DataOption[]>([]);
const consideredAgencytoptions = ref<DataOption[]>([]);

/*** store ของข้อมูลสืบสวนข้อเท็จจริง */
export const useInvestigateFactStore = defineStore(
  "DisciplineInvestigateFact",
  () => {
    const tabMenu = ref<string>("investigatefacts");
    const complaintId = ref<string>("");
    const rows = ref<InvestigatefactsDataRowType[]>([]);
    const respondentTypeOps = ref<DataOption[]>(
      mainStore.complainantoptionsMain
    );

    const daysExtendOps = ref<DataNumberOption[]>([
      { id: 15, name: "15 วัน" },
      { id: 30, name: "30 วัน" },
      { id: 45, name: "45 วัน" },
      { id: 60, name: "60 วัน" },
    ]);

    const investigationDetailOps = ref<DataOption[]>([
      { id: "APPOINT_DIRECTORS", name: "แต่งตั้งกรรมการสืบสวน" },
      { id: "SECRET_INVESTIGATION", name: "สืบสวนทางลับ" },
      { id: "OTHER", name: "อื่นๆ" },
    ]);

    const faultOps = ref<DataOption[]>([
      { id: "NEW", name: "กำลังสืบสวน" },
      { id: "STOP", name: "ยุติเรื่อง" },
      { id: "SEND_DISCIPLINARY", name: "ส่งไปสอบสวนแล้ว" },
    ]);

    const daysExtendOp = ref<DataNumberOption[]>(daysExtendOps.value);
    const investigationDetailOp = ref<DataOption[]>(
      investigationDetailOps.value
    );
    const faultOp = ref<DataOption[]>(faultOps.value);
    const statusOptions = ref<DataOption[]>([
      { id: "ALL", name: "ทั้งหมด" },
      { id: "NEW", name: "กำลังสืบสวน" },
      { id: "STOP", name: "ยุติเรื่อง" },
      { id: "SEND_DISCIPLINARY", name: "ส่งไปสอบสวนแล้ว" },
    ]);
    const visibleColumns = ref<string[]>([
      "no",
      "title",
      "respondentType",
      "offenseDetails",
      "investigationDetail",
      "dateInvestigate",
      "investigationStatusResult",
      "createdAt",
      "status",
    ]);

    // หัวตาราง
    const columns = ref<QTableProps["columns"]>([
      {
        name: "no",
        align: "center",
        label: "ลำดับ",
        sortable: false,
        field: "no",
        headerStyle: "font-size: 14px",
        style: "font-size: 14px",
      },
      {
        name: "title",
        align: "left",
        label: "เรื่องร้องเรียน",
        sortable: true,
        field: "title",
        headerStyle: "font-size: 14px",
        style: "font-size: 14px",
      },
      {
        name: "respondentType",
        align: "left",
        label: "ผู้ถูกสืบสวน",
        sortable: true,
        field: "respondentType",
        headerStyle: "font-size: 14px",
        style: "font-size: 14px",
        sort: (a: string, b: string) =>
          a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
      },
      {
        name: "offenseDetails",
        align: "left",
        label: "ลักษณะความผิด",
        sortable: true,
        field: "offenseDetails",
        headerStyle: "font-size: 14px",
        style: "font-size: 14px",
        sort: (a: string, b: string) =>
          a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
      },
      {
        name: "investigationDetail",
        align: "left",
        label: "ลักษณะการสืบสวน",
        sortable: true,
        field: "investigationDetail",
        headerStyle: "font-size: 14px",
        style: "font-size: 14px",
        sort: (a: string, b: string) =>
          a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
      },
      {
        name: "dateInvestigate",
        align: "left",
        label: "วันที่สืบสวน",
        sortable: true,
        field: "dateInvestigate",
        headerStyle: "font-size: 14px",
        style: "font-size: 14px",
        sort: (a: string, b: string) =>
          a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
      },
      {
        name: "investigationStatusResult",
        align: "left",
        label: "ผลการสืบสวน",
        sortable: true,
        field: "investigationStatusResult",
        headerStyle: "font-size: 14px",
        style: "font-size: 14px",
        sort: (a: string, b: string) =>
          a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
      },
      {
        name: "createdAt",
        align: "left",
        label: "วันที่รับเรื่อง",
        sortable: true,
        field: "createdAt",
        headerStyle: "font-size: 14px",
        style: "font-size: 14px",
        sort: (a: string, b: string) =>
          a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
      },
      {
        name: "status",
        align: "left",
        label: "สถานะ",
        sortable: false,
        field: "status",
        headerStyle: "font-size: 14px",
        style: "font-size: 14px",
      },
    ]);

    /**
     * ดึงข้อมูล เฉพาะ สังกัด โดย เก็บ id/name
     * @param data ชุดข้อมูลรวม
     */
    function ocListFn(data: ocListType[]) {
      let dataList: DataOption[] = data.map((item: ocListType) => ({
        id: item.organizationId,
        name: item.organizationName,
      }));
      consideredAgencytoptions.value = dataList;
      organizationIdOp.value = dataList;
    }

    /**
     * ฟิลเตอร์ข้อมูลจาก input
     * @param val ค่าที่ป้อนให้ input
     * @param update function จาก quasar
     * @param type type ที่กำหนด ของ input นั้นๆ
     */
    function filterFnOptionsType(
      val: string | number,
      update: any,
      type: string
    ) {
      update(() => {
        if (type === "faultOp") {
          faultOp.value = faultOps.value.filter(
            (v: any) => v.name.toLowerCase().indexOf(val) > -1
          );
        } else if (type === "investigationOp") {
          investigationDetailOp.value = investigationDetailOps.value.filter(
            (v: any) => v.name.toLowerCase().indexOf(val) > -1
          );
        } else if (type === "daysExtendOp") {
          daysExtendOp.value = daysExtendOps.value.filter(
            (v: any) => v.id.indexOf(val) > -1
          );
        }
      });
    }

    /**
     * ฟิลเตอร์ข้อมูลจาก input
     * @param val ค่าที่ป้อนให้ input
     * @param update function จาก quasar
     * @param type type ที่กำหนด ของ input นั้นๆ
     */
    function filterSelector(val: string, update: Function, type: string) {
      update(() => {
        const needle = val.toLowerCase();

        if (type === "filterrespondentType") {
          respondentTypeOps.value = mainStore.complainantoptionsMain.filter(
            (v: any) => v.name.toLowerCase().indexOf(needle) > -1
          );
        }
      });
    }

    /**
     * จัดเรียงข้อมูลจาก API
     * @param data ข้อมูลจาก API
     */
    async function fecthList(data: ListData[]) {
      rows.value = await data.map((e: ListData) => {
        return {
          id: e.id,
          title: e.title ? e.title : "-",
          respondentType: e.respondentType
            ? mainStore.convertComplaintType(e.respondentType)
            : "-",
          offenseDetails: e.offenseDetails
            ? mainStore.convertOffenseDetailst(e.offenseDetails)
            : "-",
          investigationDetail: e.investigationDetail
            ? convertInvestigationDetail(e.investigationDetail)
            : "-",
          dateInvestigate:
            e.investigationDateStart && e.investigationDateEnd
              ? `${date2Thai(e.investigationDateStart)} - ${date2Thai(
                  e.investigationDateEnd
                )}`
              : "-",
          investigationStatusResult: e.investigationStatusResult
            ? mainStore.convertStatusResult(e.investigationStatusResult)
            : "-",
          createdAt: e.createdAt ? date2Thai(e.createdAt as Date) : "-",
          status: e.status ? convertStatus(e.status) : "-",
        };
      });
    }

    /**
     * แปลง status เป็น text
     * @param val status
     * @returns text
     */
    function convertInvestigationDetail(val: string) {
      const result = investigationDetailOps.value.find(
        (x: any) => x.id == val
      )?.name;
      return result ? result : "-";
    }

    /**
     * แปลง status เป็น text
     * @param val status
     * @returns text
     */
    function convertStatus(val: string) {
      const result = faultOps.value.find((x: any) => x.id == val)?.name;
      return result ? result : "-";
    }

    return {
      tabMenu,
      complaintId,
      fecthList,
      rows,
      daysExtendOps,
      investigationDetailOps,
      faultOps,
      filterFnOptionsType,
      faultOp,
      daysExtendOp,
      investigationDetailOp,
      visibleColumns,
      columns,
      filterSelector,
      respondentTypeOps,
      organizationIdOp,
      ocListFn,
      statusOptions,
    };
  }
);
