/* 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,
  lockKey?:string
) {
  const pageContentRef = ref<PageContentInstance>(null);

  function getMargeParams(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];
        }
      });

      return mergeParams
    }

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

    Object.keys(mergeParams).forEach(key => {
      if (Array.isArray(mergeParams[key]) && mergeParams[key].length === 0) {
         mergeParams[key] = ""
      }
    })
  }

  function handleSearchClick(params: any) {
    const mergeParams = getMargeParams(params)
    pageContentRef.value?.getPageData(mergeParams);
  }

  function handleintial(params: any) {
    const mergeParams = getMargeParams(params)
    pageContentRef.value?.intialData(mergeParams);
  }

  function handleResetClick(params?: any) {
    console.log(params);

    const { result } = resetCallback ? resetCallback(params) : { result: {} };
    pageContentRef.value?.getPageData(resetCallback ? result : params);
    resetCallback && resetCallback();
  }

  return {
    pageContentRef,
    handleSearchClick,
    handleResetClick,
    handleintial
  };
}
