/* empty css                                               */
/* empty css                                                     */
/* empty css                                                  */
/* empty css                                               */
import { getCurrentInstance, computed, ref, onMounted, createVNode, render, nextTick, resolveComponent, createElementBlock, openBlock, Fragment, createBlock, createCommentVNode, unref, normalizeStyle, normalizeClass, withCtx, isRef, createSlots, createElementVNode, renderList, renderSlot } from "vue";
import { VxeGrid } from "vxe-table";
import { createDataSource } from "../../../utils/datasource.mjs";
/* empty css                                                      */
import { textFormatter, dateFormatter, cascadeFormatter, multipleFormatter, selectFormatter } from "../../../utils/formatterUtil.mjs";
/* empty css                                                     */
/* empty css                                                */
/* empty css                                               */
/* empty css                                                 */
/* empty css                                                            */
/* empty css                                                  */
/* empty css                                                */
/* empty css                                                 */
/* empty css            */
import _export_sfc from "../../../../../../_virtual/_plugin-vue_export-helper.mjs";
import { SwipeCell } from "../../../../node_modules/vant/es/swipe-cell/index.mjs";
import { Button } from "../../../../node_modules/vant/es/button/index.mjs";
import { showConfirmDialog } from "../../../../node_modules/vant/es/dialog/function-call.mjs";
import { CellGroup } from "../../../../node_modules/vant/es/cell-group/index.mjs";
import { List } from "../../../../node_modules/vant/es/list/index.mjs";
const _hoisted_1 = {
  key: 0,
  class: "van-list__finished-text"
};
const _hoisted_2 = {
  key: 1,
  class: "van-list__loading"
};
const _sfc_main = {
  __name: "Table",
  props: {
    modelValue: {
      //数据
      type: Array,
      default: []
    },
    columns: {
      //列配置
      type: Array,
      default: []
    },
    size: {
      //大小尺寸: medium / small / mini
      type: String,
      default: "medium"
    },
    isFixedHead: {
      //固定表头
      type: Boolean,
      default: true
    },
    autoHeight: {
      //高度自适应
      type: Boolean,
      default: true
    },
    height: {
      //高度
      type: String,
      default: "300"
    },
    border: {
      //default:默认边框， full:完整边框,outer 显示外边框,inner 显示内边框,none 隐藏边框
      type: String,
      default: "default"
    },
    round: {
      //显示圆角
      type: Boolean,
      default: false
    },
    stripe: {
      //斑马线样式
      type: Boolean,
      default: false
    },
    showHeader: {
      //显示表头
      type: Boolean,
      default: true
    },
    scrollLoad: {
      //是否滚动加载
      type: Boolean,
      default: false
    },
    dataSourceValue: {
      type: String,
      default: ""
    },
    dataSources: {
      type: Array,
      default: () => []
    },
    pageSize: {
      type: Number,
      default: 10
    },
    isCard: {
      //卡片风格
      type: Boolean,
      default: false
    },
    isShadow: {
      //卡片阴影
      type: Boolean,
      default: true
    },
    swipeDelete: {
      //左滑删除
      type: Boolean,
      default: false
    },
    swipeEdit: {
      //左滑编辑
      type: Boolean,
      default: false
    },
    enableFilter: {
      type: Boolean,
      default: false
    },
    filterPlaceholder: {
      type: String,
      default: ""
    },
    filterMode: {
      type: String,
      default: ""
    },
    quickFilter: {
      type: Array,
      default: []
    }
  },
  emits: [
    "update:modelValue",
    "deleteRow",
    "editRow",
    "clickCell"
  ],
  setup(__props, { emit: __emit }) {
    const props = __props;
    const currentInstance = getCurrentInstance();
    const ctx = currentInstance.proxy;
    const emit = __emit;
    function cellClickEvent({ row, column }) {
      emit("clickCell", { row, column });
    }
    const compHeight = computed(() => {
      return "100%";
    });
    const columnOptions = computed(() => {
      return props.columns.map((col) => {
        const newCol = { ...col };
        switch (newCol.dataType) {
          case "select":
            newCol.formatter = ({ cellValue }) => {
              if (isEmpty(cellValue)) {
                return emptyHandler(newCol.emptyFormatter);
              }
              return selectFormatter(cellValue, newCol.options);
            };
            break;
          case "multiple":
            newCol.formatter = ({ cellValue }) => {
              if (isEmpty(cellValue)) {
                return emptyHandler(newCol.emptyFormatter);
              }
              return multipleFormatter(cellValue, newCol.options);
            };
            break;
          case "cascade":
            newCol.formatter = ({ cellValue }) => {
              if (isEmpty(cellValue)) {
                return emptyHandler(newCol.emptyFormatter);
              }
              return cascadeFormatter(cellValue, newCol.treeOptions);
            };
            break;
          case "date":
            newCol.formatter = ({ cellValue }) => {
              if (isEmpty(cellValue)) {
                return emptyHandler(newCol.emptyFormatter);
              }
              return dateFormatter(
                cellValue,
                newCol.dateType,
                newCol.dateFormatter
              );
            };
            break;
          default:
            newCol.formatter = ({ cellValue }) => {
              if (isEmpty(cellValue)) {
                return emptyHandler(newCol.emptyFormatter);
              }
              return textFormatter(cellValue, newCol.dataFormatter);
            };
            break;
        }
        newCol.title = newCol.label;
        newCol.field = newCol.fieldName;
        newCol.showOverflow = true;
        newCol.showHeaderOverflow = true;
        newCol.showFooterOverflow = true;
        return newCol;
      });
    });
    function isEmpty(cellValue) {
      return !cellValue && cellValue !== 0;
    }
    function emptyHandler(emptyFormatter) {
      if (isEmpty(emptyFormatter)) {
        return "";
      } else {
        return emptyFormatter;
      }
    }
    const gridRef = ref();
    const listRef = ref();
    let isDesigner = false;
    onMounted(() => {
      var _a, _b;
      const device = (_b = (_a = listRef.value) == null ? void 0 : _a.$el) == null ? void 0 : _b.closest(".device-content");
      if (device) {
        isDesigner = true;
      }
      initDataSourceManager();
      setTimeout(() => {
        initSwipeCells();
      }, 500);
    });
    const initSwipeCells = () => {
      if (props.swipeDelete || props.swipeEdit) {
        const tableBody = gridRef.value.getEl().querySelector(".vxe-table--body");
        tableBody.offsetWidth;
        const tableRows = tableBody.querySelectorAll(".vxe-body--row");
        tableRows.forEach((row, index) => {
          if (!row.parentElement.classList.contains("van-swipe-cell__wrapper")) {
            const swipeCell = createVNode(
              SwipeCell,
              {
                class: `fec-table-row-swipe`,
                // style: `width:${offsetWidth}px`,
                style: `width:100%`
                // beforeClose: ({ position }) => {
                //   switch (position) {
                //     case "left":
                //     case "cell":
                //     case "outside":
                //       return true;
                //     case "right":
                //       return new Promise(resolve => {
                //         showConfirmDialog({
                //           title: "确定删除吗？",
                //         })
                //           .then(() => {
                //             emit("delete");
                //             resolve(true);
                //           })
                //           .catch(() => resolve(false));
                //       });
                //   }
                // },
              },
              {
                right: () => [
                  createVNode(Button, {
                    square: true,
                    type: "primary",
                    text: "编辑",
                    style: `height:100%;display:${props.swipeEdit ? "inline-block" : "none"}`,
                    onClick: () => {
                      const rowData = gridRef.value.getData(index);
                      emit("editRow", rowData, index);
                    }
                  }),
                  createVNode(Button, {
                    square: true,
                    type: "danger",
                    text: "删除",
                    style: `height:100%;display:${props.swipeDelete ? "inline-block" : "none"}`,
                    onClick: () => {
                      showConfirmDialog({
                        title: "确定删除吗？"
                      }).then(() => {
                        const rowData = gridRef.value.getData(index);
                        emit("deleteRow", rowData, index);
                      }).catch(() => {
                      });
                    }
                  })
                ]
              }
            );
            const container = document.createElement("div");
            render(swipeCell, container);
            const swipeCellElement = container.firstElementChild;
            const colgroupElement = row.parentNode.parentNode.querySelector("colgroup");
            const cloneColgroupElement = colgroupElement.cloneNode(true);
            swipeCellElement.appendChild(cloneColgroupElement);
            row.parentNode.replaceChild(swipeCellElement, row);
            swipeCellElement.querySelector(".van-swipe-cell__wrapper").appendChild(row);
          }
        });
      }
    };
    const virtualYConfig = {
      enabled: false,
      gt: 0,
      threshold: 0
    };
    const tableData = ref([]);
    const dataSourceManager = ref();
    const initLoading = ref(false);
    const loading = ref(false);
    const finished = ref(false);
    const listFinished = ref(false);
    const error = ref(false);
    const listError = ref(false);
    let pageNo = 1;
    function initDataSourceManager() {
      dataSourceManager.value = createDataSource({
        http: ctx.$http,
        dataSources: props.dataSources,
        currentDataSourceId: props.dataSourceValue,
        pagination: {
          pageNo,
          pageSize: props.pageSize
        }
        // data: hiddenFormData.value,
        // fields: fieldsData.value,
        // sortRules: localConfig.value.sortRules,
        // templateId: localConfig.value.templateKey,
      });
      dataSourceManager.value.on("loaded", (data) => {
        emit("data-loaded", data);
      });
      dataSourceManager.value.on("error", (err) => {
        emit("data-error", err);
      });
      if (dataSourceManager.value && isDesigner) {
        tableData.value = [];
        if (props.isFixedHead) {
          initLoading.value = true;
          call();
        } else if (!props.scrollLoad) {
          call();
        } else {
          pageNo = 0;
        }
      } else {
        loading.value = false;
      }
    }
    function onScrollLoads({ direction }) {
      const isBottom = direction == "bottom";
      if (finished.value || loading.value || error.value) {
        return;
      }
      if (props.scrollLoad && isBottom) {
        pageNo++;
        loading.value = true;
        error.value = false;
        call();
      }
    }
    async function call() {
      var _a;
      try {
        dataSourceManager.value.updatePagination(pageNo, props.pageSize);
        await dataSourceManager.value.fetch();
        const data = ((_a = dataSourceManager.value) == null ? void 0 : _a.getData().list) || [];
        tableData.value.push(...data);
        if (data.length < props.pageSize) {
          if (props.isFixedHead) {
            finished.value = true;
          } else {
            listFinished.value = true;
          }
        }
        loading.value = false;
        initLoading.value = false;
        setTimeout(() => {
          nextTick(() => {
            checkHasScroll();
          });
        }, 300);
        setTimeout(() => {
          initSwipeCells();
        }, 500);
      } catch (err) {
        console.error(err);
        if (props.isFixedHead) {
          error.value = isDesigner ? false : true;
        } else {
          listError.value = isDesigner ? false : true;
        }
        loading.value = false;
        initLoading.value = false;
      }
    }
    function errReload() {
      call();
    }
    function checkHasScroll() {
      if (!props.isFixedHead) {
        return;
      }
      if (finished.value) {
        return;
      }
      const scrollHeight = gridRef.value.getEl().querySelector(".vxe-table--body").scrollHeight;
      const clientHeight = gridRef.value.getEl().querySelector(".vxe-table--body-inner-wrapper").clientHeight;
      if (scrollHeight < clientHeight) {
        onScrollLoads({ direction: "bottom" });
      }
    }
    function onLoad() {
      console.log("onload");
      if (!props.isFixedHead) {
        loading.value = true;
        pageNo++;
        if (pageNo == 1) {
          initLoading.value = false;
        } else {
          loading.value = true;
        }
        listError.value = false;
        call();
      }
    }
    const quickFilterConfig = computed(() => {
      const list = props.quickFilter.map((fieldName) => props.columns.find((col) => col.fieldName == fieldName)).filter(Boolean);
      return list;
    });
    return (_ctx, _cache) => {
      const _component_fec_mobile_search = resolveComponent("fec-mobile-search");
      const _component_van_list = List;
      const _component_van_cell_group = CellGroup;
      return openBlock(), createElementBlock(Fragment, null, [
        __props.enableFilter ? (openBlock(), createBlock(_component_fec_mobile_search, {
          key: 0,
          placeholder: __props.filterPlaceholder,
          filterMode: __props.filterMode,
          dataSources: __props.dataSources,
          filterConfig: unref(quickFilterConfig)
        }, null, 8, ["placeholder", "filterMode", "dataSources", "filterConfig"])) : createCommentVNode("", true),
        createVNode(_component_van_cell_group, {
          class: normalizeClass(["mTableContent", {
            notAutoHeight: !__props.autoHeight,
            isShadow: __props.isCard && __props.isShadow,
            isCard: __props.isCard
          }]),
          style: normalizeStyle("height:" + unref(compHeight)),
          ref_key: "listRef",
          ref: listRef,
          inset: __props.isCard
        }, {
          default: withCtx(() => [
            createVNode(_component_van_list, {
              class: normalizeClass({ fixedHead: __props.isFixedHead }),
              loading: unref(loading),
              "onUpdate:loading": _cache[0] || (_cache[0] = ($event) => isRef(loading) ? loading.value = $event : null),
              error: unref(listError),
              "onUpdate:error": _cache[1] || (_cache[1] = ($event) => isRef(listError) ? listError.value = $event : null),
              finished: unref(listFinished),
              disabled: !__props.scrollLoad || __props.isFixedHead,
              offset: 0,
              "finished-text": "没有更多了",
              "error-text": "请求失败，点击重新加载",
              onLoad
            }, {
              default: withCtx(() => [
                createVNode(unref(VxeGrid), {
                  ref_key: "gridRef",
                  ref: gridRef,
                  class: "fec-table",
                  width: "100%",
                  "auto-resize": "",
                  data: unref(tableData),
                  columns: unref(columnOptions),
                  size: __props.size,
                  headerAlign: "center",
                  footerAlign: "center",
                  align: "center",
                  border: __props.border,
                  round: __props.round || __props.isCard,
                  stripe: __props.stripe,
                  height: __props.isFixedHead ? unref(compHeight) : "",
                  loading: unref(initLoading),
                  showHeader: __props.showHeader,
                  onScrollBoundary: onScrollLoads,
                  virtualYConfig,
                  onCellClick: cellClickEvent
                }, createSlots({
                  loading: withCtx(() => [
                    _cache[2] || (_cache[2] = createElementVNode("div", {
                      class: "custom-loading van-loading van-loading--circular van-list__loading-icon",
                      "aria-live": "polite",
                      "aria-busy": "true"
                    }, [
                      createElementVNode("span", { class: "van-loading__spinner van-loading__spinner--circular" }, [
                        createElementVNode("svg", {
                          class: "van-loading__circular",
                          viewBox: "25 25 50 50"
                        }, [
                          createElementVNode("circle", {
                            cx: "50",
                            cy: "50",
                            r: "20",
                            fill: "none"
                          })
                        ])
                      ]),
                      createElementVNode("span", { class: "van-loading__text" }, "加载中...")
                    ], -1))
                  ]),
                  bottom: withCtx(() => [
                    __props.scrollLoad && __props.isFixedHead ? (openBlock(), createElementBlock(Fragment, { key: 0 }, [
                      unref(finished) ? (openBlock(), createElementBlock("div", _hoisted_1, " 没有更多了 ")) : createCommentVNode("", true),
                      unref(loading) ? (openBlock(), createElementBlock("div", _hoisted_2, _cache[3] || (_cache[3] = [
                        createElementVNode("div", {
                          class: "van-loading van-loading--circular van-list__loading-icon",
                          "aria-live": "polite",
                          "aria-busy": "true"
                        }, [
                          createElementVNode("span", { class: "van-loading__spinner van-loading__spinner--circular" }, [
                            createElementVNode("svg", {
                              class: "van-loading__circular",
                              viewBox: "25 25 50 50"
                            }, [
                              createElementVNode("circle", {
                                cx: "50",
                                cy: "50",
                                r: "20",
                                fill: "none"
                              })
                            ])
                          ]),
                          createElementVNode("span", { class: "van-loading__text" }, "加载中...")
                        ], -1)
                      ]))) : createCommentVNode("", true),
                      unref(error) ? (openBlock(), createElementBlock("div", {
                        key: 2,
                        class: "van-list__error-text",
                        onClick: errReload
                      }, " 请求失败，点击重新加载 ")) : createCommentVNode("", true)
                    ], 64)) : createCommentVNode("", true)
                  ]),
                  _: 2
                }, [
                  renderList(_ctx.$slots, (item, key) => {
                    return {
                      name: key,
                      fn: withCtx(() => [
                        key != "bottom" ? renderSlot(_ctx.$slots, key, { key: 0 }, void 0, true) : createCommentVNode("", true)
                      ])
                    };
                  })
                ]), 1032, ["data", "columns", "size", "border", "round", "stripe", "height", "loading", "showHeader"])
              ]),
              _: 3
            }, 8, ["class", "loading", "error", "finished", "disabled"])
          ]),
          _: 3
        }, 8, ["class", "style", "inset"])
      ], 64);
    };
  }
};
const _Table = /* @__PURE__ */ _export_sfc(_sfc_main, [["__scopeId", "data-v-ee91bb34"]]);
export {
  _Table as default
};
