<template>
  <div>
    <div
      class="select-btn flex h-32px"
      v-if="
        (!disabled && isShowAdd) ||
        useSelectButton ||
        isImport ||
        isExport ||
        (isDeleteSelected &&
          ((props.preloadType === 'api' && !props.apiConfig?.path) ||
            (props.preloadType === 'dic' && !props.itemId))) ||
        (topButtonList && topButtonList.length > 0) ||
        (!(props.multipleHeads && props.multipleHeads.length > 0) && showColunmSet)
      "
    >
      <a-button type="primary" @click="add" v-if="!disabled && isShowAdd" class="mr-2">
        <PlusOutlined />
        {{ t('新增') }}
      </a-button>
      <a-button
        type="primary"
        @click="multipleDialog = true"
        v-if="useSelectButton"
        class="select-btn mr-2"
        :disabled="disabled"
      >
        {{ buttonName }}
      </a-button>
      <ImpExcel @success="importTable" v-if="isImport">
        <a-button type="primary" :disabled="disabled" class="mr-2"> 导入 </a-button>
      </ImpExcel>
      <a-button
        type="primary"
        @click="exportTable"
        v-if="isExport"
        :disabled="disabled"
        class="mr-2"
      >
        导出
      </a-button>
      <a-button
        type="danger"
        @click="deleteSelectedData"
        v-if="
          isDeleteSelected &&
          ((props.preloadType === 'api' && !props.apiConfig?.path) ||
            (props.preloadType === 'dic' && !props.itemId))
        "
        :disabled="disabled"
        class="mr-2"
      >
        批量删除
      </a-button>
      <div v-if="topButtonList && topButtonList.length > 0">
        <template v-for="item in topButtonList" :key="item.key">
          <CustomButtonModal v-if="item.type == CustomButtonModalType.Modal" :info="item" />
          <a-button
            v-else
            :type="item.style"
            @click="customClick(item)"
            :disabled="disabled"
            class="mr-2"
          >
            <Icon :icon="item.icon" />
            {{ t(item.label) }}
          </a-button>
        </template>
      </div>
      <FormItemRest v-if="!(props.multipleHeads && props.multipleHeads.length > 0) && showColunmSet"
        ><ColumnSetting
          :columns="showColumns"
          :mainKey="mainKey"
          @columns-change="handleColumnChange"
        />
      </FormItemRest>
    </div>
    <FormItemRest>
      <a-table
        :id="'table' + madomkey"
        :row-selection="rowSelection"
        :columns="headColums.length > 0 ? headColums : columnsList"
        :bordered="showBorder"
        :pagination="showPagenation ? pagination : false"
        :data-source="data"
        :scroll="{ x: 'max-content', y: height }"
        :expandedRowKeys="expandedRowKeys"
        @expand="onExpand"
        @change="handleTableChange"
        @resize-column="handleResizeColumn"
      >
        <template #summary>
          <a-table-summary-row v-if="columnsList.some((x) => x.componentProps?.subTotal)">
            <a-table-summary-cell v-for="(column, idx) in columnsList" :key="idx">
              <a-typography-text keyboard v-if="column.componentProps?.subTotal">
                {{ t('合计：') }} {{ getColumnTotal(column.dataIndex) }}
              </a-typography-text>
            </a-table-summary-cell>
          </a-table-summary-row>
        </template>
        <template #bodyCell="{ column, record, index }">
          <template v-if="column.key !== 'action'">
            <template v-if="column.key === 'index'">
              {{ index + 1 }}
            </template>
            <template v-else-if="column.isEdit">
              <div
                class="ant-table-cell-ellipsis"
                :title="record[column.dataIndex]"
                :style="
                  column.width
                    ? executeListStyle(record, column?.componentProps?.listStyle) +
                      `;width: ${isNumber(column.width) ? column.width + 'px' : column.width}`
                    : executeListStyle(record, column?.componentProps?.listStyle)
                "
              >
                {{ record[column.dataIndex] }}</div
              >
            </template>
            <FormItem
              :name="[mainKey, index, column.dataIndex]"
              :rules="rules(column, record, index)"
              :validateTrigger="['blur', 'change']"
              v-else-if="!column.isEdit"
            >
              <!---如果是checked一类的组件-->
              <template v-if="checkedValueComponents.includes(column.componentType)">
                <component
                  :key="subRefreshFieldObj[index][column.dataIndex]"
                  :is="componentMap.get(column.componentType)"
                  :bordered="showComponentBorder"
                  v-bind="getComponentsProps(column, record, index)"
                  v-model:checked="record[column.dataIndex]"
                  :index="realindex + index"
                  :style="executeListStyle(record, column?.componentProps?.listStyle)"
                />
              </template>
              <!---如果是RangePicker组件-->
              <template
                v-else-if="
                  column.componentType === 'RangePicker' ||
                  column.componentType === 'TimeRangePicker'
                "
              >
                <component
                  :key="subRefreshFieldObj[index][column.dataIndex]"
                  :is="componentMap.get(column.componentType)"
                  :bordered="showComponentBorder"
                  v-bind="getComponentsProps(column, record, index)"
                  v-model:startField="column.dataIndex.split(',')[0]"
                  v-model:endField="column.dataIndex.split(',')[1]"
                  v-model:value="record[column.dataIndex]"
                  v-model:record="data[index]"
                  :mainKey="mainKey"
                  :index="realindex + index"
                  :style="executeListStyle(record, column?.componentProps?.listStyle)"
                />
              </template>
              <template v-else-if="column.componentType === 'RichTextEditor'">
                <component
                  :key="subRefreshFieldObj[index][column.dataIndex]"
                  :is="componentMap.get('TableEditor')"
                  :bordered="showComponentBorder"
                  v-bind="getComponentsProps(column, record, index)"
                  v-model:value="record[column.dataIndex]"
                  :mainKey="mainKey"
                  :index="realindex + index"
                />
              </template>
              <!---如果是渲染函数组件-->
              <template v-else-if="column.componentType === 'Render'">
                <component
                  :key="subRefreshFieldObj[index][column.dataIndex]"
                  :bordered="showComponentBorder"
                  :is="
                    column.render({
                      model: record,
                      field: column.dataIndex,
                      rules: column.rules,

                      componentProps: getComponentsProps(column, record, index),
                    })
                  "
                />
              </template>

              <template v-else-if="column.componentType === 'Slot'">
                <component
                  :key="subRefreshFieldObj[index][column.dataIndex]"
                  :bordered="showComponentBorder"
                  v-bind="getComponentsProps(column, record, index)"
                  :is="props.slots![column.slot]"
                  :formModel="formModel"
                  :field="column.dataIndex"
                  :mainKey="mainKey"
                  :index="realindex + index"
                />
              </template>
              <template v-else-if="column.componentType === 'XjrCustomModal'">
                <a-button
                  :key="column.key"
                  type="primary"
                  @click="showModal(column, record, index)"
                  >{{ column.title }}</a-button
                >
              </template>
              <template v-else-if="column.key !== 'index'">
                <component
                  :key="subRefreshFieldObj[index][column.dataIndex]"
                  :is="componentMap.get(column.componentType)"
                  :bordered="showComponentBorder"
                  v-bind="getComponentsProps(column, record, index)"
                  :index="realindex + index"
                  :mainKey="mainKey"
                  :isView="isView"
                  v-model:value="record[column.dataIndex]"
                  @change="handleChange(column.componentType, column.dataIndex, index)"
                  :style="executeListStyle(record, column?.componentProps?.listStyle)"
                />
              </template>
            </FormItem>
          </template>
          <template v-if="column.key === 'action' && !disabled">
            <template v-if="buttonList && buttonList.length > 0">
              <template v-for="(item, idx) in buttonList" :key="item.key">
                <a-tooltip v-if="item.icon">
                  <template #title> {{ t(item.label) }}</template>
                  <Icon
                    :icon="item.icon"
                    :style="{
                      marginRight: idx == buttonList.length - 1 && !isShowDelete ? '' : '10px',
                    }"
                    @click="customClick(item, record, index)"
                  />
                </a-tooltip>
                <a-button
                  @click="customClick(item, record, index)"
                  v-else-if="item.label && !item.icon"
                  type="link"
                  size="small"
                  :style="{
                    marginRight: idx == buttonList.length - 1 && !isShowDelete ? '' : '10px',
                    padding: 0,
                    border: 0,
                  }"
                  >{{ t(item.label) }}</a-button
                >
              </template>
            </template>
            <MinusCircleOutlined
              v-if="isShowDelete"
              @click="remove(index, record)"
              style="padding-bottom: 20px"
            />
          </template>
          <div class="resize-handle" v-if="rowResize"></div>
        </template>
        <template #expandedRowRender="{ record, index }" v-if="sunFormInfo"
          ><div v-show="getIsShow(sunFormInfo)">
            <SunForm
              :disabled="disabled"
              :form-api="formApi"
              :subFormIndex="index"
              :subFormList="mainKey"
              v-bind="getComponentsProps(sunFormInfo, record, index)"
              v-model:value="record[sunFormInfo.mainKey!]"
            />
          </div>
        </template>
      </a-table>
    </FormItemRest>

    <FormItemRest>
      <MultipleSelect
        ref="MultipleSelectRef"
        v-if="multipleDialog"
        v-model:multipleDialog="multipleDialog"
        :params="{ itemId }"
        :datasourceType="preloadType"
        :dicOptions="dicOptions"
        :apiConfig="apiConfig"
        :isSubFormUse="useSelectButton"
        @submit="renderSubFormList"
        popupType="preload"
      />
      <TableCustomModal
        @register="registerModal"
        @confirm="
          (val) => {
            data[curRecord] = val;
            handleConfirm('confirm');
          }
        "
        @cancel="
          () => {
            handleConfirm('cancel');
          }
        "
        @open="
          () => {
            handleConfirm('open');
          }
        "
        @close="
          () => {
            handleConfirm('close');
          }
        "
      />
    </FormItemRest>
  </div>
</template>
<script lang="ts" setup>
  import { PlusOutlined, MinusCircleOutlined } from '@ant-design/icons-vue';
  import { Form } from 'ant-design-vue';
  import { inject, onMounted, ref, unref, watch, nextTick, computed, reactive, Ref } from 'vue';
  import { SubFormColumn } from '../types';
  import { componentMap } from '../componentMap';
  import { DicDataComponents, checkedValueComponents, staticDataComponents } from '../helper';
  import { MultipleSelect } from '/@/components/MultiplePopup';
  import { isFunction, cloneDeep, isBoolean, upperFirst, isNil, isNumber } from 'lodash-es';
  import { deepMerge } from '/@/utils';
  import {
    apiConfigFunc,
    camelCaseString,
    isValidJSON,
    moneyChineseData,
  } from '/@/utils/event/design';
  import { getDicDetailList } from '/@/api/system/dic';
  import { getDepartment, getDepartmentTree } from '/@/api/system/department';
  import { getUserMulti, getUser, getAllUserList } from '/@/api/system/user';
  import { getAreaList } from '/@/api/system/area';
  import { getInfo } from '/@/api/system/generator/treeStructure';
  import { TreeStructureType } from '/@/enums/treeStructure';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { MutipleHeadInfo } from '/@/components/Designer';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { FormActionType } from '/@/components/Form/src/types/form';
  import XLSX from 'xlsx-js-style';
  import { ImpExcel, ExcelData } from '/@/components/Excel';
  import SunForm from './SunForm.vue';
  import TableCustomModal from './TableCustomModal.vue';
  import JBC from 'jsbi-calculator';
  import ColumnSetting from './ColumnSetting.vue';
  import { useUserStore } from '/@/store/modules/user';
  import { executeListStyle } from '/@/hooks/web/useListStyle';
  import { Icon } from '/@/components/Icon';
  import { executeCurFormEvent } from '/@/utils/event/data';
  import { useModal } from '/@/components/Modal';
  import { ExecuteType } from '/@/enums/desktop';
  import { CustomButtonModalType } from '/@/enums/userEnum';
  import CustomButtonModal from '/@/components/Form/src/components/CustomButtonModal.vue';

  const { t } = useI18n();
  // 用于包裹弹窗的form组件 因为一个FormItem 只能收集一个表单组件  所以弹窗的form 必须排除
  // const FormItemRest = Form.ItemRest;
  const FormItem = Form.Item;
  const FormItemRest = Form.ItemRest;

  //const prereloadData = ref<Recordable[] | undefined>(undefined);
  const multipleDialog = ref<boolean>(false);
  const emit = defineEmits(['change', 'update:value', 'add', 'delete', 'select', 'load']);
  const { calculator } = JBC;

  const props = defineProps({
    /**
     * 如果是编辑状态 默认现实的值
     */
    value: { type: Array as PropType<Recordable[]>, default: () => [] },
    /**
     * 是否预加载
     */
    preload: {
      type: Boolean,
      default: false,
    },
    /**
     * 预加载 类型 开启 preload  为true 才有用
     * datasource || dataitem
     */
    preloadType: { type: String, default: null },

    /**
     * 需要绑定主表的字段  用于验证  必填
     */
    mainKey: { type: String, required: true },
    /**
     * 子表单配置
     */
    columns: {
      type: Array as PropType<SubFormColumn[]>,
      required: true,
    },
    /**
     * 是否禁用所有组件
     */
    disabled: {
      type: Boolean,
      default: false,
    },
    /**
     * 预加载数据为api时使用
     */
    apiConfig: Object,
    /**
     * 预加载数据为数据字典时使用
     */
    itemId: String,
    dicOptions: Array,
    /**
     * 是否使用按钮选数据
     */
    useSelectButton: Boolean,
    /**
     * 选数据按钮名称
     */
    buttonName: String,
    //是否显示表格边框
    showBorder: Boolean,
    //是否显示组件边框
    showComponentBorder: Boolean,
    //是否展示序号
    showIndex: Boolean,
    //add before hooks
    addBefore: Function,
    //add after hooks
    addAfter: Function,
    isView: Boolean,
    rowSpan: String,
    showColunmSet: Boolean,
    showPagenation: {
      type: Boolean,
      default: () => true,
    },
    //表头合并数据
    multipleHeads: { type: Array as PropType<MutipleHeadInfo[]> },
    buttonList: Array as any,
    topButtonList: Array as any,
    formApi: {
      type: Object as PropType<FormActionType>,
    },
    isExport: {
      type: Boolean,
      default: false,
    },
    isImport: {
      type: Boolean,
      default: false,
    },
    isDeleteSelected: {
      type: Boolean,
      default: false,
    },
    tableName: {
      type: String,
      default: '',
    },
    //插槽节点
    slots: [Object, Array],
    bordercolor: {
      type: String,
      default: '#f0f0f0',
    },
    bordershowtype: {
      type: Array,
      default: () => [true, true, true, true],
    },
    borderwidth: {
      type: Number,
      default: 1,
    },
    isShowAdd: {
      type: Boolean,
      default: true,
    },
    isShowDelete: {
      type: Boolean,
      default: true,
    },
    hasCheckedCol: {
      type: Boolean,
      default: true,
    },
    //刷新api使用
    refreshFieldObj: {
      type: Object,
      default: () => ({}),
    },
    //表格列宽配置
    widths: Array,
    //表格行高可拖拽改变
    rowResize: Boolean,
    height: Number,
  });
  const [registerModal, { openModal }] = useModal();
  const userStore = useUserStore();
  const data = ref<Recordable[]>([]);
  //缓存字段是否disable
  const cacheMap = new Map<String, number[]>();
  const expandedRowKeys = ref<number[]>([]);
  const headColums = ref<MutipleHeadInfo[]>([]); // 多表头
  const originHeads = ref<MutipleHeadInfo[]>([]); // 多表头源数据
  const columnsList = ref<SubFormColumn[]>(props.columns);
  const isCamelCase = inject<boolean>('isCamelCase', false);
  const apiComponent = ['XjrSelect', 'AssociateSelect', 'ApiRadioGroup'];
  const madomkey = ref<string>(Math.random().toString(36).slice(-8));
  const changeColumns = ref({});
  // 注入表单数据
  const formModel = inject<any>('formModel', null);
  const formId = inject<Ref<string>>('currentFormId') as Ref<string>;
  const { notification } = useMessage();
  const showColumns = ref<any>([]);
  const sunFormInfo = computed(() => {
    return props.columns.find((x) => x.componentType === 'SunForm');
  });
  const subRefreshFieldObj = ref<any>([]);
  const formborderwidth = computed(() => {
    return props.borderwidth + 'px';
  });
  const curRecord = ref();
  const curButtonModalConfig = ref();
  const selectedRowKeys = ref<string[]>([]);
  const selectedRowsData = ref<any>([]);
  const rowSelection = computed(() => {
    return props.hasCheckedCol
      ? {
          selectedRowKeys: selectedRowKeys.value,
          onChange: (selectedKeys: string[], selectedRows) => {
            selectedRowsData.value = selectedRows;
            selectedRowKeys.value = selectedKeys;
            emit('select', { selectedKeys, selectedRows });
          },
        }
      : null;
  });
  //分页
  const pagination = reactive({
    current: 1,
    pageSize: 10,
    total: 0,
    showSizeChanger: true,
    pageSizeOptions: ['5', '10', '20', '30', '40', '50'],
    showTotal: (total) => {
      return `共 ${total} 条`;
    },
  });

  const realindex = computed(() => {
    return (pagination.current - 1) * pagination.pageSize;
  });

  onMounted(() => {
    props.columns.forEach((col) => {
      if (col.dataIndex) {
        changeColumns.value[col.dataIndex] = { default: cloneDeep(col) };
      }
    });
    data.value = cloneDeep(props.value);
    if (props.showIndex && columnsList.value && columnsList.value[0].key !== 'index') {
      columnsList.value.unshift({
        title: '序号',
        key: 'index',
        align: 'center',
        width: 60,
      });
    }
    showColumns.value = cloneDeep(columnsList.value);
    let tableColumnShowSetting = isValidJSON(localStorage.getItem('tableColumnShowSetting'));

    if (
      tableColumnShowSetting &&
      formId &&
      tableColumnShowSetting[userStore.getUserInfo.id] &&
      tableColumnShowSetting[userStore.getUserInfo.id][formId.value] &&
      tableColumnShowSetting[userStore.getUserInfo.id][formId.value][props.mainKey]
    ) {
      columnsList.value =
        tableColumnShowSetting[userStore.getUserInfo.id][formId.value][props.mainKey];
    } else {
      columnsList.value = filterColum(columnsList.value);
    }

    updateColum(props.widths);
    nextTick(() => {
      //处理多表头
      if (props.multipleHeads && props.multipleHeads.length > 0) {
        originHeads.value = cloneDeep(props.multipleHeads);

        getColumns(columnsList.value);
        //过滤权限为不显示的组件
        filterHeads(headColums.value);
      }
    });
  });

  watch(
    () => props.columns,
    (val) => {
      if (!formId) columnsList.value = filterColum(val);
    },
    {
      deep: true,
    },
  );
  watch(
    () => props.widths,
    (val) => {
      updateColum(val);
    },
    {
      deep: true,
    },
  );
  watch(
    () => data.value,
    (val) => {
      if (!(props.preloadType === 'api' && props.apiConfig?.path)) {
        pagination.total = data.value.length;
      }

      if (val?.length) {
        val.forEach((item, index) => {
          item.key = index;
          if (sunFormInfo.value && item[sunFormInfo.value!.mainKey!]?.length) {
            expandedRowKeys.value.push(item.key);
          }
        });
      }
      if (val.length && !sunFormInfo.value) {
        if (props.rowSpan) {
          let colName: string = isCamelCase ? camelCaseString(props.rowSpan) || '' : props.rowSpan;
          let curI = 0;
          let cur = val[curI][colName];
          let arr: number[] = [];
          val.forEach((o, i) => {
            arr.push(1);
            if (i >= 1) {
              if (
                o[colName] == cur &&
                o[colName] !== '' &&
                o[colName] !== null &&
                o[colName] !== undefined
              ) {
                arr[curI] += 1;
                arr[i] = 0;
              } else {
                curI = i;
                cur = val[curI][colName];
              }
            }
          });
          let newcolumns = headColums.value.length > 0 ? headColums.value : columnsList.value;
          newcolumns.forEach((item) => {
            if (item.dataIndex == colName) {
              item.customCell = (_, index) => {
                let obj = { rowSpan: 1 };
                arr.forEach((o, i) => {
                  if (index == i) {
                    obj = { rowSpan: o };
                  }
                });
                return obj;
              };
            }
          });
        }
      }
      handleResizeRow();
    },
    {
      deep: true,
    },
  );

  watch(
    () => props.value,
    (v) => {
      // console.log('watch props.value', props.value);
      data.value = v;
      if (subRefreshFieldObj.value.length <= 0) {
        v.forEach(() => {
          subRefreshFieldObj.value.push({});
        });
      }
      // const rangeComponents = props.columns.filter((column) =>
      //   column.componentType?.includes('Range'),
      // );
      // if (rangeComponents.length && formModel) {
      //   rangeComponents.forEach((item) => {
      //     data.value.forEach((x) => {
      //       if (x[(item.dataIndex as string)?.split(',')[0]]) {
      //         x[item.dataIndex as string] = [
      //           x[(item.dataIndex as string)?.split(',')[0]],
      //           x[(item.dataIndex as string)?.split(',')[1]],
      //         ];
      //       }
      //     });
      //   });
      // }

      //要保证在预加载之后在emit  不然预加载数据不会绑定到表单数据中
      emit('change', unref(data));
      emit('update:value', unref(data));
      emit('load', unref(data));
    },
    { deep: true },
  );

  function handleResizeRow() {
    if (!props.rowResize) return;
    nextTick(() => {
      const table = document.getElementById('table' + madomkey.value);
      const rows: any = table?.querySelectorAll('.ant-table-row');
      for (let row of rows) {
        const resizable: any = row.getElementsByClassName('ant-table-cell');
        for (let item of resizable) {
          const handle = item.querySelector('.resize-handle');
          let originY, originHeight;

          handle?.addEventListener('mousedown', function (e) {
            originY = e.clientY;
            originHeight = item.offsetHeight;

            document.addEventListener('mousemove', resize);
            document.addEventListener('mouseup', stopResize);
          });

          function resize(e) {
            const height = originHeight + (e.clientY - originY);
            resizable[0].style.height = `${height}px`;
          }

          function stopResize() {
            document.removeEventListener('mousemove', resize);
            document.removeEventListener('mouseup', stopResize);
          }
        }
      }
    });
  }
  function handleResizeColumn(w, col) {
    col.width = w;
  }

  function getColumns(children) {
    let headsColumn: MutipleHeadInfo[] = [];
    let leafNode = 0;
    children.forEach((o) => {
      o.isleaf = false;
      let flag = false;
      for (let i = 0; i < originHeads.value.length; i++) {
        let k = originHeads.value[i];

        let idx = k.children.findIndex((j) => {
          return j == o.key || j.key == o.key;
        });
        if (idx >= 0) {
          o.isleaf = true;
          flag = true;
          leafNode += 1;
          k.children.splice(idx, 1, o);
          let obj = headsColumn.find((j) => {
            return j.key == k.key;
          });
          if (!obj) headsColumn.push(k);
          break;
        } else {
          flag = false;
        }
      }
      if (!flag) {
        let obj = headsColumn.find((j) => {
          return j.key == o.key;
        });
        if (!obj) headsColumn.push(o);
      }
    });
    if (leafNode > 0) {
      //继续循环
      getColumns(headsColumn);
    } else {
      headColums.value = headsColumn;
    }
  }
  function filterHeads(children) {
    children.forEach((k, i) => {
      if (typeof k == 'string') {
        children.splice(i, 1);
      } else if (k.children) {
        filterHeads(k.children);
      }
    });
  }

  const add = () => {
    //给各个组件赋默认值
    const pushObj: Recordable = {};
    if (sunFormInfo.value) {
      pushObj[sunFormInfo.value.mainKey!] = [];
    }
    //新增数据钩子
    if (isFunction(props.addBefore)) {
      props.addBefore(formModel, pushObj);
    }

    props.columns.forEach((column, index) => {
      //判断是否为操作菜单  并且设置了默认值
      if ((column.key === 'index' && index === 0) || column.componentType === 'SunForm') return;
      if (column.key !== 'action') {
        if (column.componentType === 'RangePicker' || column.componentType === 'TimeRangePicker') {
          handleSetRangeTimeValue(pushObj, column.dataIndex as string);
        } else if (
          (column.componentType &&
            staticDataComponents.includes(column.componentType) &&
            (column.componentProps as any)?.datasourceType === 'staticData') ||
          (column.componentType &&
            DicDataComponents.includes(column.componentType) &&
            (column.componentProps as any)?.datasourceType === 'dic')
        ) {
          let { defaultSelect } = column.componentProps as any;
          pushObj[column!.dataIndex as string] = defaultSelect;
        } else {
          pushObj[column!.dataIndex as string] = column.defaultValue;
        }
      }
    });
    pushObj.key = data.value.length;
    data.value.push(pushObj);
    subRefreshFieldObj.value.push({});
    emit('change', unref(data));
    emit('update:value', unref(data));
    //新增数据钩子
    if (isFunction(props.addAfter)) {
      props.addAfter(formModel, pushObj);
    }
    pagination.current = Math.ceil(data.value.length / pagination.pageSize);
    emit('add', unref(data));
  };

  const handleTableChange = async (paginationData) => {
    pagination.current = paginationData.current;
    pagination.pageSize = paginationData.pageSize;
    if (!props.useSelectButton && props.preloadType === 'api' && props.apiConfig?.path) {
      let res = await apiConfigFunc(props.apiConfig, isCamelCase, formModel, null, pagination);
      renderSubFormList(res, true);
    }
  };

  const remove = (index, record) => {
    if (props.showPagenation) {
      const realIndex = (pagination.current - 1) * pagination.pageSize + index;
      data.value.splice(realIndex, 1);
      subRefreshFieldObj.value.splice(realIndex, 1);
    } else {
      data.value.splice(index, 1);
      subRefreshFieldObj.value.splice(index, 1);
    }

    emit('change', unref(data));
    emit('update:value', unref(data));
    emit('delete', { tableData: unref(data), removeData: record }); //tableData是全部数据，removeData是当前被删的数据
  };

  const renderSubFormList = async (list, isClear = false) => {
    if (isClear) {
      data.value = [];
      subRefreshFieldObj.value = [];
    }
    list?.forEach((x) => {
      const dataObj = {};
      props.columns?.map((item) => {
        if (!item?.dataIndex) return;
        dataObj[item.dataIndex as string] = item.componentProps?.prestrainField
          ? x[item.componentProps.prestrainField]
          : null;
      });

      data.value.push(dataObj);
      subRefreshFieldObj.value.push({});
    });
    emit('change', unref(data));
    emit('update:value', unref(data));
  };

  watch(
    () => props.preloadType,
    async () => {
      reload();
    },
    {
      immediate: true,
    },
  );
  async function reload() {
    pagination.current = 1;
    if (props.preloadType && !props.useSelectButton) {
      let res;
      if (props.preloadType === 'api' && props.apiConfig?.path) {
        if (props.apiConfig?.apiParams) {
          for (const param of props.apiConfig.apiParams) {
            if (param.key === '1' && param.tableInfo && param.tableInfo.length) {
              for (const query of param.tableInfo) {
                if (query.name == 'size') {
                  if (query.value) pagination.pageSize = query.value;
                }
              }
            }
          }
        }
        res = await apiConfigFunc(props.apiConfig, isCamelCase, formModel, null, pagination);
      }
      if (props.preloadType === 'dic' && props.itemId) {
        res = await getDicDetailList({ itemId: props.itemId });
      }
      renderSubFormList(res, true);
    }
  }
  /**
   * @author: tzx
   * @description: 设置RangeTime的值
   *
   */
  function handleSetRangeTimeValue(values: Recordable, field: string) {
    const startTimeKey = field.split(',')[0];
    const endTimeKey = field.split(',')[1];
    values[startTimeKey] = '';
    values[endTimeKey] = '';

    return values;
  }
  const rules = (column, record, index) => {
    if (column.key === 'index') return;
    const requiredRule = {
      required: getComponentsProps(column, record, index)?.required || false,
      message: `${column.title}是必填项`,
    };
    const rulesList = cloneDeep(getComponentsProps(column, record, index)?.rules);
    if (!rulesList) return [requiredRule];
    rulesList?.map((item) => (item.pattern = eval(item.pattern)));
    return [...rulesList, requiredRule];
  };

  const getComponentsProps = (column, record, index) => {
    let componentProps = column?.componentProps;
    const dataIndex = column?.dataIndex;
    let newIndex = index + (pagination.current - 1) * pagination.pageSize;
    if (!componentProps) return;
    if (isFunction(componentProps)) {
      componentProps =
        componentProps({ updateSchema, formModel, record, newIndex, disableRow }) ?? {};
    } else {
      componentProps = cloneDeep(column?.componentProps);
      if (componentProps['events']) {
        for (const eventKey in componentProps['events']) {
          try {
            const event = new Function(
              'index',
              'schema',
              'formModel',
              'formActionType',
              'subFormColumns',
              'eventData',
              'options',
              `${componentProps['events'][eventKey]}`,
            );
            componentProps['on' + upperFirst(eventKey)] = function (e, opt) {
              event(
                newIndex,
                column,
                formModel,
                { ...props.formApi, refreshAPI, subUpdateSchema: updateSchema },
                changeColumns.value,
                e,
                opt,
              );
            };
          } catch (error) {
            notification.error({
              message: 'Tip',
              description: '触发事件填写有误！',
            });
          }
        }
      }
      const col = changeColumns.value[dataIndex];
      if (col && col[newIndex]?.componentProps) {
        componentProps = cloneDeep(col[newIndex].componentProps);
      }
    }
    if (isBoolean(props.disabled)) {
      componentProps['disabled'] = componentProps['disabled'] || props.disabled;
    }
    if (isBoolean(componentProps['disabled'])) {
      componentProps['disabled'] =
        cacheMap.has(dataIndex) && cacheMap.get(dataIndex)?.includes(newIndex) ? true : false;
    }

    return componentProps as Recordable;
  };
  const refreshAPI = (field: string, index) => {
    if (!field) return;

    if (isNumber(index)) {
      if (unref(subRefreshFieldObj)[index] && unref(subRefreshFieldObj)[index][field]) {
        unref(subRefreshFieldObj)[index][field]++;
      } else {
        unref(subRefreshFieldObj)[index] = {};
        unref(subRefreshFieldObj)[index][field] = 1;
      }
    }
  };
  // const getDisable = (column, index) => {
  //   console.log('getDisable', cacheMap.get(column.dataIndex), column.componentProps.disabled);
  //   return cacheMap.has(column.dataIndex) && cacheMap.get(column.dataIndex)?.includes(index)
  //     ? true
  //     : false;
  // };

  const onExpand = (expanded, record) => {
    if (expanded) {
      expandedRowKeys.value.push(record.key);
    } else {
      if (expandedRowKeys.value.length) {
        expandedRowKeys.value = expandedRowKeys.value.filter((x) => x !== record.key);
      }
    }
  };

  const disableRow = (column: SubFormColumn, index?: number) => {
    let col: any = columnsList.value.find((x) => x.dataIndex == column.dataIndex);
    if (col && index !== undefined) {
      //如果当前字段已经缓存
      if (cacheMap.has(col.dataIndex)) {
        let indexArray = cacheMap.get(col.dataIndex);

        if (column.componentProps.disabled) {
          if (!indexArray) {
            indexArray = [index];
          } else {
            if (!indexArray.includes(index)) {
              indexArray.push(index);
            }
          }
        } else {
          if (indexArray) {
            if (indexArray.findIndex((x) => x === index) > -1) {
              indexArray.splice(
                indexArray.findIndex((x) => x === index),
                1,
              );
            }
          }
        }
      } else {
        if (column.componentProps.disabled) {
          cacheMap.set(col.dataIndex, [index]);
        }
      }
    }
  };

  const updateSchema = (column: SubFormColumn, index?: number) => {
    let col: any = columnsList.value.find((x) => x.dataIndex == column.dataIndex);
    if (col && index !== undefined) {
      //如果当前字段已经缓存
      if (cacheMap.has(col.dataIndex)) {
        let indexArray = cacheMap.get(col.dataIndex);

        if (column.componentProps.disabled) {
          if (!indexArray) {
            indexArray = [index];
          } else {
            indexArray.push(index);
          }
        } else {
          if (indexArray) {
            if (indexArray.findIndex((x) => x === index) > -1) {
              indexArray.splice(
                indexArray.findIndex((x) => x === index),
                1,
              );
            }
          }
        }
      } else {
        if (column.componentProps.disabled) {
          cacheMap.set(col.dataIndex, [index]);
        }
      }
    }
    return col || col?.length ? deepMerge(col, column) : col;
  };
  function isAlphaString1(str) {
    return /^[a-zA-Z]+$/.test(str) ? 10 : 15;
  }
  function updateColum(widths) {
    if (widths) {
      widths.forEach((o: any) => {
        let obj: any = columnsList.value.find((k) => k.key == o.key);
        if (obj) {
          let width = o.resizable ? o.width : o.unit && o.width ? o.width + o.unit : o.width;
          if (width === 0 || width) obj.width = width;
          if (o.minWidth === 0 || o.minWidth) obj.minWidth = o.minWidth;
          if (o.maxWidth === 0 || o.maxWidth) obj.maxWidth = o.maxWidth;
          obj.resizable = o.resizable;
          obj.isEdit = o.isEdit;
          if (o.isEdit) obj.ellipsis = true;
        }
      });
    }
    if (props.buttonList?.length > 0) {
      let w = 30;
      props.buttonList.forEach((o) => {
        if (o.icon) {
          w += 26;
        } else if (o.label) {
          w += String(o.label).length * isAlphaString1(o.label);
        }
      });
      let obj = columnsList.value.find((k) => k.key == 'action');
      if (obj) obj.width = w + 'px';
    }
  }
  function filterColum(column) {
    return column.filter((o) => {
      return (
        o.componentType !== 'SunForm' &&
        (o.key == 'action' ||
          o.key == 'index' ||
          (((isBoolean(o.show) && o.show) || !isBoolean(o.show)) &&
            isBoolean(o.componentProps?.isShow) &&
            o.componentProps?.isShow) ||
          !isBoolean(o.componentProps?.isShow))
      );
    });
  }

  const handleChange = (type, dataIndex, index) => {
    if (type === 'Upload') {
      props.formApi?.validateFields([[props.mainKey, index, dataIndex]]);
    }
  };
  function deleteSelectedData() {
    if (selectedRowsData.value.length <= 0) {
      notification.warning({
        message: t('提示'),
        description: t(`请先选择要删除的数据项`),
      }); //提示消息
      return;
    }
    selectedRowsData.value.forEach((o) => {
      let idx = data.value.findIndex((k) => k.key == o.key);
      if (idx >= 0) {
        data.value.splice(idx, 1);
      }
    });
    selectedRowsData.value = [];
    selectedRowKeys.value = [];
  }
  const exportTable = async () => {
    const fieldList = {};
    data.value.map((item) => {
      for (const k in item) {
        if (!fieldList[k]) {
          fieldList[k] = [];
        }
        fieldList[k].push(item[k]);
      }
    });
    const columnsInfo = columnsList.value.filter((item) => {
      if (item.componentType === 'Input') {
        return !item.componentProps.isSave;
      }
      return item.key !== 'action' && item.key !== 'index';
    });
    const exportValue: Array<string>[] = [[]];
    columnsInfo.map((item) => {
      const requiredSign = '(*)';
      const title = item.componentProps.required ? item.title + requiredSign : item.title;
      if (item.componentType?.includes('RangePicker')) {
        const column = [`${title}开始时间`, `${title}结束时间`];
        exportValue[0].push(...column);
      } else {
        exportValue[0].push(title!);
      }
    });
    if (Object.keys(fieldList).length) {
      for (const col of columnsInfo) {
        const componentProps = col.componentProps;
        const componentType = col.componentType;
        for (const [index, val] of fieldList[col.dataIndex!]?.entries()) {
          let value = isNil(val) ? '' : val;
          if (
            apiComponent.includes(componentType!) ||
            (componentType === 'MultiplePopup' && col.componentProps.popupType === 'associate')
          ) {
            //下拉、联想下拉、单选、联想弹层
            if (componentProps.datasourceType === 'staticData') {
              const info = componentProps.staticOptions.find((option) => option.value === val);
              value = info?.label || val;
            } else if (componentProps.datasourceType === 'api') {
              const options = await apiConfigFunc(
                componentProps.apiConfig,
                isCamelCase,
                formModel,
                index,
              );
              const info = options?.find((option) => option.value === val);
              value = info?.label || val;
            } else if (componentProps.datasourceType === 'dic') {
              const options = await getDicDetailList(componentProps.params);
              const info = options.find((option) => option.value === val);
              value = info?.name || val;
            }
          } else if (
            componentType === 'ApiCheckboxGroup' ||
            (componentType === 'MultiplePopup' && componentProps.popupType === 'multiple')
          ) {
            //多选、多选弹层
            if (val) {
              const valArr = val.split(',');
              if (componentProps.datasourceType === 'staticData') {
                const info = componentProps.staticOptions.filter((option) =>
                  valArr.includes(option.value),
                );
                if (info.length) {
                  const labelArr = info.map((item) => item.label);
                  value = labelArr.toString();
                }
              } else if (componentProps.datasourceType === 'api') {
                const options = await apiConfigFunc(
                  componentProps.apiConfig,
                  isCamelCase,
                  formModel,
                  index,
                );
                const info = options?.filter((option) => valArr.includes(option.value));
                if (info.length) {
                  const labelArr = info.map((item) => item.label);
                  value = labelArr.toString();
                }
              } else if (componentProps.datasourceType === 'dic') {
                const options = await getDicDetailList(componentProps.params);
                const info = options.filter((option) => valArr.includes(option.value));
                if (info.length) {
                  const labelArr = info.map((item) => item.name);
                  value = labelArr.toString();
                }
              }
            }
          } else if (componentType === 'Info') {
            //信息体
            if (componentProps.infoType === 0) {
              //用户
              const userInfo = await getUser(val);
              value = userInfo.name;
            }
            if (componentProps.infoType === 1) {
              //部门
              const dept = await getDepartment(val);
              value = dept.name;
            }
          } else if (componentType === 'User') {
            //人员
            const users = await getUserMulti(val);
            value = users.map((item) => item.name).toString();
          } else if (componentType === 'Dept') {
            //组织架构
            if (val) {
              const dept = await getDepartment(val);
              value = dept.name;
            }
          } else if (componentType === 'MoneyChineseInput') {
            //货币大写
            value = moneyChineseData(val);
          } else if (componentType === 'ApiCascader') {
            //级联
            const options = await apiConfigFunc(
              componentProps.apiConfig,
              isCamelCase,
              formModel,
              index,
            );
            const valArr = val?.split(',');
            if (valArr?.length) {
              const labelArr = getCascaderLabel(options, valArr);
              value =
                componentProps.showFormat === 'all'
                  ? labelArr.join(componentProps.separator)
                  : labelArr[labelArr.length - 1];
            }
          } else if (componentType === 'Area') {
            //行政区域
            const options = await getAreaList({ id: '0' });
            const valArr = val?.split(',');
            if (valArr?.length) {
              const labelArr = await getAreaLabel(options, valArr);
              value = labelArr.join('/');
            }
          } else if (componentType === 'TreeSelectComponent') {
            //树选择
            if (componentProps.treeConfig.id) {
              let formState = await getInfo(componentProps.treeConfig?.id);
              if (formState && formState.config) {
                let config = JSON.parse(formState.config);
                let options = config.staticData;
                let labelKey = 'label';
                let valueKey = 'value';

                if (formState.type == TreeStructureType.API) {
                  labelKey = config.apiData.apiColumns[0].dataIndex;
                  valueKey = config.apiData.apiColumns[1].dataIndex;
                  const res = await apiConfigFunc(
                    config.apiData.apiConfig,
                    isCamelCase,
                    formModel,
                    index,
                  );
                  options = res?.data || [];
                }
                const valArr = val?.split(',');
                const labelArr = [];
                for (const item of valArr) {
                  const valInfo = item?.split('---');
                  getTreeSelectLabel(options, valInfo, labelArr, labelKey, valueKey);
                }
                value = labelArr.toString();
              }
            }
          }
          if (!exportValue[index + 1]) {
            exportValue[index + 1] = [];
          }
          if (componentType?.includes('RangePicker')) {
            //时间范围、日期范围
            exportValue[index + 1].push(...value);
          } else {
            exportValue[index + 1].push(value);
          }
        }
      }
    }
    const dataInfo = XLSX.utils.aoa_to_sheet(exportValue);
    /**设置标题头背景色 */
    for (const key in dataInfo) {
      // 第一行，表头
      if (key.replace(/[^0-9]/gi, '') === '1') {
        dataInfo[key].s = {
          fill: {
            //背景色
            fgColor: {
              rgb: 'C0C0C0',
            },
          },
          font: {
            //字体
            name: '宋体',
            sz: 12,
            bold: true,
          },
          border: {
            //边框
            bottom: {
              style: 'thin',
              color: '#9a9a9a',
            },
            right: {
              style: 'thin',
              color: '#9a9a9a',
            },
          },
          alignment: {
            horizontal: 'center', //水平居中
            vertical: 'center',
          },
        };
      }
    }
    dataInfo['!rows'] = [{ hpx: 25 }];

    // 创建工作簿
    const wb = XLSX.utils.book_new();
    // 将工作表放入工作簿中
    XLSX.utils.book_append_sheet(wb, dataInfo);
    // 生成文件并下载
    XLSX.writeFile(wb, `${props.tableName || '子表导出数据'}.xlsx`);
  };

  const deptId = ref('');
  const importTable = async (excelDataList: ExcelData[]) => {
    const columnsInfo = columnsList.value.filter((item) => item.key !== 'action');
    const tableInfo: any = [];
    for (const [index, item] of excelDataList[0].results?.entries()) {
      const returnItem = {};
      for (let key in item) {
        item[key.replace('(*)', '')] = item[key];
      }
      for (const col of columnsInfo) {
        const componentProps = col.componentProps;
        const componentType = col.componentType;
        const val = item[col.title!];
        let value = val;
        if (!item[col.title!]) {
        } else if (
          apiComponent.includes(componentType!) ||
          (componentType === 'MultiplePopup' && col.componentProps.popupType === 'associate')
        ) {
          //下拉、联想下拉、单选、联想弹层
          if (componentProps.datasourceType === 'staticData') {
            const info = componentProps.staticOptions.find((option) => option.label === val);
            value = info?.value || val;
          } else if (componentProps.datasourceType === 'api') {
            const options = await apiConfigFunc(
              componentProps.apiConfig,
              isCamelCase,
              formModel,
              index,
            );
            const info = options?.find((option) => option.label === val);
            value = info?.value || val;
          } else if (componentProps.datasourceType === 'dic') {
            const options = await getDicDetailList(componentProps.params);
            const info = options.find((option) => option.name === val);
            value = info?.value || val;
          }
        } else if (
          componentType === 'ApiCheckboxGroup' ||
          (componentType === 'MultiplePopup' && componentProps.popupType === 'multiple')
        ) {
          //多选、多选弹层
          const valArr = val.split(',');
          if (componentProps.datasourceType === 'staticData') {
            const info = componentProps.staticOptions.filter((option) =>
              valArr.includes(option.label),
            );
            if (info.length) {
              const labelArr = info.map((item) => item.value);
              value = labelArr.toString();
            }
          } else if (componentProps.datasourceType === 'api') {
            const options = await apiConfigFunc(
              componentProps.apiConfig,
              isCamelCase,
              formModel,
              index,
            );
            const info = options?.filter((option) => valArr.includes(option.label));
            if (info.length) {
              const labelArr = info.map((item) => item.value);
              value = labelArr.toString();
            }
          } else if (componentProps.datasourceType === 'dic') {
            const options = await getDicDetailList(componentProps.params);
            const info = options.filter((option) => valArr.includes(option.name));
            if (info.length) {
              const labelArr = info.map((item) => item.value);
              value = labelArr.toString();
            }
          }
        } else if (componentType === 'Info') {
          //信息体
          if (componentProps.infoType === 0) {
            //用户
            const userInfo = await getAllUserList();
            const user = userInfo.find((item) => item.name === val);
            value = user?.id || val;
          }
          if (componentProps.infoType === 1) {
            //部门
            const dept = await getDepartmentTree();
            getDepartmentVal(dept, val);
            value = deptId.value;
          }
        } else if (componentType === 'User') {
          //人员
          const userInfo = await getAllUserList();
          const userNameArr = val.split(',');
          const users = userInfo
            .filter((item) => userNameArr.includes(item.name))
            .map((item) => item.id);
          value = users.toString();
        } else if (componentType === 'Dept') {
          //组织架构
          const dept = await getDepartmentTree();
          getDepartmentVal(dept, val);
          value = deptId.value;
        } else if (componentType === 'MoneyChineseInput') {
          //货币大写
          const valArr = val.split('.');
          if (valArr.length > 1) {
            const decimals = valArr[1].substr(0, componentProps.decimals);
            value = `${valArr[0]}.${decimals}`;
          } else {
            value = val;
          }
        } else if (componentType === 'ApiCascader') {
          //级联
          const options = await apiConfigFunc(
            componentProps.apiConfig,
            isCamelCase,
            formModel,
            index,
          );
          const labelArr = val?.split('/');
          if (labelArr?.length) {
            const valueArr = getCascaderVal(options, labelArr);
            value =
              componentProps.showFormat === 'all'
                ? valueArr.toString()
                : valueArr[valueArr.length - 1];
          }
        } else if (componentType === 'Area') {
          //行政区域
          const options = await getAreaList({ id: '0' });
          const labelArr = val?.split('/');
          if (labelArr?.length) {
            const valueArr = await getAreaVal(options, labelArr);
            value = valueArr.toString();
          }
        } else if (componentType === 'TreeSelectComponent') {
          //树选择
          if (componentProps.treeConfig.id) {
            let formState = await getInfo(componentProps.treeConfig?.id);
            let config = JSON.parse(formState.config);
            let options = config.staticData;
            if (formState.type == TreeStructureType.API) {
              const res = await apiConfigFunc(
                config.apiData.apiConfig,
                isCamelCase,
                formModel,
                index,
              );
              options = res?.data || [];
            }
            const valueArr: string[] = [];
            if (val) {
              const arr = val.split(',');
              arr.forEach((item) => {
                valueArr.push(getTreeSelectVal(options, item).reverse().join('---') as string);
              });
              value = valueArr.toString();
            }
          }
        }
        if (componentType?.includes('RangePicker')) {
          //时间范围、日期范围
          const rangeArr = col.dataIndex!.split(',');
          returnItem[rangeArr[0]] = item[col.title + '开始时间'];
          returnItem[rangeArr[1]] = item[col.title + '结束时间'];
        } else {
          returnItem[col.dataIndex!] = value;
        }
      }
      tableInfo.push(returnItem);
    }
    data.value.push(...tableInfo);
    emit('change', unref(data));
    emit('update:value', unref(data));
  };

  const getDepartmentVal = (dept, label) => {
    for (let item of dept) {
      if (item.name === label) {
        deptId.value = item.id;
        return false;
      } else if (item.children?.length) {
        getDepartmentVal(item.children, label);
      }
    }
  };

  const getCascaderLabel = (options, valArr, level = 0, labelArr: string[] = []) => {
    const info = options?.find((option) => option.value === valArr[level]);
    labelArr.push(info?.label);
    if (info.children && info.children.length) {
      getCascaderLabel(info.children, valArr, level + 1, labelArr);
    }
    return labelArr;
  };

  const getCascaderVal = (options, labelArr, level = 0, valueArr: string[] = []) => {
    const info = options?.find((option) => option.label === labelArr[level]);
    valueArr.push(info?.value);
    if (info?.children && info.children.length) {
      getCascaderVal(info.children, labelArr, level + 1, valueArr);
    }
    return valueArr;
  };

  const getTreeSelectLabel = (options, valArr, labelArr, labelKey, valueKey, level = 0) => {
    const info = options?.find((option) => option[valueKey] === valArr[level]);

    if (level === valArr.length - 1 && info) {
      labelArr.push(info[labelKey]);
    } else if (level < valArr.length - 1 && info.children && info.children.length) {
      getTreeSelectLabel(info.children, valArr, labelArr, labelKey, valueKey, level + 1);
    }
    return labelArr;
  };

  const getTreeSelectVal = (options, label) => {
    for (const item of options) {
      if (item.label === label) return [item.label];
      if (item.children) {
        let value = getTreeSelectVal(item.children, label);
        if (value !== undefined) return value.concat(item.label);
      }
    }
  };

  const getAreaLabel = async (options, valArr, level = 0, labelArr: string[] = []) => {
    for (const item of options) {
      if (item.id === valArr[level]) {
        labelArr.push(item?.name);
        if (level < valArr.length - 1) {
          const info = await getAreaList({ id: valArr[level] });
          await getAreaLabel(info, valArr, level + 1, labelArr);
        }
        break;
      }
    }
    return labelArr;
  };

  const getAreaVal = async (options, labelArr, level = 0, valueArr: string[] = []) => {
    for (const item of options) {
      if (item.name === labelArr[level]) {
        valueArr.push(item?.id);
        if (level < labelArr.length - 1) {
          const info = await getAreaList({ id: item.id });
          await getAreaVal(info, labelArr, level + 1, valueArr);
        }
        break;
      }
    }
    return valueArr;
  };

  const getColumnTotal = (dataIndex) => {
    const numArr = data.value.map((x) => x[dataIndex as string] || 0);
    if (numArr?.length) {
      return numArr.reduce((prev, cur) => calculator(`(${prev}+${cur})`));
    }
    return 0;
  };
  function getIsShow(schema): boolean {
    const { componentProps, show } = schema as any;
    let isShow = true;
    if (isBoolean(componentProps?.isShow)) {
      isShow = componentProps?.isShow;
    }
    if (isBoolean(show)) {
      isShow = show;
    }

    return isShow;
  }

  function handleColumnChange(v) {
    columnsList.value = filterColum(v);
    if (!formId) return;
    let obj = {};
    if (!obj[userStore.getUserInfo.id]) obj[userStore.getUserInfo.id] = {};
    if (!obj[userStore.getUserInfo.id][formId.value])
      obj[userStore.getUserInfo.id][formId.value] = {};
    obj[userStore.getUserInfo.id][formId.value][props.mainKey] = columnsList.value;
    localStorage.setItem('tableColumnShowSetting', JSON.stringify(obj));
  }

  function customClick(executeButton, record?, index?) {
    curRecord.value = index;
    curButtonModalConfig.value = executeButton.modal;
    let obj = {
      selectedRows: selectedRowsData.value,
      tableDatas: data.value,
      curRow: record,
      curIndex: index,
      formApi,
    };
    executeCurFormEvent(executeButton.event, formModel, isCamelCase, obj);
  }
  function showModal(column, record, index) {
    curRecord.value = index;
    curButtonModalConfig.value = { ...column.componentProps, title: column.title };
    if (column.componentProps.events && column.componentProps.events.click) {
      if (!column.componentProps.events.click.includes('formActionType.openModal')) {
        customOpenModal(record);
      }
      let obj = {
        selectedRows: selectedRowsData.value,
        tableDatas: data.value,
        curRow: record,
        curIndex: index,
        formApi,
      };
      executeCurFormEvent(
        [
          {
            operateType: ExecuteType.JS,
            operateConfig: { js: column.componentProps.events.click },
          },
        ],
        formModel,
        isCamelCase,
        obj,
      );
    } else {
      customOpenModal(record);
    }
  }
  function getSelectedRows() {
    return selectedRowsData.value;
  }
  const customOpenModal = (record) => {
    if (record && curButtonModalConfig.value?.bindModal) {
      openModal(true, { isUpdate: true, record, modal: curButtonModalConfig.value });
    }
  };
  function handleConfirm(type) {
    let obj = {
      selectedRows: selectedRowsData.value,
      tableDatas: data.value,
      curRow: data.value[curRecord.value],
      curIndex: curRecord.value,
      formApi,
    };
    executeCurFormEvent(
      [
        {
          operateType: ExecuteType.JS,
          operateConfig: { js: curButtonModalConfig.value[type] },
        },
      ],
      formModel,
      isCamelCase,
      obj,
    );
  }
  // eslint-disable-next-line vue/no-dupe-keys
  const formApi = { openModal: customOpenModal, reload };
  defineExpose({
    getSelectedRows,
  });
</script>
<style lang="less" scoped>
  :deep(.ant-table-cell) {
    padding: 8px 0;

    .ant-form-item {
      margin-bottom: 0;
    }
  }

  :deep(.ant-table .ant-table-thead tr th) {
    padding: 11px;
  }

  :deep(.ant-input-number),
  :deep(.ant-input-affix-wrapper),
  :deep(.ant-input),
  :deep(.ant-select-selector),
  :deep(.ant-picker) {
    border: 0;
    box-shadow: none !important;
  }

  :deep(.anticon) {
    padding-bottom: 0 !important;
  }

  :deep(.ant-table-cell-fix-right) {
    text-align: center;
    width: 60px;
  }

  :deep(.ant-radio-group),
  :deep(.ant-checkbox-group),
  :deep(.ant-rate),
  :deep(.ant-upload),
  :deep(.ant-form-item-explain-error) {
    padding: 0 11px;
  }

  :deep(.ant-switch),
  :deep(input[type='color']) {
    margin: 0 11px;
  }

  :deep(.ant-table.ant-table-bordered > .ant-table-container) {
    border-left: v-bind('bordershowtype[3] ? formborderwidth: 0') solid v-bind(bordercolor);

    & > .ant-table-content > table {
      border-top: v-bind('bordershowtype[0] ? formborderwidth: 0') solid v-bind(bordercolor);

      & > tbody > tr > td > .ant-table-expanded-row-fixed::after {
        border-right: 0;
      }

      & > thead > tr > th:last-child,
      & > tbody > tr > td:last-child,
      & > tfoot > tr > td:last-child {
        border-right: v-bind('bordershowtype[1] ? formborderwidth: 0') solid v-bind(bordercolor);
      }
    }
  }

  :deep(.ant-table.ant-table-bordered) {
    .ant-table-tbody,
    .ant-table-summary {
      > tr:last-child > td {
        border-bottom: v-bind('bordershowtype[2] ? formborderwidth: 0') solid v-bind(bordercolor);
      }
    }
  }

  :deep(.ant-table-tbody > tr:last-child > td) {
    border-bottom: none;
  }

  .select-btn {
    margin-bottom: 8px;

    :deep(.ant-upload) {
      padding: 0;
    }
  }

  .resize-handle {
    width: 100%;
    height: 1px;
    right: 0;
    bottom: 0;
    cursor: row-resize;
    border-top: 1px solid #1c8dff;
    position: absolute;
    opacity: 0;
  }

  tr:hover {
    .resize-handle {
      opacity: 1;
    }
  }
</style>
