/* eslint-disable prettier/prettier */
import { ref } from "vue";
import { PageContentInstance } from "/@/components/PageContent";
import { FormConfig } from "/@/components/PageSearch";
import dayjs from "dayjs";

type Fn = (params?: any) => any;

const convertDateVal = val => (val ? dayjs(val).format("YYYY-MM-DD") : "");
export function usePageSearch(
  searchCallback?: Fn,
  resetCallback?: Fn,
  searchFormConfig?: FormConfig,
  resetEmpty?: boolean
) {
  const pageContentRef = ref<PageContentInstance>(null);

  function handleSearchClick(params: any) {
    const { result, deleteProps } = searchCallback ? searchCallback(params) : { result: {}, deleteProps: [] };

    const mergeParams = { ...params, ...result };

    if (searchFormConfig) {
      const { formItems } = searchFormConfig;

      formItems.forEach(item => {
        const { field, type_field, otherOptions = {}, type } = item;
        const { startProp, endProp } = otherOptions;

        if ((startProp || endProp) && mergeParams[field]) {
          mergeParams[startProp] =
            type === "date_picker"
              ? convertDateVal(mergeParams[field][0])
              : mergeParams[field][0];
          mergeParams[endProp] =
            type === "date_picker"
              ? convertDateVal(mergeParams[field][1])
              : mergeParams[field][1];
          delete mergeParams[field];
        }

        if (type_field) {
          mergeParams[mergeParams[type_field]] = mergeParams[field];
          delete mergeParams[field];
          delete mergeParams[type_field];
        }
      });
    }

    deleteProps.forEach(key => delete mergeParams[key]);

    pageContentRef.value?.getPageData(mergeParams);
  }

  function handleResetClick(params?: any) {
    const { result } = searchCallback ? searchCallback(params) : { result: {} };
    pageContentRef.value?.getPageData(resetEmpty ? {} : result);
    resetCallback && resetCallback();
  }

  return {
    pageContentRef,
    handleSearchClick,
    handleResetClick
  };
}
