"use strict";
Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: "Module" } });
;/* empty css                                               */
;/* empty css                                                     */
;/* empty css                                                  */
;/* empty css                                               */
const Vue = require("vue");
const vxeTable = require("vxe-table");
const datasource = require("../../../utils/datasource.js");
;/* empty css                                                      */
const formatterUtil = require("../../../utils/formatterUtil.js");
const optionUtil = require("../../../utils/optionUtil.js");
;/* empty css                                                     */
;/* empty css                                                */
;/* empty css                                               */
;/* empty css                                                 */
;/* empty css                                                            */
;/* empty css                                                  */
;/* empty css                                                */
;/* empty css                                                 */
;/* empty css            */
const _pluginVue_exportHelper = require("../../../../../../_virtual/_plugin-vue_export-helper.js");
const index = require("../../../../node_modules/vant/es/swipe-cell/index.js");
const index$1 = require("../../../../node_modules/vant/es/button/index.js");
const functionCall = require("../../../../node_modules/vant/es/dialog/function-call.js");
const index$2 = require("../../../../node_modules/vant/es/cell-group/index.js");
const index$3 = require("../../../../node_modules/vant/es/list/index.js");
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: false
    },
    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: () => []
    },
    formData: {
      type: Object,
      default: {}
    },
    fields: {
      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 = Vue.getCurrentInstance();
    const ctx = currentInstance.proxy;
    const emit = __emit;
    function cellClickEvent({ row, column }) {
      emit("clickCell", { row, column });
    }
    const compHeight = Vue.computed(() => {
      return "100%";
    });
    const columnOptions = Vue.ref([]);
    async function initColumnOptions() {
      const columns = [...props.columns];
      for (const col of columns) {
        if (col.dataType == "select" || col.dataType == "multiple") {
          const options = await optionUtil.getOptions({
            ctx,
            dataSources: props.dataSources,
            formData: props.formData,
            fields: props.fields,
            ...col.optionConfig
          });
          col.options = options;
        }
      }
      columns.forEach((col) => {
        const newCol = { ...col };
        switch (newCol.dataType) {
          case "select":
            newCol.formatter = ({ cellValue }) => {
              if (isEmpty(cellValue)) {
                return emptyHandler(newCol.emptyFormatter);
              }
              return formatterUtil.selectFormatter(cellValue, newCol.options);
            };
            break;
          case "multiple":
            newCol.formatter = ({ cellValue }) => {
              if (isEmpty(cellValue)) {
                return emptyHandler(newCol.emptyFormatter);
              }
              return formatterUtil.multipleFormatter(cellValue, newCol.options);
            };
            break;
          case "cascade":
            newCol.formatter = ({ cellValue }) => {
              if (isEmpty(cellValue)) {
                return emptyHandler(newCol.emptyFormatter);
              }
              return formatterUtil.cascadeFormatter(cellValue, newCol.treeOptions);
            };
            break;
          case "date":
            newCol.formatter = ({ cellValue }) => {
              if (isEmpty(cellValue)) {
                return emptyHandler(newCol.emptyFormatter);
              }
              return formatterUtil.dateFormatter(
                cellValue,
                newCol.dateType,
                newCol.dateFormatter
              );
            };
            break;
          default:
            newCol.formatter = ({ cellValue }) => {
              if (isEmpty(cellValue)) {
                return emptyHandler(newCol.emptyFormatter);
              }
              return formatterUtil.textFormatter(cellValue, newCol.dataFormatter);
            };
            break;
        }
        newCol.title = newCol.label;
        newCol.field = newCol.fieldName;
        newCol.showOverflow = true;
        newCol.showHeaderOverflow = true;
        newCol.showFooterOverflow = true;
        columnOptions.value.push(newCol);
      });
    }
    initColumnOptions();
    function isEmpty(cellValue) {
      return !cellValue && cellValue !== 0;
    }
    function emptyHandler(emptyFormatter) {
      if (isEmpty(emptyFormatter)) {
        return "";
      } else {
        return emptyFormatter;
      }
    }
    const gridRef = Vue.ref();
    const listRef = Vue.ref();
    let isDesigner = false;
    Vue.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$22) => {
          if (!row.parentElement.classList.contains("van-swipe-cell__wrapper")) {
            const swipeCell = Vue.createVNode(
              index.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: () => [
                  Vue.createVNode(index$1.Button, {
                    square: true,
                    type: "primary",
                    text: "编辑",
                    style: `height:100%;display:${props.swipeEdit ? "inline-block" : "none"}`,
                    onClick: () => {
                      const rowData = gridRef.value.getData(index$22);
                      emit("editRow", rowData, index$22);
                    }
                  }),
                  Vue.createVNode(index$1.Button, {
                    square: true,
                    type: "danger",
                    text: "删除",
                    style: `height:100%;display:${props.swipeDelete ? "inline-block" : "none"}`,
                    onClick: () => {
                      functionCall.showConfirmDialog({
                        title: "确定删除吗？"
                      }).then(() => {
                        const rowData = gridRef.value.getData(index$22);
                        emit("deleteRow", rowData, index$22);
                      }).catch(() => {
                      });
                    }
                  })
                ]
              }
            );
            const container = document.createElement("div");
            Vue.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 = Vue.ref([]);
    const dataSourceManager = Vue.ref();
    const initLoading = Vue.ref(false);
    const loading = Vue.ref(false);
    const finished = Vue.ref(false);
    const listFinished = Vue.ref(false);
    const error = Vue.ref(false);
    const listError = Vue.ref(false);
    let pageNo = 1;
    const pageSize = Vue.computed(() => {
      if (props.scrollLoad) {
        return props.pageSize;
      }
      return -1;
    });
    function initDataSourceManager() {
      dataSourceManager.value = datasource.createDataSource({
        http: ctx.$http,
        dataSources: props.dataSources,
        currentDataSourceId: props.dataSourceValue,
        pagination: {
          pageNo,
          pageSize: pageSize.value
        },
        data: props.formData,
        fields: props.fields
        // 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) {
        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, pageSize.value);
        await dataSourceManager.value.fetch();
        const data = ((_a = dataSourceManager.value) == null ? void 0 : _a.getData().list) || [];
        tableData.value.push(...data);
        if (data.length < pageSize.value) {
          if (props.isFixedHead) {
            finished.value = true;
          } else {
            listFinished.value = true;
          }
        }
        loading.value = false;
        initLoading.value = false;
        setTimeout(() => {
          Vue.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 = Vue.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 = Vue.resolveComponent("fec-mobile-search");
      const _component_van_list = index$3.List;
      const _component_van_cell_group = index$2.CellGroup;
      return Vue.openBlock(), Vue.createElementBlock(Vue.Fragment, null, [
        __props.enableFilter ? (Vue.openBlock(), Vue.createBlock(_component_fec_mobile_search, {
          key: 0,
          placeholder: __props.filterPlaceholder,
          filterMode: __props.filterMode,
          dataSources: __props.dataSources,
          filterConfig: Vue.unref(quickFilterConfig)
        }, null, 8, ["placeholder", "filterMode", "dataSources", "filterConfig"])) : Vue.createCommentVNode("", true),
        Vue.createVNode(_component_van_cell_group, {
          class: Vue.normalizeClass(["mTableContent", {
            notAutoHeight: !__props.autoHeight,
            isShadow: __props.isCard && __props.isShadow,
            isCard: __props.isCard
          }]),
          style: Vue.normalizeStyle("height:" + Vue.unref(compHeight)),
          ref_key: "listRef",
          ref: listRef,
          inset: __props.isCard
        }, {
          default: Vue.withCtx(() => [
            Vue.createVNode(_component_van_list, {
              class: Vue.normalizeClass({ fixedHead: __props.isFixedHead }),
              loading: Vue.unref(loading),
              "onUpdate:loading": _cache[0] || (_cache[0] = ($event) => Vue.isRef(loading) ? loading.value = $event : null),
              error: Vue.unref(listError),
              "onUpdate:error": _cache[1] || (_cache[1] = ($event) => Vue.isRef(listError) ? listError.value = $event : null),
              finished: Vue.unref(listFinished),
              disabled: !__props.scrollLoad || __props.isFixedHead,
              offset: 0,
              "finished-text": "没有更多了",
              "error-text": "请求失败，点击重新加载",
              onLoad
            }, {
              default: Vue.withCtx(() => [
                Vue.createVNode(Vue.unref(vxeTable.VxeGrid), {
                  ref_key: "gridRef",
                  ref: gridRef,
                  class: "fec-table",
                  width: "100%",
                  "auto-resize": "",
                  data: Vue.unref(tableData),
                  columns: Vue.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 ? Vue.unref(compHeight) : "",
                  loading: Vue.unref(initLoading),
                  showHeader: __props.showHeader,
                  onScrollBoundary: onScrollLoads,
                  virtualYConfig,
                  onCellClick: cellClickEvent
                }, Vue.createSlots({
                  loading: Vue.withCtx(() => [
                    _cache[2] || (_cache[2] = Vue.createElementVNode("div", {
                      class: "custom-loading van-loading van-loading--circular van-list__loading-icon",
                      "aria-live": "polite",
                      "aria-busy": "true"
                    }, [
                      Vue.createElementVNode("span", { class: "van-loading__spinner van-loading__spinner--circular" }, [
                        Vue.createElementVNode("svg", {
                          class: "van-loading__circular",
                          viewBox: "25 25 50 50"
                        }, [
                          Vue.createElementVNode("circle", {
                            cx: "50",
                            cy: "50",
                            r: "20",
                            fill: "none"
                          })
                        ])
                      ]),
                      Vue.createElementVNode("span", { class: "van-loading__text" }, "加载中...")
                    ], -1))
                  ]),
                  bottom: Vue.withCtx(() => [
                    __props.scrollLoad && __props.isFixedHead ? (Vue.openBlock(), Vue.createElementBlock(Vue.Fragment, { key: 0 }, [
                      Vue.unref(finished) ? (Vue.openBlock(), Vue.createElementBlock("div", _hoisted_1, " 没有更多了 ")) : Vue.createCommentVNode("", true),
                      Vue.unref(loading) ? (Vue.openBlock(), Vue.createElementBlock("div", _hoisted_2, _cache[3] || (_cache[3] = [
                        Vue.createElementVNode("div", {
                          class: "van-loading van-loading--circular van-list__loading-icon",
                          "aria-live": "polite",
                          "aria-busy": "true"
                        }, [
                          Vue.createElementVNode("span", { class: "van-loading__spinner van-loading__spinner--circular" }, [
                            Vue.createElementVNode("svg", {
                              class: "van-loading__circular",
                              viewBox: "25 25 50 50"
                            }, [
                              Vue.createElementVNode("circle", {
                                cx: "50",
                                cy: "50",
                                r: "20",
                                fill: "none"
                              })
                            ])
                          ]),
                          Vue.createElementVNode("span", { class: "van-loading__text" }, "加载中...")
                        ], -1)
                      ]))) : Vue.createCommentVNode("", true),
                      Vue.unref(error) ? (Vue.openBlock(), Vue.createElementBlock("div", {
                        key: 2,
                        class: "van-list__error-text",
                        onClick: errReload
                      }, " 请求失败，点击重新加载 ")) : Vue.createCommentVNode("", true)
                    ], 64)) : Vue.createCommentVNode("", true)
                  ]),
                  _: 2
                }, [
                  Vue.renderList(_ctx.$slots, (item, key) => {
                    return {
                      name: key,
                      fn: Vue.withCtx(() => [
                        key != "bottom" ? Vue.renderSlot(_ctx.$slots, key, { key: 0 }, void 0, true) : Vue.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__ */ _pluginVue_exportHelper.default(_sfc_main, [["__scopeId", "data-v-77c6ee76"]]);
exports.default = _Table;
