import { ref as me, reactive as J, unref as d, nextTick as Se, onMounted as ze, watch as Pe, computed as M, createVNode as x } from "vue";
import { cloneDeep as Te, isArray as K, isEqualWith as Ce, isUndefined as be } from "lodash-unified";
import "../../config-provider/index.mjs";
import "../../utils/index.mjs";
import { parseFieldValue as xe, dataIndexToStr as Fe, isEqualCustom as we } from "../utils.mjs";
import { useTableSortedAndFiltered as De } from "./use-sorted-filtered.mjs";
import { useLocale as Ee } from "../../config-provider/hooks/use-locale.mjs";
import { useNamespace as ve } from "../../config-provider/hooks/use-namespace.mjs";
import { isDef as Q } from "../../utils/is.mjs";
const p = 1, y = 20, W = {
  defaultCurrent: p,
  defaultPageSize: y,
  showLessItems: !1,
  showTotal: !0
};
function Ae(i) {
  return i === !1 ? {} : i == null || i === !0 ? W : {
    ...W,
    ...i
  };
}
function Le(i) {
  const f = {};
  return i === !1 || (i === !0 || i == null ? (f.current = p, f.pageSize = y) : (f.current = i.defaultCurrent || p, f.pageSize = i.defaultPageSize || y)), f;
}
const qe = ({
  manual: i = !1,
  request: f,
  params: R = {},
  defaultData: I = [],
  formatParams: N,
  paramsValueTypeMap: O,
  resetFieldsIgnores: V,
  filterFields: $,
  sortFields: G,
  namespace: Z = "ap-table",
  pagination: g,
  onClickReset: H,
  onAfterRequest: X,
  defaultSortOrder: h
}) => {
  let F = 0, c = {};
  const Y = Ae(g), ee = (e) => N ? N(e) : e, m = me(), o = J(Le(g)), {
    getColumnSFConfig: te,
    setSF: ne,
    clearAll: re,
    sortedInfo: j,
    filteredInfo: U
  } = De(h), {
    t: S
  } = Ee(), {
    b: z
  } = ve(Z), a = J({
    total: I.length,
    records: I,
    loading: !1
  }), P = () => m.value?.apForm?.getFieldsValueTransformed(!0) || {}, w = async (e, t) => {
    const n = ee(e), r = Date.now(), s = t?.cache;
    F = r, a.loading = !0;
    try {
      const u = await f({
        ...d(R),
        ...n
      });
      if (F === r) {
        a.total = u.total || u.data?.length || 0, s ? a.records.push(...u.data || []) : a.records = [...u.data || []];
        const b = a.records.length < a.total;
        t?.onSuccess?.(e, b), a.loading = !1;
      }
    } catch {
      F === r && !s && (a.records = [], a.total = 0), a.loading = !1;
    } finally {
      X?.(a.records);
    }
  }, D = (e) => {
    const t = {};
    return Object.entries(e).forEach(([n, r]) => {
      if (t[n] = r, O && r) {
        const s = O[n];
        s && (t[n] = xe(s, r));
      }
    }), t;
  }, ae = async (e) => {
    const t = P(), n = {};
    Object.entries(t).forEach(([r, s]) => {
      V && V.indexOf(r) > -1 && (n[r] = s);
    }), await m.value?.apForm?.resetFields(), m.value?.apForm?.setFieldsValue?.(n), Se(() => {
      e?.();
    });
  }, T = (e) => {
    c = e;
    const t = D(e);
    w(t);
  }, oe = (e) => {
    T({
      ...c,
      ...e
    });
  };
  let C, E = !0;
  function q() {
    C = void 0, E = !0;
  }
  const se = () => {
    if (!E)
      return;
    const e = C ? C + 1 : 2, t = {
      ...c,
      current: e
    };
    c = t;
    const n = D(t);
    w(n, {
      cache: !0,
      onSuccess(r, s) {
        C = r.current, E = s;
      }
    });
  }, ce = () => Te(c), v = () => {
    _(!0), q();
  }, _ = (e = !1) => {
    const t = P(), n = g !== !1;
    n && e && (o.current = p), T({
      ...t,
      filter: c.filter,
      sort: c.sort,
      current: n ? e ? p : c.current || o.current : void 0,
      pageSize: n ? c.pageSize || o.pageSize : void 0
    });
  }, ie = () => {
    re(), c.sort = {}, c.filter = {}, H?.(), ae(v), q();
  }, A = () => {
    T(c);
  }, ue = (e) => {
    if (g === !1)
      A();
    else {
      const {
        current: t,
        pageSize: n
      } = o, r = a.total - e, s = Math.ceil(r / n), u = t > s ? s : t;
      oe({
        current: u > 0 ? u : 1
      });
    }
  }, L = (e, t, n) => {
    const r = P();
    o.current = e.current, o.pageSize = e.pageSize, ne(t, n);
    const s = K(n) ? [...n] : [n], u = {};
    for (const l of s)
      d(G)?.includes(l.columnKey || l.field) && l.order && (u[Fe(l.columnKey || l.field)] = l.order);
    const b = {};
    for (const l of Object.keys(t))
      d($)?.includes(l) && t[l] && (b[l] = t[l]);
    const B = {
      ...r,
      filter: b,
      sort: u,
      current: e.current,
      pageSize: e.pageSize
    };
    Ce(c, B, we) || T(B);
  }, k = (e, t = U.value || {}, n = j.value || {}) => {
    const r = e?.current ?? o.current, s = e?.pageSize ?? o.pageSize;
    L(
      {
        current: r,
        pageSize: s
      },
      t,
      n,
      // 此参数随意传递，并无使用
      {
        action: "sort",
        currentDataSource: []
      }
    );
  };
  function le() {
    return h ? {
      [h.field]: h.order
    } : {};
  }
  ze(() => {
    const e = P(), {
      current: t,
      pageSize: n
    } = o;
    if (c = {
      current: t,
      pageSize: n,
      filter: {},
      sort: le(),
      ...e
    }, !i) {
      const r = D(c);
      w(r);
    }
  }), Pe(() => d(R), () => {
    v();
  }, {
    deep: !0
  });
  const fe = M(() => {
    if (a.total === 0)
      return "-";
    const {
      current: e,
      pageSize: t
    } = o;
    return `${e}/${Math.ceil(a.total / t)}`;
  });
  function ge(e, t = !1) {
    if (K(e)) {
      if (g !== !1 && t) {
        const n = o.pageSize * (o.current - 1);
        a.records = e.slice(n, n + o.pageSize) || [];
        const r = Math.max(Math.ceil(e.length / o.pageSize), 1);
        r < o.current && k({
          current: r
        });
      } else
        a.records = e;
      a.total = e.length;
    }
  }
  const de = M(() => {
    const {
      showLessItems: e,
      showTotal: t,
      showQuickJumper: n,
      showSizeChanger: r,
      pageSizeOptions: s
    } = Y;
    return {
      loading: a.loading,
      pagination: {
        current: o.current,
        pageSize: o.pageSize,
        total: a.total,
        showSizeChanger: Q(r) ? r : !e,
        showQuickJumper: Q(n) ? n : !e,
        showLessItems: e,
        size: "default",
        pageSizeOptions: be(s) ? ["10", "20", "50", "100"] : s,
        showTotal: t ? (u) => x("span", {
          class: z("pagination-total-wrapper")
        }, [S("ap.apTable.pagination.totalLeftPrefix"), " ", x("span", {
          class: z("pagination-count-text")
        }, [u]), " ", S("ap.apTable.pagination.totalLeftSuffix"), x("span", {
          class: z("pagination--total-right")
        }, [S("ap.apTable.pagination.totalRightPrefix"), " ", x("span", {
          class: z("pagination-count-text")
        }, [d(fe)]), " ", S("ap.apTable.pagination.totalRightSuffix")])]) : void 0
      },
      onChange: L,
      dataSource: a.records
    };
  });
  function pe(e, t = !0) {
    Object.assign(o, e), c.current = e.current, c.pageSize = e.pageSize, t && A();
  }
  function he() {
    return {
      ...o
    };
  }
  return {
    formRef: m,
    submit: v,
    reset: ie,
    refresh: A,
    refreshByDelete: ue,
    data: a,
    handleTableChange: L,
    handleTableChangeOptional: k,
    tableProps: de,
    dataSource: M(() => a.records),
    setDataSource: ge,
    getColumnSFConfig: te,
    sortedInfo: j,
    filteredInfo: U,
    getPaging: he,
    setPaging: pe,
    submitWith: _,
    fetchNextPageAndCache: se,
    getLastParams: ce
  };
};
export {
  p as DEFAULT_CURRENT,
  y as DEFAULT_PAGE_SIZE,
  qe as useTablePaging
};
