/* 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

export function usePageSearch(searchCallback?: Fn, resetCallback?: Fn, searchFormConfig?: FormConfig) {
  const pageContentRef = ref<PageContentInstance>(null);

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

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

    console.log(searchFormConfig);

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

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

        if (startProp || endProp) {
          mergeParams[startProp] = mergeParams[field][0] ? dayjs(mergeParams[field][0]).format('YYYY-MM-DD hh:mm:ss') : "";
          mergeParams[endProp] = mergeParams[field][1] ? dayjs(mergeParams[field][1]).format('YYYY-MM-DD hh:mm:ss') : "";
          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(result);
    resetCallback && resetCallback()
  }

  return {
    pageContentRef,
    handleSearchClick,
    handleResetClick
  };
}
