import { ref, watchEffect, unref, useSlots, nextTick } from 'vue';
import { cloneDeep, isFunction, mergeWith } from 'lodash-es';
import { EditableCell } from '../components';
import { ColumnKeyFlag, CustomRenderParams } from '../types/column';
import type { Slots } from 'vue';
import type {
  TableActionType,
  TableColumn,
  TableMethods,
  TableState,
  DynamicTableProps,
  DynamicTableEmitFn,
} from '@/components/lt-a-table/src';
import type { FormSchema } from '@/components/lt-a-form/src';
import { isBoolean } from '@/utils/is';
import { TableAction } from '@/components/lt-a-table/src/components';
import { getFixedCols } from './commonMethods';
import { i18n } from '../../../../locales/index';

export type UseTableColumnsContext = {
  state: TableState;
  props: DynamicTableProps;
  methods: TableMethods;
  tableAction: TableActionType;
  slots: Slots;
  emit: DynamicTableEmitFn;
  tableID: String;
};

export const useColumns = ({
  state,
  methods,
  props,
  tableAction,
  tableID,
}: UseTableColumnsContext) => {
  const { t } = i18n.global;
  const slots = useSlots();
  const innerColumns = ref(props.columns);
  const { getColumnKey, initColumnFilter, showEditDlg } = methods;
  // const { setProps } = tableAction;
  const { getProps } = state;
  const { isEditable } = tableAction;

  watchEffect(() => {
    const innerProps = { ...unref(getProps) };
    const ColumnKeyFlags = Object.keys(ColumnKeyFlag);
    let columns = cloneDeep(innerProps!.columns!.filter((n) => !n.hideInTable));
    // 是否添加序号列
    if (innerProps?.showIndex) {
      const indexCols = columns.filter((item) => {
        return item.dataIndex == 'INDEX';
      });
      if (indexCols.length == 0) {
        columns.unshift({
          dataIndex: 'INDEX',
          title: '序号',
          width: 60,
          align: 'center',
          fixed: 'left',
          ...innerProps?.indexColumnProps,
          customRender: ({ index }) => {
            const getPagination = unref(state.paginationRef);
            if (isBoolean(getPagination)) {
              return index + 1;
            }
            const { current = 1, pageSize = 10 } = getPagination!;
            return ((current < 1 ? 1 : current) - 1) * pageSize + index + 1;
          },
        } as TableColumn);
      }
    }
    if (innerProps.showEditInDialog) {
      const showCols = columns.filter((item) => {
        return item.dataIndex == 'SHOW';
      });
      if (showCols.length == 0) {
        columns.push({
          dataIndex: 'SHOW',
          title: t('component.table.show'),
          width: 60,
          align: 'center',
          fixed: 'right',
          ...innerProps?.indexColumnProps,
          customRender: ({ record }) => {
            return setBtnOperate(record);
          },
        } as TableColumn);
      }
    }
    columns = getFixedCols(columns);
    if (innerProps.isAutoEditable) {
      //如果是可编辑表格，则不在此生成列信息  因为列改变，都会进入这里，因此不能用原始的列信息进行计算
      // @ts-ignore
      innerColumns.value = columns; 
      nextTick(() => {
        initColumnFilter(tableID, props);
      });
    } else {
      innerColumns.value = columns.map((item) => {
        const customRender = item.customRender;
        const rowKey = props.rowKey ? (props.rowKey as string) : '_tableKey'; //如果外部没有传进来，则使用默认key
        const columnKey = getColumnKey(item) as string;
        item.ellipsis = true; //设置宽度超长的时候，要自动
        item.customRender = (options) => {
          options as CustomRenderParams<Recordable<any>>;
          const { record, index, text } = options;
          /** 当前行是否开启了编辑行模式 */
          const isEditableRow = isEditable(record[rowKey]);
          /** 是否开启了单元格编辑模式 */
          const isEditableCell = innerProps.editableType === 'cell';
          /** 当前单元格是否允许被编辑 */
          const isCellEditable = isBoolean(item.editable)
            ? item.editable
            : typeof item.editable != 'undefined'
            ? true
            : false;
          /** 是否允许被编辑 */
          const isShowEditable =
            (isEditableRow || isEditableCell) &&
            isCellEditable &&
            !ColumnKeyFlags.includes(columnKey);
          return isShowEditable ? (
            <EditableCell
              schema={getColumnFormSchema(item, record)}
              rowKey={record[rowKey] ?? index}
              editableType={innerProps.editableType}
              //@ts-ignore
              column={options}
              v-slots={slots}
            >
              {customRender?.(options) ?? text}
            </EditableCell>
          ) : (
            customRender?.(options)
          );
        };

        // 操作列
        if (item.actions && columnKey === ColumnKeyFlag.ACTION) {
          item.customRender = (options) => {
            const { record, index } = options;
            return (
              <TableAction
                //@ts-ignore
                actions={item.actions!(options, tableAction)}
                rowKey={record[rowKey] ?? index}
                //@ts-ignore
                columnParams={options}
              />
            );
          };
        }
        return {
          key: item.key ?? (item.dataIndex as Key),
          dataIndex: item.dataIndex ?? (item.key as Key),
          ...item,
        } as TableColumn;
      });
      // setProps({
      //   columns: innerColumns.value,
      // });
      nextTick(() => {
        initColumnFilter(tableID, props);
      });
    }
  });

  function setBtnOperate(record) {
    return (
      <span>
        <a-button
          size="small"
          title={t('common.edit')}
          label={t('common.edit')}
          style="color:#4AA4FA"
          type="text"
          //@ts-ignore
          onClick={btnClick.bind(this, record)}
        >
          <em class="icon icon-location-arrow" style="color:#4AA4FA"></em>
        </a-button>
      </span>
    );
  }

  function btnClick(record) {
    showEditDlg(record);
    // emit('edit-in-dlg', record);
  }

  function mergeCustomizer(objValue, srcValue, key) {
    /** 这里着重处理 `componentProps` 为函数时的合并处理 */
    if (key === 'componentProps') {
      return (...rest) => {
        return {
          ...(isFunction(objValue) ? objValue(...rest) : objValue),
          ...(isFunction(srcValue) ? srcValue(...rest) : srcValue),
        };
      };
    }
  }

  /** 获取当前行的form schema */
  const getColumnFormSchema = (item: TableColumn, record: Recordable): FormSchema<string> => {
    const key = getColumnKey(item) as string;
    /** 是否继承搜索表单的属性 */
    const isExtendSearchFormProps = !Object.is(
      item.editFormItemProps?.extendSearchFormProps,
      false,
    );

    return {
      field: `${record[props.rowKey as string]}.${item.searchField ?? key}`,
      component: 'Input',
      defaultValue: record[key],
      colProps: {
        span: unref(getProps).editableType === 'cell' ? 20 : 24,
      },
      formItemProps: {
        help: '',
      },
      ...(isExtendSearchFormProps
        ? mergeWith(cloneDeep(item.formItemProps), item.editFormItemProps, mergeCustomizer)
        : item.editFormItemProps),
    };
  };

  return {
    innerColumns,
  };
};
