From 436b52186129e60ba72c20e43d2845bc3f899901 Mon Sep 17 00:00:00 2001
From: Ben Lin <maobin001@msn.com>
Date: 星期四, 22 八月 2024 11:16:56 +0800
Subject: [PATCH] 取消暂停svg更新

---
 src/components/Table/src/components/settings/ColumnSetting.vue |  838 ++++++++++++++++++++++++++++++++++++-----------------------
 1 files changed, 505 insertions(+), 333 deletions(-)

diff --git a/src/components/Table/src/components/settings/ColumnSetting.vue b/src/components/Table/src/components/settings/ColumnSetting.vue
index e1424ff..1a66513 100644
--- a/src/components/Table/src/components/settings/ColumnSetting.vue
+++ b/src/components/Table/src/components/settings/ColumnSetting.vue
@@ -6,33 +6,33 @@
     <Popover
       placement="bottomLeft"
       trigger="click"
-      @visible-change="handleVisibleChange"
-      :overlayClassName="`${prefixCls}__cloumn-list`"
+      @open-change="onOpenChange"
+      :overlayClassName="`${prefixCls}__column-list`"
       :getPopupContainer="getPopupContainer"
     >
       <template #title>
         <div :class="`${prefixCls}__popover-title`">
           <Checkbox
             :indeterminate="indeterminate"
-            v-model:checked="checkAll"
-            @change="onCheckAllChange"
+            v-model:checked="isColumnAllSelected"
+            @change="onColumnAllSelectChange"
           >
             {{ t('component.table.settingColumnShow') }}
           </Checkbox>
 
-          <Checkbox v-model:checked="checkIndex" @change="handleIndexCheckChange">
+          <Checkbox v-model:checked="isIndexColumnShow" @change="onIndexColumnShowChange">
             {{ t('component.table.settingIndexColumnShow') }}
           </Checkbox>
-
+          <!-- 璁剧疆浜� rowSelection 鎵嶅嚭鐜� -->
           <Checkbox
-            v-model:checked="checkSelect"
-            @change="handleSelectCheckChange"
-            :disabled="!defaultRowSelection"
+            v-model:checked="isRowSelectionShow"
+            @change="onRowSelectionShowChange"
+            v-if="defaultIsRowSelectionShow"
           >
             {{ t('component.table.settingSelectColumnShow') }}
           </Checkbox>
 
-          <a-button size="small" type="link" @click="reset">
+          <a-button size="small" type="link" @click="onReset">
             {{ t('common.resetText') }}
           </a-button>
         </div>
@@ -40,12 +40,12 @@
 
       <template #content>
         <ScrollContainer>
-          <CheckboxGroup v-model:value="checkedList" @change="onChange" ref="columnListRef">
-            <template v-for="item in plainOptions" :key="item.value">
-              <div :class="`${prefixCls}__check-item`" v-if="!('ifShow' in item && !item.ifShow)">
+          <Checkbox.Group v-model:value="columnCheckedOptions" ref="columnOptionsRef">
+            <template v-for="opt in columnOptions" :key="opt.value">
+              <div :class="`${prefixCls}__check-item`" :data-no="opt.value">
                 <DragOutlined class="table-column-drag-icon" />
-                <Checkbox :value="item.value">
-                  {{ item.label }}
+                <Checkbox :value="opt.value">
+                  {{ opt.label }}
                 </Checkbox>
 
                 <Tooltip
@@ -61,11 +61,11 @@
                     :class="[
                       `${prefixCls}__fixed-left`,
                       {
-                        active: item.fixed === 'left',
-                        disabled: !checkedList.includes(item.value),
+                        active: opt.fixed === 'left',
+                        disabled: opt.value ? !columnCheckedOptions.includes(opt.value) : true,
                       },
                     ]"
-                    @click="handleColumnFixed(item, 'left')"
+                    @click="onColumnFixedChange(opt, 'left')"
                   />
                 </Tooltip>
                 <Divider type="vertical" />
@@ -82,359 +82,530 @@
                     :class="[
                       `${prefixCls}__fixed-right`,
                       {
-                        active: item.fixed === 'right',
-                        disabled: !checkedList.includes(item.value),
+                        active: opt.fixed === 'right',
+                        disabled: opt.value ? !columnCheckedOptions.includes(opt.value) : true,
                       },
                     ]"
-                    @click="handleColumnFixed(item, 'right')"
+                    @click="onColumnFixedChange(opt, 'right')"
                   />
                 </Tooltip>
               </div>
             </template>
-          </CheckboxGroup>
+          </Checkbox.Group>
         </ScrollContainer>
       </template>
       <SettingOutlined />
     </Popover>
   </Tooltip>
 </template>
-<script lang="ts">
-  import type { BasicColumn, BasicTableProps, ColumnChangeParam } from '../../types/table';
-  import {
-    defineComponent,
-    ref,
-    reactive,
-    toRefs,
-    watchEffect,
-    nextTick,
-    unref,
-    computed,
-  } from 'vue';
+<script lang="ts" setup>
+  import type { BasicColumn, ColumnOptionsType, ColumnChangeParam } from '../../types/table';
+  import { ref, nextTick, unref, computed, useAttrs, watch, onMounted } from 'vue';
   import { Tooltip, Popover, Checkbox, Divider } from 'ant-design-vue';
   import type { CheckboxChangeEvent } from 'ant-design-vue/lib/checkbox/interface';
   import { SettingOutlined, DragOutlined } from '@ant-design/icons-vue';
   import Icon from '@/components/Icon/Icon.vue';
-  import { ScrollContainer } from '/@/components/Container';
-  import { useI18n } from '/@/hooks/web/useI18n';
+  import { ScrollContainer } from '@/components/Container';
+  import { useI18n } from '@/hooks/web/useI18n';
   import { useTableContext } from '../../hooks/useTableContext';
-  import { useDesign } from '/@/hooks/web/useDesign';
-  // import { useSortable } from '/@/hooks/web/useSortable';
-  import { isFunction, isNullAndUnDef } from '/@/utils/is';
-  import { getPopupContainer as getParentContainer } from '/@/utils';
+  import { useDesign } from '@/hooks/web/useDesign';
+  import { isFunction, isNil } from '@/utils/is';
+  import { getPopupContainer as getParentContainer } from '@/utils';
   import { cloneDeep, omit } from 'lodash-es';
   import Sortablejs from 'sortablejs';
-  import type Sortable from 'sortablejs';
+  import { INDEX_COLUMN_FLAG } from '@/components/Table/src/const';
 
-  interface State {
-    checkAll: boolean;
-    isInit?: boolean;
-    checkedList: string[];
-    defaultCheckList: string[];
-  }
+  // 鍒楄〃璁剧疆缂撳瓨
+  import { useTableSettingStore } from '@/store/modules/tableSetting';
+  import { useRoute } from 'vue-router';
+  import { TableRowSelection } from '@/components/Table/src/types/table';
 
-  interface Options {
-    label: string;
-    value: string;
-    fixed?: boolean | 'left' | 'right';
-  }
+  const tableSettingStore = useTableSettingStore();
 
-  export default defineComponent({
-    name: 'ColumnSetting',
-    components: {
-      SettingOutlined,
-      Popover,
-      Tooltip,
-      Checkbox,
-      CheckboxGroup: Checkbox.Group,
-      DragOutlined,
-      ScrollContainer,
-      Divider,
-      Icon,
+  defineOptions({ name: 'ColumnSetting' });
+  const emit = defineEmits(['columns-change']);
+
+  const route = useRoute();
+
+  const { t } = useI18n();
+  const { prefixCls } = useDesign('basic-column-setting');
+
+  const attrs = useAttrs();
+  const table = useTableContext();
+
+  const props = withDefaults(
+    defineProps<{
+      /**
+       * 鏄惁缂撳瓨鍒楃殑璁剧疆
+       */
+      cache?: boolean;
+    }>(),
+    {
+      cache: () => false,
     },
-    emits: ['columns-change'],
+  );
 
-    setup(_, { emit, attrs }) {
-      const { t } = useI18n();
-      const table = useTableContext();
+  const getPopupContainer = () => {
+    return isFunction(attrs.getPopupContainer) ? attrs.getPopupContainer() : getParentContainer();
+  };
 
-      const defaultRowSelection = omit(table.getRowSelection(), 'selectedRowKeys');
-      let inited = false;
-      // 鏄惁褰撳墠鐨剆etColums瑙﹀彂鐨�
-      let isSetColumnsFromThis = false;
-      // 鏄惁褰撳墠缁勪欢瑙﹀彂鐨剆etProps
-      let isSetPropsFromThis = false;
+  // 榛樿鍊�
+  let defaultIsIndexColumnShow: boolean = false;
+  let defaultIsRowSelectionShow: boolean = false;
+  let defaultRowSelection: TableRowSelection<Recordable<any>>;
+  let defaultColumnOptions: ColumnOptionsType[] = [];
 
-      const cachePlainOptions = ref<Options[]>([]);
-      const plainOptions = ref<Options[] | any>([]);
+  // 鏄惁宸茬粡浠庣紦瀛樻仮澶�
+  let isRestored = false;
+  let isInnerChange = false;
 
-      const plainSortOptions = ref<Options[]>([]);
+  // 鍒楀彲閫夐」
+  const columnOptions = ref<ColumnOptionsType[]>([]);
+  const columnOptionsRef = ref(null);
+  // 宸查�夊垪
+  const columnCheckedOptions = ref<string[]>([]);
+  // 宸查�夊彉鍖�
+  watch(columnCheckedOptions, () => {
+    // 鎭㈠缂撳瓨鍚庣敓鏁�
+    if (isRestored) {
+      // 鏄剧ず
+      columnOptions.value
+        .filter((o) => columnCheckedOptions.value.includes(o.value))
+        .forEach((o) => {
+          o.column.defaultHidden = false;
+        });
+      // 闅愯棌
+      columnOptions.value
+        .filter((o) => !columnCheckedOptions.value.includes(o.value))
+        .forEach((o) => {
+          o.column.defaultHidden = true;
+          o.fixed = undefined;
+        });
+      // 浠� 鍒楀彲閫夐」 鏇存柊 鍏ㄩ�夌姸鎬�
+      isColumnAllSelectedUpdate();
 
-      const columnListRef = ref(null);
+      // 鍒楄〃鍒楁洿鏂�
+      tableColumnsUpdate();
+      // 鏇存柊鍒楃紦瀛�
+      props.cache && columnOptionsSave();
+    }
+  });
 
-      const state = reactive<State>({
-        checkAll: true,
-        checkedList: [],
-        defaultCheckList: [],
-      });
-      /** 缂撳瓨鍒濆鍖杙rops */
-      let cacheTableProps: Partial<BasicTableProps<any>> = {};
-      const checkIndex = ref(false);
-      const checkSelect = ref(false);
+  // 鍏ㄩ��
+  const isColumnAllSelected = ref<boolean>(false);
+  const onColumnAllSelectChange = () => {
+    if (columnCheckedOptions.value.length < columnOptions.value.length) {
+      columnCheckedOptions.value = columnOptions.value.map((o) => o.value);
+    } else {
+      columnCheckedOptions.value = [];
+    }
+  };
 
-      const { prefixCls } = useDesign('basic-column-setting');
+  // 鍗婇�夌姸鎬�
+  const indeterminate = computed(() => {
+    return (
+      columnCheckedOptions.value.length > 0 &&
+      columnCheckedOptions.value.length < columnOptions.value.length
+    );
+  });
 
-      const getValues = computed(() => {
-        return unref(table?.getBindValues) || {};
-      });
+  // 鏄惁鏄剧ず搴忓彿鍒�
+  const isIndexColumnShow = ref<boolean>(false);
+  // 搴忓彿鍒楁洿鏂�
+  const onIndexColumnShowChange = (e: CheckboxChangeEvent) => {
+    // 鏇存柊 showIndexColumn
+    showIndexColumnUpdate(e.target.checked);
+    // 鏇存柊 showIndexColumn 缂撳瓨
+    props.cache &&
+      typeof route.name === 'string' &&
+      tableSettingStore.setShowIndexColumn(route.name, e.target.checked);
+  };
 
-      watchEffect(() => {
-        const columns = table.getColumns();
-        setTimeout(() => {
-          if (isSetColumnsFromThis) {
-            isSetColumnsFromThis = false;
-          } else if (columns.length) {
-            init();
+  // 鏄惁鏄剧ず閫夋嫨鍒�
+  const isRowSelectionShow = ref<boolean>(false);
+  // 閫夋嫨鍒楁洿鏂�
+  const onRowSelectionShowChange = (e: CheckboxChangeEvent) => {
+    // 鏇存柊 showRowSelection
+    showRowSelectionUpdate(e.target.checked);
+    // 鏇存柊 showRowSelection 缂撳瓨
+    props.cache &&
+      typeof route.name === 'string' &&
+      tableSettingStore.setShowRowSelection(route.name, e.target.checked);
+  };
+
+  // 鏇存柊鍒楃紦瀛�
+  const columnOptionsSave = () => {
+    if (typeof route.name === 'string') {
+      // 鎸夎矾鐢� name 浣滀负缂撳瓨鐨刱ey锛堣嫢涓�涓矾鐢卞唴瀛樺湪澶氫釜琛ㄦ牸锛岄渶鑷璋冩暣缂撳瓨key鏉ユ簮锛�
+      tableSettingStore.setColumns(route.name, columnOptions.value);
+    }
+  };
+
+  // 閲嶇疆
+  const onReset = () => {
+    // 閲嶇疆榛樿鍊�
+    isIndexColumnShow.value = defaultIsIndexColumnShow;
+    // 搴忓彿鍒楁洿鏂�
+    onIndexColumnShowChange({
+      target: { checked: defaultIsIndexColumnShow },
+    } as CheckboxChangeEvent);
+    // 閲嶇疆榛樿鍊�
+    isRowSelectionShow.value = defaultIsRowSelectionShow;
+    // 閫夋嫨鍒楁洿鏂�
+    onRowSelectionShowChange({
+      target: { checked: defaultIsRowSelectionShow },
+    } as CheckboxChangeEvent);
+    // 閲嶇疆榛樿鍊�
+    columnOptions.value = cloneDeep(defaultColumnOptions);
+    // 鏇存柊琛ㄥ崟鐘舵��
+    formUpdate();
+  };
+
+  // 璁剧疆鍒楃殑 fixed
+  const onColumnFixedChange = (opt: ColumnOptionsType, type: 'left' | 'right') => {
+    if (type === 'left') {
+      if (!opt.fixed || opt.fixed === 'right') {
+        opt.fixed = 'left';
+      } else {
+        opt.fixed = undefined;
+      }
+    } else if (type === 'right') {
+      if (!opt.fixed || opt.fixed === 'left') {
+        opt.fixed = 'right';
+      } else {
+        opt.fixed = undefined;
+      }
+    }
+
+    // 鍒楄〃鍒楁洿鏂�
+    tableColumnsUpdate();
+    // 鏇存柊鍒楃紦瀛�
+    props.cache && columnOptionsSave();
+  };
+
+  // 娌跨敤閫昏緫
+  const sortableFix = async () => {
+    // Sortablejs瀛樺湪bug锛屼笉鐭ラ亾鍦ㄥ摢涓楠や腑浼氬悜el append浜嗕竴涓猚hildNode锛屽洜姝よ繖閲屽厛娓呯┖childNode
+    // 鏈夊彲鑳藉鐜颁笂杩伴棶棰樼殑鎿嶄綔锛氭嫋鎷戒竴涓厓绱狅紝蹇�熺殑涓婁笅绉诲姩锛屾渶鍚庢斁鍒版渶鍚庣殑浣嶇疆涓澗鎵�
+    if (columnOptionsRef.value) {
+      const el = (columnOptionsRef.value as InstanceType<typeof Checkbox.Group>).$el;
+      Array.from(el.children).forEach((item) => el.removeChild(item));
+    }
+    await nextTick();
+  };
+
+  // 鍒楁槸鍚︽樉绀洪�昏緫
+  const columnIfShow = (column?: Partial<Omit<BasicColumn, 'children'>>) => {
+    if (column) {
+      if ('ifShow' in column) {
+        if (typeof column.ifShow === 'boolean') {
+          return column.ifShow;
+        } else if (column.ifShow) {
+          return column.ifShow(column);
+        }
+      }
+      return true;
+    }
+    return false;
+  };
+
+  // 鑾峰彇鏁版嵁鍒�
+  const getTableColumns = () => {
+    return table
+      .getColumns({ ignoreIndex: true, ignoreAction: true })
+      .filter((col) => columnIfShow(col));
+  };
+
+  // 璁剧疆鍒楄〃鍒�
+  const tableColumnsSet = (columns: BasicColumn[]) => {
+    isInnerChange = true;
+    table?.setColumns(columns);
+
+    // 娌跨敤閫昏緫
+    const columnChangeParams: ColumnChangeParam[] = columns.map((col) => ({
+      dataIndex: col.dataIndex ? col.dataIndex.toString() : '',
+      fixed: col.fixed,
+      visible: !col.defaultHidden,
+    }));
+    emit('columns-change', columnChangeParams);
+  };
+
+  // 鍒楄〃鍒楁洿鏂�
+  const tableColumnsUpdate = () => {
+    // 鑰冭檻浜嗘墍鏈夊垪
+    const columns = cloneDeep(table.getColumns());
+
+    // 浠庡乏 fixed 鏈�涓�鍒楀紑濮嬫帓搴忥紙闄や簡 搴忓彿鍒楋級
+    let count = columns.filter(
+      (o) => o.flag !== INDEX_COLUMN_FLAG && (o.fixed === 'left' || o.fixed === true),
+    ).length;
+
+    // 搴忓彿鍒楁彁鍓�
+    if (isIndexColumnShow.value) {
+      count++;
+    }
+
+    // 鎸� columnOptions 鐨勬帓搴� 璋冩暣 table.getColumns() 鐨勯『搴忓拰鍊�
+    for (const opt of columnOptions.value) {
+      const colIdx = columns.findIndex((o) => o.dataIndex === opt.value);
+      //
+      if (colIdx > -1) {
+        const target = columns[colIdx];
+        target.defaultHidden = opt.column?.defaultHidden;
+        target.fixed = opt.fixed;
+        columns.splice(colIdx, 1);
+        columns.splice(count++, 0, target); // 閫掑鎻掑叆
+      }
+    }
+
+    // 鏄惁瀛樺湪 action
+    const actionIndex = columns.findIndex((o) => o.dataIndex === 'action');
+    if (actionIndex > -1) {
+      const actionCol = columns.splice(actionIndex, 1);
+      columns.push(actionCol[0]);
+    }
+
+    // 璁剧疆鍒楄〃鍒�
+    tableColumnsSet(columns);
+  };
+
+  // 鎵撳紑娴獥
+  const onOpenChange = async () => {
+    await nextTick();
+
+    if (columnOptionsRef.value) {
+      // 娉ㄥ唽鎺掑簭瀹炰緥
+      const el = (columnOptionsRef.value as InstanceType<typeof Checkbox.Group>).$el;
+      Sortablejs.create(unref(el), {
+        animation: 500,
+        delay: 400,
+        delayOnTouchOnly: true,
+        handle: '.table-column-drag-icon ',
+        dataIdAttr: 'data-no',
+        onEnd: (evt) => {
+          const { oldIndex, newIndex } = evt;
+          if (isNil(oldIndex) || isNil(newIndex) || oldIndex === newIndex) {
+            return;
           }
-        }, 0);
-      });
 
-      watchEffect(() => {
-        const values = unref(getValues);
-        if (isSetPropsFromThis) {
-          isSetPropsFromThis = false;
-        } else {
-          cacheTableProps = cloneDeep(values);
-        }
-        checkIndex.value = !!values.showIndexColumn;
-        checkSelect.value = !!values.rowSelection;
-      });
+          const options = cloneDeep(columnOptions.value);
 
-      function getColumns() {
-        const ret: Options[] = [];
-        table.getColumns({ ignoreIndex: true, ignoreAction: true }).forEach((item) => {
-          ret.push({
-            label: (item.title as string) || (item.customTitle as string),
-            value: (item.dataIndex || item.title) as string,
-            ...item,
-          });
-        });
-        return ret;
-      }
-
-      async function init(isReset = false) {
-        // Sortablejs瀛樺湪bug锛屼笉鐭ラ亾鍦ㄥ摢涓楠や腑浼氬悜el append浜嗕竴涓猚hildNode锛屽洜姝よ繖閲屽厛娓呯┖childNode
-        // 鏈夊彲鑳藉鐜颁笂杩伴棶棰樼殑鎿嶄綔锛氭嫋鎷戒竴涓厓绱狅紝蹇�熺殑涓婁笅绉诲姩锛屾渶鍚庢斁鍒版渶鍚庣殑浣嶇疆涓澗鎵�
-        plainOptions.value = [];
-        const columnListEl = unref(columnListRef);
-        if (columnListEl && (columnListEl as any).$el) {
-          const el = (columnListEl as any).$el as Element;
-          Array.from(el.children).forEach((item) => el.removeChild(item));
-        }
-        await nextTick();
-        const columns = isReset ? cloneDeep(cachePlainOptions.value) : getColumns();
-
-        const checkList = table
-          .getColumns({ ignoreAction: true, ignoreIndex: true })
-          .map((item) => {
-            if (item.defaultHidden) {
-              return '';
-            }
-            return item.dataIndex || item.title;
-          })
-          .filter(Boolean) as string[];
-        plainOptions.value = columns;
-        plainSortOptions.value = columns;
-        // 鏇存柊缂撳瓨閰嶇疆
-        table.setCacheColumns?.(columns);
-        !isReset && (cachePlainOptions.value = cloneDeep(columns));
-        state.defaultCheckList = checkList;
-        state.checkedList = checkList;
-        // 鏄惁鍒楀睍绀哄叏閫�
-        state.checkAll = checkList.length === columns.length;
-        inited = false;
-        handleVisibleChange();
-      }
-
-      // checkAll change
-      function onCheckAllChange(e: CheckboxChangeEvent) {
-        const checkList = plainSortOptions.value.map((item) => item.value);
-        plainSortOptions.value.forEach(
-          (item) => ((item as BasicColumn).defaultHidden = !e.target.checked),
-        );
-        if (e.target.checked) {
-          state.checkedList = checkList;
-          setColumns(checkList);
-        } else {
-          state.checkedList = [];
-          setColumns([]);
-        }
-      }
-
-      const indeterminate = computed(() => {
-        const len = plainOptions.value.length;
-        let checkedLen = state.checkedList.length;
-        // unref(checkIndex) && checkedLen--;
-        return checkedLen > 0 && checkedLen < len;
-      });
-
-      // Trigger when check/uncheck a column
-      function onChange(checkedList: string[]) {
-        const len = plainSortOptions.value.length;
-        state.checkAll = checkedList.length === len;
-        const sortList = unref(plainSortOptions).map((item) => item.value);
-        checkedList.sort((prev, next) => {
-          return sortList.indexOf(prev) - sortList.indexOf(next);
-        });
-        unref(plainSortOptions).forEach((item) => {
-          (item as BasicColumn).defaultHidden = !checkedList.includes(item.value);
-        });
-        setColumns(checkedList);
-      }
-
-      let sortable: Sortable;
-      let sortableOrder: string[] = [];
-      // reset columns
-      function reset() {
-        setColumns(cachePlainOptions.value);
-        init(true);
-        checkIndex.value = !!cacheTableProps.showIndexColumn;
-        checkSelect.value = !!cacheTableProps.rowSelection;
-        table.setProps({
-          showIndexColumn: checkIndex.value,
-          rowSelection: checkSelect.value ? defaultRowSelection : undefined,
-        });
-        sortable.sort(sortableOrder);
-      }
-
-      // Open the pop-up window for drag and drop initialization
-      function handleVisibleChange() {
-        if (inited) return;
-        nextTick(() => {
-          const columnListEl = unref(columnListRef);
-          if (!columnListEl) return;
-          const el = (columnListEl as any).$el;
-          if (!el) return;
-          // Drag and drop sort
-          sortable = Sortablejs.create(unref(el), {
-            animation: 500,
-            delay: 400,
-            delayOnTouchOnly: true,
-            handle: '.table-column-drag-icon ',
-            onEnd: (evt) => {
-              const { oldIndex, newIndex } = evt;
-              if (isNullAndUnDef(oldIndex) || isNullAndUnDef(newIndex) || oldIndex === newIndex) {
-                return;
-              }
-              // Sort column
-              const columns = cloneDeep(plainSortOptions.value);
-
-              if (oldIndex > newIndex) {
-                columns.splice(newIndex, 0, columns[oldIndex]);
-                columns.splice(oldIndex + 1, 1);
-              } else {
-                columns.splice(newIndex + 1, 0, columns[oldIndex]);
-                columns.splice(oldIndex, 1);
-              }
-
-              plainSortOptions.value = columns;
-              setColumns(columns.filter((item) => state.checkedList.includes(item.value)));
-            },
-          });
-          // 璁板綍鍘熷order 搴忓垪
-          sortableOrder = sortable.toArray();
-          inited = true;
-        });
-      }
-
-      // Control whether the serial number column is displayed
-      function handleIndexCheckChange(e: CheckboxChangeEvent) {
-        isSetPropsFromThis = true;
-        isSetColumnsFromThis = true;
-        table.setProps({
-          showIndexColumn: e.target.checked,
-        });
-      }
-
-      // Control whether the check box is displayed
-      function handleSelectCheckChange(e: CheckboxChangeEvent) {
-        isSetPropsFromThis = true;
-        isSetColumnsFromThis = true;
-        table.setProps({
-          rowSelection: e.target.checked ? defaultRowSelection : undefined,
-        });
-      }
-
-      function handleColumnFixed(item: BasicColumn, fixed?: 'left' | 'right') {
-        if (!state.checkedList.includes(item.dataIndex as string)) return;
-
-        const columns = getColumns().filter((c: BasicColumn) =>
-          state.checkedList.includes(c.dataIndex as string),
-        ) as BasicColumn[];
-        const isFixed = item.fixed === fixed ? false : fixed;
-        const index = columns.findIndex((col) => col.dataIndex === item.dataIndex);
-        if (index !== -1) {
-          columns[index].fixed = isFixed;
-        }
-        item.fixed = isFixed;
-
-        if (isFixed && !item.width) {
-          item.width = 100;
-        }
-        updateSortOption(item);
-        table.setCacheColumnsByField?.(item.dataIndex as string, { fixed: isFixed });
-        setColumns(columns);
-      }
-
-      function setColumns(columns: BasicColumn[] | string[]) {
-        isSetPropsFromThis = true;
-        isSetColumnsFromThis = true;
-        table.setColumns(columns);
-        const data: ColumnChangeParam[] = unref(plainSortOptions).map((col) => {
-          const visible =
-            columns.findIndex(
-              (c: BasicColumn | string) =>
-                c === col.value || (typeof c !== 'string' && c.dataIndex === col.value),
-            ) !== -1;
-          return { dataIndex: col.value, fixed: col.fixed, visible };
-        });
-
-        emit('columns-change', data);
-      }
-
-      function getPopupContainer() {
-        return isFunction(attrs.getPopupContainer)
-          ? attrs.getPopupContainer()
-          : getParentContainer();
-      }
-
-      function updateSortOption(column: BasicColumn) {
-        plainSortOptions.value.forEach((item) => {
-          if (item.value === column.dataIndex) {
-            Object.assign(item, column);
+          // 鎺掑簭
+          if (oldIndex > newIndex) {
+            options.splice(newIndex, 0, options[oldIndex]);
+            options.splice(oldIndex + 1, 1);
+          } else {
+            options.splice(newIndex + 1, 0, options[oldIndex]);
+            options.splice(oldIndex, 1);
           }
+
+          // 鏇存柊 鍒楀彲閫夐」
+          columnOptions.value = options;
+
+          // 鍒楄〃鍒楁洿鏂�
+          tableColumnsUpdate();
+          // 鏇存柊鍒楃紦瀛�
+          props.cache && columnOptionsSave();
+        },
+      });
+    }
+  };
+
+  // remove娑堝け鐨勫垪銆乸ush鏂板嚭鐜扮殑鍒�
+  const diff = () => {
+    if (typeof route.name === 'string') {
+      let cache = tableSettingStore.getColumns(route.name);
+      if (cache) {
+        // value銆乴abel鏄惁涓�鑷�
+        if (
+          JSON.stringify(columnOptions.value.map((o) => ({ value: o.value, label: o.label }))) !==
+          JSON.stringify(cache.map((o) => ({ value: o.value, label: o.label })))
+        ) {
+          const map = columnOptions.value.reduce((map, item) => {
+            map[item.value] = item.label;
+            return map;
+          }, {});
+          if (Array.isArray(cache)) {
+            // remove娑堝け鐨勫垪
+            cache = cache.filter((o) => map[o.value]);
+            // 鏇存柊label
+            cache.forEach((o) => {
+              o.label = map[o.value];
+            });
+            const cacheKeys = cache.map((o) => o.value);
+            // push鏂板嚭鐜扮殑鍒�
+            cache = cache.concat(columnOptions.value.filter((o) => !cacheKeys.includes(o.value)));
+            // 鏇存柊缂撳瓨
+            tableSettingStore.setColumns(route.name, cache);
+          }
+        }
+      }
+    }
+  };
+
+  // 浠庣紦瀛樻仮澶�
+  const restore = () => {
+    if (typeof route.name === 'string') {
+      const isIndexColumnShowCache = tableSettingStore.getShowIndexColumn(route.name);
+      // 璁剧疆杩囨墠鎭㈠
+      if (typeof isIndexColumnShowCache === 'boolean') {
+        isIndexColumnShow.value = defaultIsIndexColumnShow && isIndexColumnShowCache;
+      }
+
+      const isRowSelectionShowCache = tableSettingStore.getShowRowSelection(route.name);
+      // 璁剧疆杩囨墠鎭㈠
+      if (typeof isRowSelectionShowCache === 'boolean') {
+        isRowSelectionShow.value = defaultIsRowSelectionShow && isRowSelectionShowCache;
+      }
+    }
+    // 搴忓彿鍒楁洿鏂�
+    onIndexColumnShowChange({
+      target: { checked: isIndexColumnShow.value },
+    } as CheckboxChangeEvent);
+    // 閫夋嫨鍒楁洿鏂�
+    onRowSelectionShowChange({
+      target: { checked: isRowSelectionShow.value },
+    } as CheckboxChangeEvent);
+
+    if (typeof route.name === 'string') {
+      const cache = tableSettingStore.getColumns(route.name);
+      // 璁剧疆杩囨墠鎭㈠
+      if (Array.isArray(cache)) {
+        columnOptions.value = cache;
+      }
+    }
+  };
+
+  // 浠� 鍒楀彲閫夐」 鏇存柊 宸查�夊垪
+  const columnCheckedOptionsUpdate = () => {
+    columnCheckedOptions.value = columnOptions.value
+      .filter((o) => !o.column?.defaultHidden)
+      .map((o) => o.value);
+  };
+  // 浠� 鍒楀彲閫夐」 鏇存柊 鍏ㄩ�夌姸鎬�
+  const isColumnAllSelectedUpdate = () => {
+    isColumnAllSelected.value = columnOptions.value.length === columnCheckedOptions.value.length;
+  };
+  // 鏇存柊 showIndexColumn
+  const showIndexColumnUpdate = (showIndexColumn) => {
+    isInnerChange = true;
+    table.setProps({
+      showIndexColumn,
+    });
+  };
+  // 鏇存柊 rowSelection
+  const showRowSelectionUpdate = (showRowSelection) => {
+    isInnerChange = true;
+    table.setProps({
+      rowSelection: showRowSelection
+        ? {
+            ...omit(defaultRowSelection, ['selectedRowKeys']),
+            fixed: true,
+          }
+        : undefined,
+    });
+  };
+
+  // 鏇存柊琛ㄥ崟鐘舵��
+  const formUpdate = () => {
+    // 浠� 鍒楀彲閫夐」 鏇存柊 宸查�夊垪
+    columnCheckedOptionsUpdate();
+
+    // 浠� 鍒楀彲閫夐」 鏇存柊 鍏ㄩ�夌姸鎬�
+    isColumnAllSelectedUpdate();
+
+    // 鏇存柊 showIndexColumn
+    showIndexColumnUpdate(isIndexColumnShow.value);
+
+    // 鏇存柊 showRowSelection
+    showRowSelectionUpdate(isRowSelectionShow.value);
+
+    // 鍒楄〃鍒楁洿鏂�
+    tableColumnsUpdate();
+  };
+
+  const init = async () => {
+    if (!isRestored) {
+      // 鑾峰彇鏁版嵁鍒�
+      const columns = getTableColumns();
+
+      // 娌跨敤閫昏緫
+      table.setCacheColumns?.(columns);
+
+      // 鐢熸垚 榛樿鍊�
+      const options: ColumnOptionsType[] = [];
+      for (const col of columns) {
+        // 鍙紦瀛� string 绫诲瀷鐨勫垪
+        options.push({
+          label:
+            typeof col.title === 'string'
+              ? col.title
+              : col.customTitle === 'string'
+                ? col.customTitle
+                : '',
+          value:
+            typeof col.dataIndex === 'string'
+              ? col.dataIndex
+              : col.title === 'string'
+                ? col.title
+                : '',
+          column: {
+            defaultHidden: col.defaultHidden,
+          },
+          fixed: col.fixed,
         });
       }
 
-      return {
-        t,
-        ...toRefs(state),
-        indeterminate,
-        onCheckAllChange,
-        onChange,
-        plainOptions,
-        reset,
-        prefixCls,
-        columnListRef,
-        handleVisibleChange,
-        checkIndex,
-        checkSelect,
-        handleIndexCheckChange,
-        handleSelectCheckChange,
-        defaultRowSelection,
-        handleColumnFixed,
-        getPopupContainer,
-      };
-    },
+      // 榛樿鍊� 缂撳瓨
+      defaultIsIndexColumnShow = table.getBindValues.value.showIndexColumn || false;
+      defaultRowSelection = table.getRowSelection();
+      defaultIsRowSelectionShow = !!defaultRowSelection; // 璁剧疆浜� rowSelection 鎵嶅嚭鐜�
+      defaultColumnOptions = options;
+
+      // 榛樿鍊� 璧嬪��
+      isIndexColumnShow.value = defaultIsIndexColumnShow;
+      isRowSelectionShow.value = defaultIsRowSelectionShow;
+      columnOptions.value = cloneDeep(options);
+
+      // remove娑堝け鐨勫垪銆乸ush鏂板嚭鐜扮殑鍒�
+      props.cache && diff();
+
+      // 浠庣紦瀛樻仮澶�
+      props.cache && restore();
+
+      // 鏇存柊琛ㄥ崟鐘舵��
+      formUpdate();
+
+      isRestored = true;
+    }
+  };
+
+  // 鍒濆鍖�
+  const once = async () => {
+    // 浠呮墽琛屼竴娆�
+    await sortableFix();
+    init();
+  };
+  once();
+
+  // 澶栭儴鍒楁敼鍙�
+  const getColumns = computed(() => {
+    return table?.getColumns();
+  });
+  const getValues = computed(() => {
+    return table?.getBindValues;
+  });
+
+  onMounted(() => {
+    watch([getColumns, getValues], () => {
+      if (!isInnerChange) {
+        isRestored = false;
+        console.log('onMounted isRestored');
+        init();
+      } else {
+        isInnerChange = false;
+      }
+    });
   });
 </script>
 <style lang="less">
@@ -488,7 +659,7 @@
       transform: rotate(180deg);
     }
 
-    &__cloumn-list {
+    &__column-list {
       svg {
         width: 1em !important;
         height: 1em !important;
@@ -502,6 +673,7 @@
       }
 
       .ant-checkbox-group {
+        display: inline-block;
         width: 100%;
         min-width: 260px;
         // flex-wrap: wrap;

--
Gitblit v1.9.3