import { jsx as i, jsxs as te } from "react/jsx-runtime";
import { useRef as oe, isValidElement as re } from "react";
import o from "prop-types";
import ae, { TableFilterList as le, TableFooter as ie } from "mui-datatables";
import { TableFilterList as Ie, TableFooter as Ue } from "mui-datatables";
import { css as H } from "@emotion/react";
import F from "lodash/isObject";
import se from "lodash/cloneDeep";
import ne from "lodash/get";
import P from "clsx";
import { useCreation as de, useDeepCompareEffect as h } from "ahooks";
import { CircularProgress as ce } from "@mui/material";
import R from "../Empty/index.js";
import pe from "./CustomToolbar.js";
import { DatatableProvider as ue, useDatatableContext as M } from "./DatatableContext.js";
import { styled as $ } from "../Theme/index.js";
const fe = $("div")`
  display: flex;
  align-items: center;
  .toolbar-filter-content {
    margin-bottom: 8px;
  }
  .toolbar-filter-title {
    font-weight: 700;
    font-size: 14px;
  }
`;
function N({ ...e }) {
  const { filterLabel: a } = M(), r = !!(e.filterList ?? []).filter((n) => n.length).length;
  return r ? /* @__PURE__ */ te(fe, { children: [
    r && /* @__PURE__ */ i("div", { className: "toolbar-filter-title", children: a }),
    /* @__PURE__ */ i("div", { className: "toolbar-filter-content", children: /* @__PURE__ */ i(le, { ...e }) })
  ] }) : "";
}
N.propTypes = {
  filterList: o.array
};
function be(e) {
  const { loading: a, disabled: r } = M();
  return /* @__PURE__ */ i(he, { children: /* @__PURE__ */ i("div", { className: `datatable-footer ${a || r ? "datatable-footer-disabled" : ""}`, children: /* @__PURE__ */ i(ie, { ...e }) }) });
}
const ge = (e) => {
  const a = `datatable-durable-${e}`;
  let r = localStorage[a];
  if (r)
    try {
      r = JSON.parse(r);
    } catch (n) {
      console.error(`parse durable data error (key:${e}) => `, n);
    }
  return r || {};
};
function He(e) {
  return /* @__PURE__ */ i(ue, { children: /* @__PURE__ */ i(A, { ...e }) });
}
const k = (e, a) => {
  const r = {};
  e.align && (a.className = P(a.className, `pc-align-${e.align}`)), e.verticalKeyAlign && (a.className = P(a.className, `vertical-align-${e.verticalKeyAlign}`)), e.minWidth && (r.minWidth = e.minWidth), a.style = Object.assign({}, a.style, r);
};
function A({
  data: e,
  columns: a,
  locale: r = "en",
  options: n = {},
  // The options object is usually a property supported by mui-datatable
  style: w = {},
  customPreButtons: b = [],
  customButtons: g = [],
  onChange: m = "",
  loading: c = !1,
  disabled: C = !1,
  stripped: I = !1,
  verticalKeyWidth: U = "",
  hideTableHeader: E = !1,
  components: _ = {},
  emptyNode: T = "",
  durable: v = "",
  durableKeys: j = ["page", "rowsPerPage", "searchText", "sortOrder"],
  bgColor: B = "transparent",
  hoverColor: O = "",
  stripColor: W = "",
  ...z
}) {
  const D = oe(null), { setCustomPreButtons: K, setCustomButtons: J, setFilterLabel: V, setLoading: q, setDisabled: G } = M(), Q = {
    cursor: "not-allowed",
    pointerEvents: "none"
  }, x = [], X = a.map((s) => {
    let t;
    F(s) ? t = se(s) : t = {
      label: s,
      name: s
    }, x.push(t.name), t.align || (t.align = "left"), t.options || (t.options = {});
    const { setCellHeaderProps: d, setCellProps: u } = t.options;
    return t.options.setCellHeaderProps = (...f) => {
      let l = {
        className: ""
      };
      return d && !d.__innerFunc && (l = {
        ...l,
        ...d(...f) || {}
      }), (c || C) && (l = { ...l, style: Q }), t.width && (l.width = t.width), k(t, l), l;
    }, t.options.setCellHeaderProps.__innerFunc = 1, (t.align || t.style) && (t.options.setCellProps = (...f) => {
      let l = {
        className: ""
      };
      return u && !u.__innerFunc && (l = {
        ...l,
        ...u(...f) || {}
      }), k(t, l), l;
    }, t.options.setCellProps.__innerFunc = 1), t;
  }), Y = de(() => e.map((s) => !Array.isArray(s) && F(s) ? x.map((t) => ne(s, t)) : s), [e, x]);
  h(() => J(g || []), [g]), h(() => K(b || []), [b]), h(() => q(c), [c]), h(() => G(C), [C]);
  let p;
  c ? p = /* @__PURE__ */ i(ce, { color: "primary" }) : re(T) ? p = T : r === "zh" ? p = /* @__PURE__ */ i(R, { children: T || "没有找到匹配的记录" }) : p = /* @__PURE__ */ i(R, { children: T || "No matching records found" });
  let y = {
    body: {
      noMatch: p,
      toolTip: "Sort"
    },
    pagination: {
      next: "Next Page",
      previous: "Previous Page",
      rowsPerPage: "Per page:",
      displayRows: "of",
      jumpToPage: "Jump to Page:"
    },
    toolbar: {
      search: "Search",
      downloadCsv: "Download CSV",
      print: "Print",
      viewColumns: "View Columns",
      filterTable: "Filter Table"
    },
    filter: { all: "All", title: "FILTERS", reset: "RESET" },
    viewColumns: { title: "Show Columns", titleAria: "Show/Hide Table Columns" },
    selectedRows: { text: "row(s) selected", delete: "Delete", deleteAria: "Delete Selected Rows" }
  };
  r === "zh" && (y = {
    body: { noMatch: p, toolTip: "排序" },
    pagination: {
      next: "下一页",
      previous: "上一页",
      rowsPerPage: "每页行数",
      displayRows: "/",
      jumpToPage: "跳转到页面："
    },
    toolbar: {
      search: "搜索",
      downloadCsv: "下载CSV",
      print: "打印",
      viewColumns: "查看列",
      filterTable: "筛选表格"
    },
    filter: { all: "全部", title: "筛选器", reset: "重置" },
    viewColumns: { title: "显示的列", titleAria: "显示/隐藏 表格的列" },
    selectedRows: { text: "个已选项目", delete: "删除", deleteAria: "删除所选项目" }
  }), h(() => V(y.filter.title), [y.filter.title]);
  const Z = ge(v), S = {
    selectableRows: "none",
    textLabels: y,
    rowsPerPage: 10,
    rowsPerPageOptions: [10, 20, 50],
    ...Z,
    ...n,
    // Wrap the more friendly onChange callback by listening to onTableChange,
    // which will only be triggered when the table key state changes
    onTableChange: (s, t) => {
      if (s === "propsUpdate")
        return;
      const d = {
        count: t.count,
        page: t.page,
        rowsPerPage: t.rowsPerPage,
        searchText: t.searchText,
        sortOrder: t.sortOrder,
        //
        filterList: t.filterList
      };
      if (v) {
        const f = {};
        j.forEach((l) => {
          f[l] = d[l];
        }), localStorage.setItem(`datatable-durable-${v}`, JSON.stringify(f));
      }
      const u = JSON.stringify(d);
      u !== D.current && (D.current = u, m && m(d, s));
    }
  };
  m && (S.serverSide = !0);
  const ee = {
    options: S,
    ...z,
    components: {
      TableToolbar: pe,
      TableFooter: be,
      TableFilterList: N,
      ..._
    }
  };
  return /* @__PURE__ */ i(
    me,
    {
      verticalKeyWidth: U,
      bgColor: B,
      hoverColor: O,
      stripColor: W,
      className: P({
        "datatable-stripped": I,
        "datatable-hide-header": E
      }),
      style: w,
      children: /* @__PURE__ */ i(ae, { data: Y, columns: X, ...ee })
    }
  );
}
A.propTypes = {
  data: o.array.isRequired,
  columns: o.array.isRequired,
  options: o.object,
  style: o.object,
  locale: o.string,
  loading: o.bool,
  disabled: o.bool,
  customPreButtons: o.array,
  customButtons: o.array,
  onChange: o.oneOfType([o.func, o.string]),
  stripped: o.bool,
  verticalKeyWidth: o.oneOfType([o.number, o.string]),
  hideTableHeader: o.bool,
  components: o.object,
  emptyNode: o.node,
  durable: o.string,
  durableKeys: o.array,
  bgColor: o.string,
  hoverColor: o.string,
  stripColor: o.string
};
const L = H`
  .MuiTableCell-head {
    [class*='MUIDataTableHeadCell-toolButton'] {
      width: 100%;
      > [class*='MUIDataTableHeadCell-sortAction'] {
        width: 100%;
      }
    }
    &.pc-align-center {
      text-align: center;
      [class*='MUIDataTableHeadCell-toolButton'] > [class*='MUIDataTableHeadCell-sortAction'] {
        justify-content: center;
      }
    }
    &.pc-align-right {
      text-align: right;
      [class*='MUIDataTableHeadCell-toolButton'] {
        margin-right: 0;
        padding-right: 0;
        & > [class*='MUIDataTableHeadCell-sortAction'] {
          justify-content: flex-end;
        }
      }
    }
  }
  .MuiTableCell-body {
    &.pc-align-center {
      text-align: center;
    }
    &.pc-align-right {
      text-align: right;
    }
  }
`, me = $("div", {
  shouldForwardProp: (e) => !["verticalKeyWidth", "bgColor", "hoverColor", "stripColor"].includes(e)
})(({ theme: e, verticalKeyWidth: a, bgColor: r, hoverColor: n, stripColor: w }) => {
  const b = e.palette.text.primary, g = e.palette.action.hover, m = e.palette.grey[50], c = a ? `
      ${e.breakpoints.down("md")} {
        [class*='MUIDataTable-responsiveBase'] {
          tr:not([class*='responsiveSimple']) {
            td.MuiTableCell-body {
              > div {
                &:first-of-type {
                  width: ${a + (/\D/.test(a) ? "" : "px")};
                }
              }
            }
          }
        }
      }
    ` : "";
  return H`
    &.datatable-hide-header {
      thead.MuiTableHead-root {
        display: none;
      }
    }

    td {
      &.vertical-align-top {
        align-items: flex-start;
      }
      &.vertical-align-center {
        align-items: center;
      }
      &.vertical-align-bottom {
        align-items: flex-end;
      }
    }

    height: 100%;
    > .MuiPaper-root {
      display: flex;
      flex-direction: column;
      height: 100%;
      box-shadow: none;
      background: none;
      background-color: ${r};
    }
    ${e.breakpoints.down("md")} {
      td.MuiTableCell-body {
        padding-right: 0;
      }
      [class*='MUIDataTable-responsiveBase'] {
        tr:not([class*='responsiveSimple']) {
          td.MuiTableCell-body {
            display: flex;
            > div {
              width: auto;
              flex: 1;
              &:first-of-type {
                font-weight: bold;
                font-size: 14px;
                width: auto;
                flex: 0 0 auto;
                padding-right: 16px;
                &:empty {
                  padding-right: 0;
                }
              }
            }
          }
        }
      }
    }
    ${e.breakpoints.up("md")} {
      ${L}
    }
    ${e.breakpoints.up("sm")} {
      [class*='responsiveSimple'] {
        ${L}
      }
    }

    ${c}

    .MuiTableCell-head {
      color: ${b};
      background-color: ${r};
    }

    .MuiTableCell-root {
      color: ${b};
    }

    .MuiTableRow-root {
      background-color: ${r};
      &:hover {
        background-color: ${n || g};
      }
      &.MuiTableRow-footer {
        background-color: ${r};
      }
    }

    &.datatable-stripped {
      .MuiTableRow-root:nth-of-type(odd) {
        background-color: ${w || m};
        &:hover {
          background-color: ${n || g};
        }
        &.MuiTableRow-head {
          background-color: ${r};
        }
        &.MuiTableRow-footer {
          background-color: ${r};
        }
      }
    }
  `;
}), he = $("div")`
  display: flex;
  align-items: center;
  .datatable-footer {
    position: relative;
    margin-left: auto;
    &.datatable-footer-disabled {
      position: relative;
      .MuiTablePagination-root {
        opacity: 0.6;
      }
      &:after {
        position: absolute;
        display: block;
        z-index: 2;
        width: 100%;
        height: 100%;
        left: 0;
        top: 0;
        content: '';
        cursor: not-allowed;
      }
    }
  }

  ${(e) => e.theme.breakpoints.down("sm")} {
    .MuiTableCell-footer,
    .MuiToolbar-gutters {
      padding: 0;
    }

    div[variant='standard'] {
      margin-left: 4px;
      margin-right: 16px;
    }

    .MuiTablePagination-actions {
      margin-left: 10px;
    }
  }
`;
export {
  Ie as TableFilterList,
  Ue as TableFooter,
  He as default,
  ge as getDurableData
};
