//import type { ColEx } from '../types';
import type { AdvanceState } from '../types/hooks';
import { ComputedRef, Ref } from 'vue';
import type { FormProps, FormSchema } from '../types/form';
import {
  // computed,
  unref,
  watch,
} from 'vue';
// import {
//   isBoolean,
//   isFunction,
//   //  isNumber, isObject
// } from '/@/utils/is';
//import { useBreakpoint } from '/@/hooks/event/useBreakpoint';
//import { useDebounceFn } from '@vueuse/core';

//const BASIC_COL_LEN = 24;

interface UseAdvancedContext {
  advanceState: AdvanceState;
  emit: EmitType;
  getProps: ComputedRef<FormProps>;
  getSchema: ComputedRef<FormSchema[]>;
  formModel: Recordable;
  defaultValueRef: Ref<Recordable>;
}

export default function ({
  advanceState,
  emit,
  getProps,
  getSchema,
}: // formModel,
// defaultValueRef
UseAdvancedContext) {
  // const {
  //   realWidthRef,
  //   // screenEnum,
  //   //screenRef
  // } = useBreakpoint();
  // const searchWidth = ref<any>({
  //   xxl: { row: 'calc(100% - 170px)', col: 'calc(100% - 178px)' },
  //   xl: { row: 'calc(100% - 170px)', col: 'calc(100% - 178px)' },
  //   lg: { row: 'calc(100% - 170px)', col: 'calc(100% - 178px)' },
  //   md: { row: 'calc(100% - 170px)', col: 'calc(100% - 178px)' },
  //   sm: { row: 'calc(100% - 170px)', col: 'calc(100% - 178px)' },
  //   xs: { row: 'calc(100% - 170px)', col: 'calc(100% - 178px)' },
  //   span: { row: 'calc(100% - 170px)', col: 'calc(100% - 178px)' },
  // });
  // const getEmptySpan = computed((): number => {
  //   if (!advanceState.isAdvanced) {
  //     return 0;
  //   }
  //   // For some special cases, you need to manually specify additional blank lines
  //   const emptySpan = unref(getProps).emptySpan || 0;

  //   if (isNumber(emptySpan)) {
  //     return emptySpan;
  //   }
  //   if (isObject(emptySpan)) {
  //     const { span = 0 } = emptySpan;
  //     const screen = unref(screenRef) as string;

  //     const screenSpan = (emptySpan as any)[screen.toLowerCase()];
  //     return screenSpan || span || 0;
  //   }
  //   return 0;
  // });

  // const debounceUpdateAdvanced = useDebounceFn(updateAdvanced, 30);

  watch(
    // [
    // () => unref(getSchema),
    () => [unref(getProps).searchWidth],
    // () => unref(realWidthRef)
    // ],
    () => {
      // console.log(val, 'searchWidthsearchWidthsearchWidth');
      const { showAdvancedButton } = unref(getProps);
      if (showAdvancedButton) {
        //debounceUpdateAdvanced();
        updateAdvanced();
      }
    },
    { immediate: true },
  );

  // function compulateSearchWidth(obj, itemColSum) {
  //   const tablewidth = unref(getProps).tableWidth;
  //   // const curObj = { xxl: 0, xl: 0, xs: 0, sm: 0, md: 0, lg: 0, span: 0 };
  //   // const width = unref(realWidthRef);

  //   //const curSpan = obj.span;
  //   // schema.forEach((o) => {
  //   //   if (o.isAdvanced) {
  //   //     for (const i in o.colProps) {
  //   //       obj[i] += o.colProps[i] ? Number(o.colProps[i]) : baseColProps[i];
  //   //     }
  //   //   }
  //   // });

  //   // if (width > screenEnum.XS) {
  //   //   curSpan = obj.xs ? Number(obj.xs) : curSpan;
  //   // }
  //   // if (width > screenEnum.SM) {
  //   //   curSpan = obj.sm ? Number(obj.sm) : curSpan;
  //   // }
  //   // if (width > screenEnum.MD) {
  //   //   curSpan = obj.md ? Number(obj.md) : curSpan;
  //   // }
  //   // if (width > screenEnum.LG) {
  //   //   curSpan = obj.lg ? Number(obj.lg) : curSpan;
  //   // }
  //   // if (width > screenEnum.XL) {
  //   //   curSpan = obj.xl ? Number(obj.xl) : curSpan;
  //   // }
  //   // if (width > screenEnum.XXL) {
  //   //   curSpan = obj.xxl ? Number(obj.xxl) : curSpan;
  //   // }

  //   for (const i in obj) {
  //     let str = '100%';
  //     let row = '100%';
  //     if (((24 - itemColSum) / 24) * tablewidth! >= 178 || itemColSum >= 24) {
  //       str = '(100% - 178px)';
  //       row = '(100% - 178px)';
  //     }
  //     searchWidth.value[i].row = 'calc(' + row + ')';
  //     searchWidth.value[i].col = 'calc(' + str + ' * ' + itemColSum / 24 + ')';
  //   }
  // }
  // function getAdvanced(
  //   itemCol: Partial<ColEx>,
  //   itemColSum = 0,
  //   //isLastAction = false
  // ) {
  //   const { tableWidth } = unref(getProps);
  //   const width = tableWidth || 0;

  //   const spanWidth = itemCol.span as number;
  //   const xsWidth = spanWidth || parseInt(itemCol.xs as number) || 24;
  //   const smWidth = spanWidth || parseInt(itemCol.sm as number) || 12;
  //   const mdWidth = spanWidth || parseInt(itemCol.md as number) || 8;
  //   const lgWidth = spanWidth || parseInt(itemCol.lg as number) || 8;
  //   const xlWidth = spanWidth || parseInt(itemCol.xl as number) || 8;
  //   const xxlWidth = spanWidth || parseInt(itemCol.xxl as number) || 8;
  //   // const widthObj = {
  //   //   span: spanWidth,
  //   //   xs: xsWidth,
  //   //   sm: smWidth,
  //   //   md: mdWidth,
  //   //   lg: lgWidth,
  //   //   xl: xlWidth,
  //   //   xxl: xxlWidth,
  //   // };
  //   if (width <= screenEnum.XS) {
  //     itemColSum += xsWidth;
  //   } else if (width > screenEnum.XS && width <= screenEnum.SM) {
  //     itemColSum += xsWidth;
  //   } else if (width > screenEnum.SM && width <= screenEnum.MD) {
  //     itemColSum += smWidth;
  //   } else if (width > screenEnum.MD && width <= screenEnum.LG) {
  //     itemColSum += mdWidth;
  //   } else if (width > screenEnum.LG && width <= screenEnum.XL) {
  //     itemColSum += lgWidth;
  //   } else if (width > screenEnum.XL && width <= screenEnum.XXL) {
  //     itemColSum += xlWidth;
  //   } else {
  //     itemColSum += xxlWidth;
  //   }

  //   // if (isLastAction) {
  //   advanceState.hideAdvanceBtn = false;

  //   if (itemColSum <= BASIC_COL_LEN) {
  //     // When less than or equal to 2 lines, the collapse and expand buttons are not displayed
  //     advanceState.hideAdvanceBtn = true;
  //     advanceState.isAdvanced = true;
  //     // compulateSearchWidth(widthObj, itemColSum);
  //   } else if (itemColSum > BASIC_COL_LEN) {
  //     advanceState.hideAdvanceBtn = false;
  //     advanceState.isAdvanced = false;

  //     // More than 3 lines collapsed by default
  //   } else if (!advanceState.isLoad) {
  //     advanceState.isLoad = true;
  //     advanceState.isAdvanced = !advanceState.isAdvanced;
  //   }
  //   return { isAdvanced: true, itemColSum };
  //   //}

  //   // if (itemColSum > BASIC_COL_LEN * (unref(getProps).alwaysShowLines || 1)) {
  //   //   return { isAdvanced: advanceState.isAdvanced, itemColSum };
  //   // }
  //   // else {
  //   //   // The first line is always displayed
  //   //   return { isAdvanced: true, itemColSum };
  //   // }
  // }
  function getMinSearchWidth() {
    let itemWidthTotal = 0;
    const { searchWidth, showResetButton } = unref(getProps);

    const itemLenArr: Array<number> = [];
    const len = unref(getSchema).length;
    for (let index = 0; index < len; index++) {
      const schema = unref(getSchema)[index];
      const labelW =
        String(schema.label).length * isAlphaString1(schema.label) > 120
          ? 120
          : String(schema.label).length * isAlphaString1(schema.label);
      itemWidthTotal +=
        labelW +
        10 +
        16 +
        (['RangePicker', 'Input'].includes(schema.component)
          ? 200
          : ['InputNumber'].includes(schema.component)
          ? 182
          : 180);
      itemLenArr.push(itemWidthTotal);
    }
    // console.log(itemLenArr, tableWidth, toolBarWidth, 'itemLenArritemLenArritemLenArr');
    if (len == 1) {
      advanceState.hideAdvanceBtn = true;
    } else if (len == 2) {
      if (itemLenArr[1] + (showResetButton ? 175 : 96) <= searchWidth!) {
        advanceState.hideAdvanceBtn = true;
      } else if (itemLenArr[0] + (showResetButton ? 224 : 144) <= searchWidth!) {
        advanceState.hideAdvanceBtn = false;
      } else {
        advanceState.hideAdvanceBtn = false;
      }
    } else if (len >= 3) {
      computeParallel(len, itemLenArr, searchWidth, showResetButton);
      // console.log(toolBarWidth, 'tableWidth, toolBarWidth');
      // searchWidth = newSearchWidth;
    }

    if (!advanceState.isLoad) {
      advanceState.isLoad = true;
      advanceState.isAdvanced = !advanceState.isAdvanced;
    }
    return { searchWidth };
  }
  function computeParallel(len, itemLenArr, newSearchWidth, showResetButton) {
    for (let x = len - 1; x >= 0; x--) {
      if (x == len - 1) {
        if (itemLenArr[x] + (showResetButton ? 175 : 96) <= newSearchWidth) {
          advanceState.hideAdvanceBtn = true;
          break;
        }
      } else if (x < len - 1 && x >= 1) {
        if (itemLenArr[x] + (showResetButton ? 224 : 144) <= newSearchWidth) {
          advanceState.hideAdvanceBtn = false;
          break;
        }
      } else {
        advanceState.hideAdvanceBtn = false;
      }
    }
  }
  function updateAdvanced() {
    // let itemColSum = 0;
    let itemWidth = 0;
    // const itemSpan = 0;
    getMinSearchWidth();
    const { tableWidth, searchWidth, isSearch, showResetButton } = unref(getProps);

    // const { baseColProps = {} } = unref(getProps);

    for (let index = 0; index < unref(getSchema).length; index++) {
      const schema = unref(getSchema)[index];
      // const {
      //   //show,
      //   colProps,
      // } = schema;
      // let isShow = true;

      // if (isBoolean(show)) {
      //   isShow = show;
      // }

      // if (isFunction(show)) {
      //   isShow = show({
      //     schema: schema,
      //     model: formModel,
      //     field: schema.field,
      //     values: {
      //       ...unref(defaultValueRef),
      //       ...formModel,
      //     },
      //   });
      // }

      //if (colProps || baseColProps) {
      // const { itemColSum: sum, isAdvanced } = getAdvanced(
      //   { ...baseColProps, ...colProps },
      //   itemColSum,
      // );
      schema.isAdvanced = true;
      if (tableWidth !== undefined || isSearch) {
        //  console.log(searchWidth, 'searchWidthsearchWidth');
        const labelW =
          String(schema.label).length * isAlphaString1(schema.label) > 120
            ? 120
            : String(schema.label).length * isAlphaString1(schema.label);
        itemWidth +=
          labelW +
          10 +
          16 +
          (['RangePicker', 'Input'].includes(schema.component)
            ? 200
            : ['InputNumber'].includes(schema.component)
            ? 182
            : 180);
        // itemSpan += sum || 0;
        // if (index <= 2) minSearchWidth = itemWidth + (isAdvanced ? 128 : 150);
        const minSearchWidth =
          searchWidth! -
          (!advanceState.hideAdvanceBtn
            ? showResetButton
              ? 224
              : 144
            : showResetButton
            ? 175
            : 96);

        if (itemWidth <= minSearchWidth) {
          schema.show = true;
        } else {
          schema.show = advanceState.isAdvanced ? true : false;
          // itemColSum += 1;
        }
        // } else {
        //   itemColSum = 0;
        // }
      }
    }
    // if ((tableWidth !== undefined && toolBarWidth !== undefined) || isSearch) {
    //   if (itemColSum > 0) {
    //     advanceState.hideAdvanceBtn = false;
    //     advanceState.isAdvanced = false;
    //   } else {
    //     advanceState.hideAdvanceBtn = true;
    //     advanceState.isAdvanced = true;
    //   }
    // }

    // advanceState.actionSpan = (realItemColSum % BASIC_COL_LEN) + unref(getEmptySpan);

    // getAdvanced(unref(getProps).actionColOptions || { span: BASIC_COL_LEN }, itemColSum, true);

    emit('advanced-change');
  }

  function isAlphaString1(str) {
    return /^[a-zA-Z]+$/.test(str) ? 10 : 15;
  }
  function handleToggleAdvanced() {
    let itemWidth = 0;
    getMinSearchWidth();
    advanceState.isAdvanced = !advanceState.isAdvanced;
    // console.log(unref(realWidthRef), 'widthwidth');

    const { tableWidth, searchWidth, isSearch, showResetButton } = unref(getProps);
    if (tableWidth !== undefined || isSearch) {
      for (let index = 0; index < unref(getSchema).length; index++) {
        const schema = unref(getSchema)[index];
        const labelW =
          String(schema.label).length * isAlphaString1(schema.label) > 120
            ? 120
            : String(schema.label).length * isAlphaString1(schema.label);
        itemWidth +=
          labelW +
          10 +
          16 +
          (['RangePicker', 'Input'].includes(schema.component)
            ? 200
            : ['InputNumber'].includes(schema.component)
            ? 182
            : 180);
        // if (index === 0) minSearchWidth = itemWidth + (showAdvancedButton ? 128 : 150);
        const minSearchWidth =
          searchWidth! -
          (!advanceState.hideAdvanceBtn
            ? showResetButton
              ? 224
              : 144
            : showResetButton
            ? 175
            : 96);
        if (itemWidth <= minSearchWidth) {
          schema.show = true;
        } else {
          schema.show = advanceState.isAdvanced ? true : false;
        }
      }
    }
  }

  return { handleToggleAdvanced };
}
