<template>
  <div
    class="row col-12"
    :id="props.config?.expandConfig ? 'fln-table-id' : ''"
    :style="{ width: props.tableWidth }"
  >
    <div
      class="col-12 row fl-mt-md"
      style="
        background: #ffffff;
        border-radius: 3px;
        padding: 13px 35px;
        box-shadow: 0 3px 6px 1px rgba(188, 188, 188, 0.18);
      "
    >
      <div class="col-12 row fl-mb-md">
        <div
          v-if="config.searchConfig"
          class="col-12 row"
          style="align-content: flex-start"
        >
          <template v-for="(item, idx) in state.searchConfig">
            <div
              :key="idx"
              v-if="calcSearchItemShow(item)"
              :style="item.style"
              class="fl-mt-sm"
              :class="item.class || 'col-3'"
            >
              <fln-form-item
                v-if="item.type === 'text'"
                type="text"
                :config="item"
                :val="item.value"
                :clearCount="state.clearSearchFormCount"
                @triggerValChange="handleValChange"
                @triggerNewValChange="handleFormNewValChange"
              />

              <fln-form-item
                v-if="item.type === 'inputsearch'"
                type="inputsearch"
                :config="item"
                :val="item.value"
                :clearCount="state.clearSearchFormCount"
                @triggerValChange="handleValChange"
                @triggerNewValChange="handleFormNewValChange"
              />

              <fln-form-item
                v-if="item.type === 'date'"
                type="date"
                :config="item"
                :picker="item.picker || 'date'"
                :format="item.format || 'YYYY-MM-DD'"
                :val="item.value"
                :clearCount="state.clearSearchFormCount"
                @triggerValChange="handleValChange"
                @triggerNewValChange="handleFormNewValChange"
              />

              <fln-form-item
                v-if="item.type === 'select'"
                type="select"
                :config="item"
                :val="item.value"
                :clearCount="state.clearSearchFormCount"
                :clearable="item.clearable"
                @triggerValChange="handleValChange"
                @triggerNewValChange="handleFormNewValChange"
              />

              <fln-form-item
                v-if="item.type === 'selectsearch'"
                type="selectsearch"
                :config="item"
                :val="item.value"
                :clearCount="state.clearSearchFormCount"
                :clearable="item.clearable"
                @triggerValChange="handleValChange"
                @triggerNewValChange="handleFormNewValChange"
              />

              <fln-form-item
                v-if="item.type === 'rangdate'"
                type="rangdate"
                :config="item"
                :format="item.format"
                :formItemConfig="item"
                :val="item.value"
                :clearCount="state.clearSearchFormCount"
                :clearable="item.clearable"
                @triggerValChange="handleValChange"
                @triggerNewValChange="handleFormNewValChange"
              />

              <fln-form-item
                v-if="item.type === 'rangnum'"
                type="rangnum"
                :config="item"
                :format="item.format"
                :val="item.value"
                :clearCount="state.clearSearchFormCount"
                :clearable="item.clearable"
                @triggerValChange="handleValChange"
                @triggerNewValChange="handleFormNewValChange"
              />
            </div>
          </template>

          <div
            style="width: 340px; margin-left: auto"
            class="row justify-around items-center fl-mt-sm"
          >
            <div
              v-if="config.tableBatchActions"
              class="fl-mb-sm"
              :class="config.tableBatchActionsClass"
              :style="['margin-right:auto', config.tableBatchActionsStyle]"
            >
              <template v-if="config.tableBatchActions.length > 0">
                <n-button
                  v-for="(btn, idx) in config.tableBatchActions"
                  v-show="
                    !state.tableEdit &&
                    visibleFormItem(btn.show, props.fatherData)
                  "
                  :key="idx"
                  v-permission="btn.permission"
                  :type="btn.type"
                  tertiary
                  :loading="btn.loading"
                  class="fl-mx-xs"
                  :class="btn.class"
                  :style="btn.style"
                  style="width: 161px; height: 34px"
                  :disabled="
                    btn.notLimitSelect
                      ? calcTableBatchActionsDisabled(btn)
                      : state.selectedRowKeys.length === 0
                  "
                  @click="handleTableBatchActions(state.selectedRows, btn)"
                >
                  {{ btn.label }}
                </n-button>
              </template>
            </div>
          </div>
        </div>
      </div>
      <!-- 白色背景里-表格上方插槽 -->
      <slot name="table-header-box"></slot>
      <n-data-table
        v-model:checked-row-keys="state.selectedRowKeys"
        :rowKey="(record) => record[config.rowKey] || record.uid"
        :columns="state.columns"
        class="fln-table"
        :loading="tableLoading"
        :row-class-name="config.rowClassName"
        :data="state.tableData"
        :expanded-row-keys="state.expandedRowKeys"
        :scroll-x="calcTableScrollWitdh()"
        :max-height="config.maxHeight"
        @update:checked-row-keys="handleTableRowSelect"
        @update:expanded-row-keys="handleExpandChange"
        @update:sorter="handleSort"
      >
      </n-data-table>

      <div class="col-12 row fl-my-sm justify-between">
        <div>
          <slot name="table-footer-l"></slot>
        </div>
        <div class="row items-center">
          <slot name="pagination-left"></slot>
          <span
            v-if="state.pagination.total"
            style="font-size: 16px"
            class="fl-mx-sm"
            >共<span class="fl-mx-xs">{{ state.pagination.total }}</span
            >条</span
          >
          <n-pagination
            v-if="tableType === 'pagination'"
            v-model:page="state.pagination.current"
            v-model:page-size="state.pagination.pageSize"
            show-size-picker
            show-quick-jumper
            :item-count="state.pagination.total"
            :page-sizes="state.pagination.pageSizeOptions"
            :on-update:page="handlePagination"
            :on-update:page-size="handlePaginationSize"
          />
        </div>
      </div>
    </div>

    <n-modal :show="state.modalMdVisible" :close-on-esc="false">
      <div
        class="row fl-ma-md fl-pa-sm justify-center overflow-auto height-100"
      >
        <div v-html="state.markdownVal"></div>
      </div>
    </n-modal>
  </div>
</template>
<script setup>
import { EditOutlined } from "@ant-design/icons-vue";
import {
  reactive,
  onBeforeMount,
  ref,
  watch,
  getCurrentInstance,
  computed,
  onUnmounted,
  onMounted,
} from "vue";

import { processError, processSuccess } from "@/utils/helper/message";
import { getParamsByObj, deepCopy, visibleFormItem } from "@/utils/helper/form";
import flnFormItem from "@/components/flnlayout/form/flnformItem.vue";
import flnTable from "@/components/flnlayout/table/flntable.vue";
import flnSecTable from "@/components/flnlayout/table/flnsectable.vue";
import tableCell from "./tablecell.vue";
const emit = defineEmits([
  "select",
  "triggerGetTableData",
  "triggerTableSearch",
  "triggerTableBatchActions",
  "triggerTableData",
  "triggerRowEditActSuccess",
  "triggerBatchSave",
  "triggerBatchCancel",
  "triggerBatchEdit",
  "triggerActionUrlSuccess",
  "triggerNewValChange",
  "triggerRowSelect",
  "triggerRowSelectAll",
  "triggerPreMd",
  "triggerRowActions",
  "triggerRowEditActions",
  "triggerRowClick",
  "triggerOneRowActionsSuccess",
  "triggerExpandRowKey",
  "triggerSelectCheck",
]);
const currentInstance = getCurrentInstance();

const { $request, $hadRule } =
  currentInstance.appContext.config.globalProperties;

const tableLoading = ref(false);
import staticpdf from "@/assets/file/pdf.png";
let props = defineProps({
  config: Object,
  fatherData: Object,
  pagination: Object,
  resetSearchConfigCount: Number,
  clearSelectCount: Number,
  getTableDataCount: Number,
  refreshCount: Number,
  refreshCountWithPagination: Number,
  tableType: {
    type: String,
    default: () => "pagination",
  },
  tableData: {
    type: Array,
    default: () => [],
  },
  fatherParams: {
    type: Object,
    default: () => {},
  },
  clearSelectRowKey: {
    type: [String, Number],
  },
  defaultSelectedRows: {
    type: Array,
  },
  innerkey: {
    type: Number,
  },
  scrollX: {
    type: String,
    default: "100%",
  },
  searchShow: {
    type: Boolean,
  },
  tableWidth: {
    type: String,
    default: "100%",
  },
  calcSearchConfigCount: Number,
  expandTable: {
    type: Boolean,
    default: false,
  },
});

const state = reactive({
  markdownVal: "",
  modalMdVisible: false,
  btnLoading: false,
  defaultSearch: null,
  searchData: {},
  sortParams: {},
  columns: [],
  tableData: [],
  pagination: {
    current: 1,
    pageSize: 10,
    total: 0,
    hideOnSinglePage: true,
    showQuickJumper: true,
    pageSizeOptions: [10, 20, 50],
  },
  selectedRowKeys: [],
  selectedRows: [],
  tableEdit: false,
  searchConfig: {},
  searchConfigData: {},
  clearSearchFormCount: 0,
  lastExpandedRowKeys: [],
  expandedRowKeys: [],
  selectRowData: [],
  selectKeyData: [],
  expandTableWidth: "100%",
});

onBeforeMount(() => {
  console.log("flnsectable onBeforeMount");
  state.pagination = Object.assign({}, state.pagination, props.pagination);
  state.columns = deepCopy(props.config.columns);

  getTableColumns();
  state.searchConfigData = {};
  if (props.config?.searchConfig) {
    // config 是给form item用的
    state.searchConfig = deepCopy(props.config.searchConfig);
    // search data 是给table检索用
    state.searchConfigData = {};
    calcSearchData();
  }
  if (props.config?.requestbysf) {
    return;
  }
  getTableData();

  // Add resize event listener
  window.addEventListener("resize", updateExpandTableWidth);
});
onMounted(() => {
  updateExpandTableWidth();
});
// Add cleanup function to remove event listener
onUnmounted(() => {
  window.removeEventListener("resize", updateExpandTableWidth);
});

// New function to update expandTableWidth
const updateExpandTableWidth = () => {
  const table = document.getElementById("fln-table-id");
  if (table) {
    state.expandTableWidth = table.offsetWidth - 110 + "px";
  } else {
    state.expandTableWidth = "100%";
  }
};

// Update calcExpandTableWidth to use reactive state
const calcExpandTableWidth = () => {
  return state.expandTableWidth;
};
watch(
  () => props.calcSearchConfigCount,
  () => {
    state.searchConfig = deepCopy(props.config.searchConfig);
    state.searchConfigData = {};
    state.searchConfig.forEach((item) => {
      if (item.field && !Array.isArray(item.field)) {
        state.searchConfigData[item.field] = item.value;
      }
      if (item.type === "rangnum") {
        state.searchConfigData[item.field[0]] = item.value[0];
        state.searchConfigData[item.field[1]] = item.value[1];
      }
    });
    getTableData();
  }
);
watch(
  () => props.defaultSelectedRows,
  () => {
    if (Array.isArray(props.defaultSelectedRows)) {
      if (props.defaultSelectedRows.length === 0) {
        return (state.selectedRowKeys = []);
      }
      props.defaultSelectedRows.forEach((item) => {
        let key = item[props.config.rowKey || "uid"];
        if (!state.selectedRowKeys.includes(key)) {
          state.selectedRowKeys.push(key);
        }
      });
    }
  },
  { deep: true }
);
watch(
  () => props.refreshCount,
  () => {
    getTableData();
  }
);
watch(
  () => props.searchShow,
  () => {
    state.searchConfig.map((item) => {
      if (item.show !== undefined) {
        item.show = props.searchShow;
      }
    });
  }
);
// 保留分页的刷新数据
watch(
  () => props.refreshCountWithPagination,
  () => {
    getTableData(true);
  }
);
watch(
  () => props.fatherParams,
  () => {
    getTableData();
  },
  { deep: true }
);
watch(
  () => props.getTableDataCount,
  () => {
    emit("triggerGetTableData", { tableData: state.tableData });
  }
);

watch(
  () => props.clearSelectRowKey,
  () => {
    let clearIdx = state.selectedRowKeys.indexOf(props.clearSelectRowKey);
    if (clearIdx >= 0) {
      state.selectedRowKeys.splice(clearIdx, 1);
    }
  }
);
// watch(
//   () => props.resetSearchConfigCount,
//   () => {
//     state.searchConfig = deepCopy(props.config.searchConfig);
//     state.searchConfigData = {};
//     calcSearchData()
//     getTableData();
//   }
// );
watch(
  () => props.clearSelectCount,
  () => {
    state.selectedRowKeys = [];
  }
);
watch(
  () => state.tableEdit,
  () => {
    if (state.tableEdit) {
      let rowKey = props.config.rowKey || "uid";
      let keys = state.selectedRows.map((item) => item[rowKey]);
      state.tableData.forEach((item) => {
        if (keys.includes(item[rowKey])) {
          item.rowEdit = true;
        }
      });
    } else {
      state.tableData.map((item) => delete item.rowEdit);
    }
  }
);

const handleTableRowSelect = (keys, rows, meta, action) => {
  // 多页数据选择
  if (meta.action === "check" || meta.action === "checkAll") {
    emit("triggerSelectCheck", {
      action: meta.action,
      selectedRow: rows,
    });
  } else if (meta.action === "uncheck") {
    emit("triggerSelectCheck", {
      action: meta.action,
      selectedRow: meta.row,
    });
  } else {
    emit("triggerSelectCheck", {
      action: meta.action,
      selectedRow: state.tableData,
    });
  }
  // 单页数据选择
  state.selectedRows = state.tableData.filter((item) =>
    keys.includes(item[props.config.rowKey || "uid"])
  );
  if (meta.action === "check" || meta.action === "uncheck") {
    emit("triggerRowSelect", {
      record: meta.row,
      selected: meta.action === "check",
      selectedRows: rows,
    });
  }
  if (meta.action === "checkAll" || meta.action === "uncheckAll") {
    emit("triggerRowSelectAll", {
      selectedRowKeys: keys,
      selectedRows: meta.action === "uncheckAll" ? [] : rows,
    });
  }
};
const handleExpandChange = (keys) => {
  if (keys.length > 0) {
    const diff = keys.filter((key) => !state.expandedRowKeys.includes(key));
    state.expandedRowKeys = diff.length > 0 ? [diff[0]] : [];
    emit("triggerExpandRowKey", keys[keys.length - 1]);
  } else {
    state.expandedRowKeys = [];
  }
};
const triggerCellEmit = (emitfunc, obj) => {
  emit(emitfunc, obj);
  // 已离职得某位大师 emit的triggerExpandRowKey 没理解这里触发的逻辑
  // 加了条件判断
  if (obj.rowData?.ID) {
    emit("triggerExpandRowKey", obj.rowData.ID);
  }
};
const triggerGetTableData = ({ refresh }) => {
  getTableData(refresh);
};
const triggerPreMd = ({ val }) => {
  state.markdownVal = val;
  state.modalMdVisible = true;
};
const getTableColumns = () => {
  if (props.config.hasSelection) {
    state.columns.unshift({
      type: "selection",
      width: 50,
      fixed: state.columns[1].fixed && state.columns[1].field ? "left" : false,
      multiple: props.config.multiple,
      disabled(row) {
        if (props.config?.selectDisable) {
          return visibleFormItem(props.config?.selectDisable, row);
        }
        return false;
      },
    });
  }
  if (props.config.expandConfig) {
    state.columns.unshift({
      type: "expand",
      expandable: (rowData) => true,
      renderExpand: (rowData, rowIndex) => {
        if (props.config.expandConfig.searchInTable) {
          return h(flnSecTable, {
            style: {
              position: "sticky",
              left: "15px",
            },
            config: props.config.expandConfig,
            fatherData: rowData,
            tableWidth: calcExpandTableWidth(),
            rowClassName: props.config.expandConfig.rowClassName,
            tableType: props.config.expandConfig.tableType,
            fatherParams: props.config.expandConfig.fatherParams,
            pagination: props.config.expandConfig.pagination,
            refreshCount: props.config.expandConfig.refreshCount,
            defaultSelectedRows: props.config.expandConfig.defaultSelectedRows,
            calcSearchConfigCount:
              props.config.expandConfig.calcSearchConfigCount,
            getTableDataCount: props.config.expandConfig.getTableDataCount,
            rowIndex,
            onTriggerRowActions: (e) => triggerCellEmit("triggerRowActions", e),
            onTriggerSelectCheck: (e) =>
              triggerCellEmit("triggerSelectCheck", e),
            onTriggerTableBatchActions: (e) =>
              triggerCellEmit("triggerTableBatchActions", e),
          });
        } else {
          return h(flnTable, {
            style: {
              position: "sticky",
              left: "15px",
            },
            config: props.config.expandConfig,
            fatherData: rowData,
            tableWidth: calcExpandTableWidth(),
            rowClassName: props.config.expandConfig.rowClassName,
            tableType: props.config.expandConfig.tableType,
            fatherParams: props.config.expandConfig.fatherParams,
            pagination: props.config.expandConfig.pagination,
            refreshCount: props.config.expandConfig.refreshCount,
            defaultSelectedRows: props.config.expandConfig.defaultSelectedRows,
            calcSearchConfigCount:
              props.config.expandConfig.calcSearchConfigCount,
            getTableDataCount: props.config.expandConfig.getTableDataCount,
            rowIndex,
            onTriggerRowActions: (e) => triggerCellEmit("triggerRowActions", e),
            onTriggerSelectCheck: (e) =>
              triggerCellEmit("triggerSelectCheck", e),
            onTriggerTableBatchActions: (e) =>
              triggerCellEmit("triggerTableBatchActions", e),
          });
        }
      },
    });
  }
  state.columns.forEach((item) => {
    if (!item.align) {
      item.align = "center";
    }
    if (!item.width) {
      item.width = 80;
    }
    if (!item.title && item.label) {
      item.title = item.label;
    }
    if (!item.key && item.field) {
      item.key = item.field;
    }
    if (item.render) {
      return;
    }
    if (item.type || item.actions || item.editConfig) {
      item.render = (rowData, index) => {
        return h(tableCell, {
          text: rowData,
          column: item,
          index,
          fatherData: props.fatherData,
          tableData: state.tableData,
          onTriggerRowActions: (e) => triggerCellEmit("triggerRowActions", e),
          onTriggerPreMd: (e) => triggerPreMd(e),
          onTriggerGetTableData: (e) => triggerGetTableData(e),
          onTriggerActionUrlSuccess: (e) =>
            triggerCellEmit("triggerActionUrlSuccess", e),
          onTriggerOneRowActionsSuccess: (e) =>
            triggerCellEmit("triggerOneRowActionsSuccess", e),
          onTriggerRowClick: (e) => triggerCellEmit("triggerRowClick", e),
          onTriggerRowEditActSuccess: (e) =>
            triggerCellEmit("triggerRowEditActSuccess", e),
          onTriggerRowEditActions: (e) =>
            triggerCellEmit("triggerRowEditActions", e),
        });
      };
    }
  });
  calcTableScrollWitdh();
};

const calcTableScrollWitdh = () => {
  let scrollWitdh = 0;
  state.columns.forEach((item) => {
    scrollWitdh += item.width || 80;
  });
  return scrollWitdh + 200;
};
// 无传参 重置分页
const getTableData = (currentNoReset) => {
  state.btnLoading = true;
  // change by pagination do not need reset
  // search change need reset pagination
  // currentNoReset 分页重置参数   --- false分页从第一页开始
  if (currentNoReset !== true) {
    state.pagination.current = 1;
  }
  state.tableEdit = false;
  if (!props.config.listUrl) {
    state.tableData = props.tableData;
    return;
  }
  tableLoading.value = true;
  let urlConfig = props.config.listUrl;
  let url = urlConfig.url;
  let params = {};
  // 分页
  if (props.tableType === "pagination") {
    if (urlConfig.pageField) {
      params[urlConfig.pageField] = state.pagination.current;
      params[urlConfig.pageSizeField] = state.pagination.pageSize;
    } else {
      Object.assign(params, {
        Page: state.pagination.current,
        PageSize: state.pagination.pageSize,
      });
    }
  }
  // 针对 模糊检索
  if (Object.keys(state.searchData).length > 0) {
    Object.assign(params, state.searchData);
  }
  // 检索
  if (Object.keys(state.searchConfigData).length > 0) {
    Object.assign(params, state.searchConfigData);
  }
  // 排序
  if (Object.keys(state.sortParams).length > 0) {
    Object.assign(params, state.sortParams);
  }
  params = getParamsByObj(params, urlConfig.params, props.fatherData);

  Object.assign(params, props.fatherParams);
  $request.HTTP.components.postDataByParams(url, params).then(
    (res) => {
      if (state.defaultSearch && JSON.stringify(state.searchData) === "{}") {
        calcDefaultSearchData();
      }
      emit("triggerTableSearch", {
        searchParams: Object.assign(
          {},
          state.searchData,
          state.searchConfigData,
          state.sortParams,
          props.fatherParams
        ),
      });
      if (res.status === 0 || res.status === 200) {
        if (props.tableType === "pagination") {
          state.pagination.total =
            res.data.Count ||
            res.data.Total ||
            res.data.count ||
            res.data.total ||
            res.data.countTotal ||
            res.data.participantCountTotal; // 儿童美术作品管理-后端宋闯
          if (res.data[urlConfig.totalField]) {
            state.pagination.total = res.data[urlConfig.totalField];
          }
          if (urlConfig.resDataField) {
            state.tableData = res.data[urlConfig.resDataField] || [];
          } else {
            state.tableData = res.data.Data || [];
          }
        } else if (urlConfig.resDataField) {
          state.tableData = res.data[urlConfig.resDataField] || [];
        } else {
          state.tableData = res.data || [];
        }
        if (props.defaultSelectedRows?.length > 0) {
          props.defaultSelectedRows.forEach((item) => {
            let key = item[props.config.rowKey || "uid"];
            if (!state.selectedRowKeys.includes(key)) {
              state.selectedRowKeys.push(key);
            }
          });
        } else {
          state.selectedRowKeys = [];
        }
        emit("triggerTableData", {
          tableData: state.tableData,
          resData: res.data,
        });
      } else {
        processError(res.msg || "获取数据失败");
      }
      tableLoading.value = false;
      state.btnLoading = false;
    },
    (err) => {
      state.btnLoading = false;
      tableLoading.value = false;
      processError(err?.response?.data?.msg || "获取数据失败");
    }
  );
};

const calcDefaultSearchData = () => {
  state.searchData = {};
  if (state.defaultSearch) {
    let searchData = {};
    props.config.defaultSearch.fields.forEach((item) => {
      searchData[item] = state.defaultSearch;
    });
    state.searchData = searchData;
  }
};

// defineExpose({
//   state,
//   getTableData,
// });

// const calcHeight = (coefficient, defaultHeight) => {
//   // return 200
//   if (props.config.tableMaxHeight) {
//     return props.config.tableMaxHeight;
//   }
//   let calcVal = window.innerHeight * coefficient;
//   return calcVal > defaultHeight ? calcVal : defaultHeight;
// };

const handlePagination = (page) => {
  state.pagination.current = page;
  getTableData(true);
};
const handlePaginationSize = (pageSize) => {
  state.pagination.pageSize = pageSize;
  getTableData();
};
const calcSearchItemShow = (item) => {
  if (item.show !== undefined) {
    return item.show;
  }
  if (item.permission !== undefined) {
    return $hadRule(item.permission);
  }
  return true;
};
const calcVisible = (ruleBtn) => {
  if (ruleBtn) {
    return $hadRule(ruleBtn);
  }
  return true;
};

// 批量编辑
const handleBatchEdit = () => {
  state.tableEdit = true;
  emit("triggerBatchEdit");
};

const handleBatchSave = () => {
  let editUrl = props.config.batchEditConfig.editUrl;

  let ignoreFields = props.config.batchEditConfig.ignoreFields;
  if (editUrl) {
    let editField = props.config.batchEditConfig.editUrl.editField;
    state.btnLoading = true;
    let rowKey = props.config.rowKey || "uid";
    let keys = state.selectedRows.map((item) => item[rowKey]);
    let editData = [];
    state.tableData.forEach((item) => {
      if (keys.includes(item[rowKey])) {
        if (Array.isArray(ignoreFields)) {
          ignoreFields.forEach((field) => {
            delete item[field];
          });
        }
        editData.push(item);
      }
    });
    let url = editUrl.url;
    let params = getParamsByObj({}, editUrl.params, props.fatherData);
    let postObj = {};
    if (editField) {
      postObj[editField] = editData;
      Object.assign(postObj, params);
    } else {
      Object.assign(postObj, params, { editData });
    }

    $request.HTTP.components.postDataByParams(url, postObj, {}).then(
      (res) => {
        if (res.status === 0) {
          state.selectedRowKeys = [];
          getTableData(true);
          processSuccess("操作成功！");
        } else {
          processError("操作失败！");
        }
        state.btnLoading = false;
      },
      () => {
        processError("操作失败！");
        state.btnLoading = false;
      },
      () => {
        processError("操作失败！");
        state.btnLoading = false;
      }
    );
  } else {
    emit("triggerBatchSave", {
      selectedRows: state.selectedRows,
      config: props.config,
      fatherData: props.fatherData,
    });
  }
};

const handleBatchCancel = () => {
  state.selectedRowKeys = [];
  getTableData(true);
  emit("triggerBatchCancel", {
    selectedRows: state.selectedRows,
    config: props.config,
    fatherData: props.fatherData,
  });
};
// 批量操作
const handleTableBatchActions = (selectedRows, btnConfig, fatherData) => {
  emit("triggerTableBatchActions", {
    selectedRows,
    btnConfig,
    fatherData: props.fatherData || fatherData,
  });
};

const calcTableBatchActionsDisabled = (config) => {
  if (config.hasTableData && state.tableData.length === 0) {
    return true;
  }
  return config.disable || false;
};

const handleValChange = ({ val, config }) => {
  if (config.type === "rangdate") {
    state.searchConfigData[config.field[0]] = val[0];
    state.searchConfigData[config.field[1]] = val[1];
    if (config.format === "hh:mm:ss" && val[0]) {
      state.searchConfigData[config.field[0]] = val[0] + " 00:00:00";
      state.searchConfigData[config.field[1]] = val[1] + " 23:59:59";
    }
  } else if (config.type === "rangnum") {
    state.searchConfigData[config.field[0]] = val[0];
    state.searchConfigData[config.field[1]] = val[1];
  } else {
    state.searchConfigData[config.field] = val;
  }
  getTableData();
};
const handleFormNewValChange = (obj) => {
  emit("triggerNewValChange", { obj });
};

const handleSearch = () => {
  getTableData();
};
const handleResetSearch = () => {
  state.searchConfigData = {};
  state.searchConfig = deepCopy(props.config.searchConfig);
  calcSearchData();
  state.clearSearchFormCount++;
  getTableData();
};
const calcSearchData = () => {
  state.searchConfig.forEach((item) => {
    if (item.field && !Array.isArray(item.field)) {
      state.searchConfigData[item.field] = item.value;
    }
    if (item.type === "rangnum") {
      item.value = item.value || [];
      state.searchConfigData[item.field[0]] = item.value[0];
      state.searchConfigData[item.field[1]] = item.value[1];
    }
    if (item.type === "rangdate") {
      item.value = item.value || [];
      state.searchConfigData[item.field[0]] = item.value[0];
      state.searchConfigData[item.field[1]] = item.value[1];
    }
  });
};

const handleSort = (sortData) => {
  state.sortParams = {};
  if (sortData.order !== false) {
    if (props.config.sortField && props.config.sortOrder) {
      state.sortParams[props.config.sortField] = sortData.columnKey;
      state.sortParams[props.config.sortOrder] = sortData.order;
    } else {
      state.sortParams["sortField"] = sortData.columnKey;
      state.sortParams["sortOrder"] = sortData.order;
    }
  }
  getTableData();
};
</script>

<style lang="scss" scoped>
// 不走table得max-height
:deep(.fln-table .n-scrollbar-content) {
  // max-height: 200px;
}
:deep(.fln-table .n-data-table-thead) {
  position: sticky;
  z-index: 10;
  top: 0;
}

:deep(.fln-table .n-scrollbar-content) {
  overflow: auto;
}
:deep(.fln-table .n-data-table-table) {
  max-width: 100%;
  overflow: auto;
}
:deep(.fln-table) {
  --n-merged-th-color-hover: #46299d !important;
}
:deep(.fln-table .n-data-table-th.n-data-table-th--sorting) {
  --n-merged-th-color-sorting: #46299d !important;
}
</style>
