import { reactive, readonly } from 'vue';

var useTableSort = _ref => {
  let {
    ctx,
    columns
  } = _ref;
  const sortState = reactive({});
  const handleRowDataBySort = (data, param) => {
    const {
      prop,
      order,
      sorter
    } = param;
    let nextData = data;
    if (order === 'ascend') {
      nextData = data.sort((a, b) => {
        let res = 0;
        if (typeof sorter === 'function') {
          try {
            res = sorter(a, b) ? 1 : -1;
          } catch (e) {}
        }
        if (sorter === 'default') {
          res = a[prop] > b[prop] ? 1 : -1;
        }
        return res;
      });
    }
    if (order === 'descend') {
      nextData = data.sort((a, b) => {
        let res = 0;
        if (typeof sorter === 'function') {
          try {
            res = sorter(a, b) ? -1 : 1;
          } catch (e) {}
        }
        if (sorter === 'default') {
          res = a[prop] > b[prop] ? -1 : 1;
        }
        return res;
      });
    }
    ctx.emit('afterSort', readonly(nextData));
    return nextData;
  };
  const handleClickSortHeader = _ref2 => {
    let {
      column
    } = _ref2;
    if (!column.props.sortable) {
      return;
    }
    if (sortState.prop !== column.props.prop) {
      const order = column.props.sortDirections[0];
      Object.assign(sortState, {
        prop: column.props.prop,
        order,
        sorter: column.props.sorter
      });
    } else {
      const index = column.props.sortDirections.indexOf(sortState.order);
      const order = column.props.sortDirections[index + 1];
      Object.assign(sortState, {
        order: order !== null && order !== void 0 ? order : false,
        sorter: column.props.sorter
      });
    }
    ctx.emit('sortChange', readonly(sortState));
  };
  const sort = (prop, order) => {
    var _column$props;
    const column = columns.value.find(col => {
      return col.props.prop === prop;
    });
    if (!column.props.sortable) {
      return;
    }
    Object.assign(sortState, {
      prop,
      order,
      sorter: column === null || column === void 0 || (_column$props = column.props) === null || _column$props === void 0 ? void 0 : _column$props.sorter
    });
    ctx.emit('sortChange', readonly(sortState));
  };
  const clearSorter = () => {
    Object.assign(sortState, {
      prop: undefined,
      order: undefined,
      sorter: undefined
    });
    ctx.emit('sortChange', readonly(sortState));
  };
  return {
    sortState,
    handleClickSortHeader,
    sort,
    clearSorter,
    handleRowDataBySort
  };
};

export { useTableSort as default };
