PaginationComponent.ts 11 KB
import type {AxiosInstance} from "axios";
import {AutumnConfig} from "lib/src/core/config/AutumnConfig";
import type {FormCommonType, OptionItem} from "lib/src/core/form/FormField";
import {setFieldDefaultValue} from "lib/src/core/form/FormField";
import type {FilterOptionsType} from "lib/src/core/page/FilterField";
import {Pagination} from "lib/src/core/page/Pagination";
import {Component, Vue} from "vue-facing-decorator";
import {reactive} from "vue";
import StringUtils from "lib/src/utils/StringUtils";

/**
 * 分页查询页面的父类
 */
@Component
export class PaginationComponent<T> extends Vue {

    /**
     * form-labelCol配置
     */
    labelCol = {xs: 24, sm: 24, md: 7};

    /**
     * form-wrapperCol配置
     */
    wrapperCol = {xs: 24, sm: 24, md: 15};

    /**
     * 加载中标志
     */
    loading = false;

    /**
     * 搜索条件显示或隐藏
     */
    collapse = false;

    /**
     * 查询表单key
     */
    queryFormKey: string;

    /**
     * 分页数据对象
     */
    pagination: Pagination<T> = null;

    /**
     * 新建弹窗
     */
    createVisible = false;

    /**
     * 修改弹窗
     */
    editVisible = false;

    /**
     * 详情弹窗
     */
    viewVisible = false;

    showCreate(): void {
        this.createVisible = true;
    }

    /**
     * 初始化组件
     * @param axiosInstance
     * @param pageUrl
     * @param pageSize
     */
    init(axiosInstance: AxiosInstance, pageUrl: string, pageSize = AutumnConfig.PAGE_LIMIT): void {
        this.pagination = new Pagination<T>(axiosInstance, pageUrl, pageSize);
    }

    /**
     * 构建表单
     * @ param controlsConfig
     * @ param options
     */
    buildQueryForm(controlsConfig: { [key: string]: [FormCommonType, [], FilterOptionsType] | [FormCommonType, FilterOptionsType] | FormCommonType }): void {
        // 创建表单对象
        const formGroup = {};
        // 循环处理所有配置项
        for (const key in controlsConfig) {
            // 获取每一个配置项的值
            const configs = controlsConfig[key];
            if (configs === null || !(configs instanceof Array)) {
                continue;
            }
            // 添加每一个属性到表单对象中,key为属性名,配置值对应数组中的第一个元素为属性值
            formGroup[key] = configs[0];
            // 添加表单渲染配置对象,在config数组中的第三个元素
            if (configs.length >= 2) {
                // 获取表单配置对象
                const formField = configs.length === 2 ? configs[1] : configs[2] as FilterOptionsType;
                formField.fieldName = key;
                if (!formField.field) {
                    formField.field = key;
                }
                if (configs.length === 3) {
                    configs[2] = null;
                }
                setFieldDefaultValue(formField);
                this.pagination.filterFields.push(formField);
            }
        }
        this.pagination.queryForm = reactive(formGroup);
    }

    /**
     * 设置表单查询缓存
     * @param queryFormKey
     */
    setQueryCacheable(queryFormKey: string): void {
        if (StringUtils.isNotEmpty(queryFormKey)) {
            this.queryFormKey = queryFormKey;
            this.pagination.filterFields.forEach(item => {
                const value = localStorage.getItem(this.queryFormKey + "_" + item.fieldName);
                if (value) {
                    this.pagination.queryForm[item.fieldName] = value;
                }
            });
            const pageSize = localStorage.getItem(this.queryFormKey + "_PAGE_SIZE");
            const pageIndex = localStorage.getItem(this.queryFormKey + "_PAGE_INDEX");
            if (StringUtils.isInteger(pageSize)) {
                this.pagination.pageSize = Number(pageSize);
            }
            if (StringUtils.isInteger(pageIndex)) {
                this.pagination.pageIndex = Number(pageIndex);
            }
        }
    }

    /**
     * 按默认条件开始查询
     */
    pageLoad(): Promise<unknown> {
        this.loading = true;
        return this.pagination.refresh().finally(() => {
            this.loading = false;
            this.onCompleteRefresh();
        });
    }

    /**
     * 重新查询,从第1页开始
     */
    pageReload(): Promise<unknown> {
        this.loading = true;
        return this.pagination.reload().finally(() => {
            this.loading = false;
            //设置缓存条件值
            this.saveQueryForm();
            this.onCompleteRefresh();
        });
    }

    /**
     * 重置查询表单,从第1页开始
     */
    pageReset(): Promise<unknown> {
        this.loading = true;
        return this.pagination.reset().finally(() => {
            this.loading = false;
            this.clearQueryForm();
            this.onCompleteInfinite();
        });
    }

    /**
     * 设置缓存条件值
     */
    saveQueryForm(): void {
        if (this.queryFormKey) {
            for (const key in this.pagination.queryForm) {
                const itemKey = this.queryFormKey + "_" + key;
                if (this.pagination.queryForm[key]) {
                    localStorage.setItem(itemKey, this.pagination.queryForm[key]);
                } else {
                    localStorage.removeItem(itemKey);
                }
            }
            localStorage.setItem(this.queryFormKey + "_PAGE_INDEX", this.pagination.pageIndex.toString());
            localStorage.setItem(this.queryFormKey + "_PAGE_SIZE", this.pagination.pageSize.toString());
        }
    }

    /**
     * 清除缓存条件值
     */
    clearQueryForm(): void {
        if (this.queryFormKey) {
            this.pagination.filterFields.forEach(item => {
                const itemKey = this.queryFormKey + "_" + item.fieldName;
                localStorage.removeItem(itemKey);
            });
            localStorage.setItem(this.queryFormKey + "_PAGE_INDEX", this.pagination.pageIndex.toString());
            localStorage.setItem(this.queryFormKey + "_PAGE_SIZE", this.pagination.pageSize.toString());
        }
    }

    /**
     * 刷新分页
     */
    pageRefresh(pagination?, filters?, sorter?): Promise<unknown> {
        if (sorter?.field) {
            let sortField = sorter.field;
            if (sorter.field instanceof Array) {
                sortField = sorter.field.join('.');
            }
            this.pagination.setSort(sortField, sorter.order === 'descend' ? 'desc' : 'asc');
        }
        if (pagination) {
            this.pagination.pageIndex = pagination.current;
            this.pagination.pageSize = pagination.pageSize;
        }
        return this.doPage();
    }

    /**
     * 分页变化之后调用
     * @param page
     * @param pageSize
     */
    pageChange(page: number, pageSize: number): Promise<unknown> {
        this.pagination.pageIndex = page;
        this.pagination.pageSize = pageSize;
        return this.doPage();
    }

    /**
     * 执行分页请求
     * @private
     */
    private doPage(): Promise<unknown> {
        this.loading = true;
        return this.pagination.refresh().finally(() => {
            this.loading = false;
            //设置缓存分页页数值
            if (this.queryFormKey) {
                localStorage.setItem(this.queryFormKey + "_PAGE_INDEX", this.pagination.pageIndex.toString());
                localStorage.setItem(this.queryFormKey + "_PAGE_SIZE", this.pagination.pageSize.toString());
            }
            this.onCompleteInfinite();
        });
    }

    /**
     * 重置查询条件后回调,页面会跳到第一页
     */
    onCompleteRefresh(): void {
        console.debug('Refresh complete!');
    }

    /**
     * 分页跳转后回调,查询条件不会变化,页面会刷新
     */
    onCompleteInfinite(): void {
        console.debug('Infinite complete!');
    }


    /**
     * 上拉加载更多
     */
    doInfinite(): void {
        if (!this.loading) {
            //判断是否加载数据
            if (!this.pagination.isLast()) {
                this.pagination.nextPage(true);
            }
        }
    }

    /**
     * 根据fieldName查询出FilterField
     * @param fieldName 字段名称
     */
    findFilterFieldByName(fieldName: string): FilterOptionsType {
        return this.pagination.filterFields.find(field => field.fieldName === fieldName);
    }

    /**
     * 设置fieldName的optionItems值,只针对select、checkbox-group、radio-group有效
     * @param fieldName
     * @param optionItems
     */
    setFilterFieldOptionItems(fieldName: string, optionItems: OptionItem[]): void {
        const filterField = this.findFilterFieldByName(fieldName);
        if (filterField.type === 'select' || filterField.type === 'checkbox-group' || filterField.type === 'radio-group') {
            filterField.optionItems = optionItems;
        }
    }

    /**
     * 根据字段名字 修改 其属性
     * @param fieldName 字段名
     * @param attribute 属性
     * @param value 值
     */
    setFilterFieldAttribute(fieldName: string, attribute: string, value: unknown): void {
        const formField: FilterOptionsType = this.findFilterFieldByName(fieldName);
        if (formField) {
            if (typeof formField[attribute] !== typeof value) {
                throw new TypeError('attribute is ' + typeof formField[attribute] + ',but value is ' + typeof value + '.');
            }
            formField[attribute] = value;
        } else {
            throw new Error(fieldName + ' not found');
        }
    }

    /**
     * 生成一个简单的 OptionItems
     * @param trueLabel value is true label
     * @param falseLabel value is false label
     * @param showAllOptions 是否展示{全部}选项
     */
    generateOptionItems(trueLabel: string, falseLabel: string, showAllOptions = false): { label: string; value: unknown }[] {
        const optionItems: { label: string; value: unknown }[] = [
            {label: trueLabel, value: true},
            {label: falseLabel, value: false}
        ];
        if (showAllOptions) {
            // @ts-ignore
            optionItems.unshift({label: this.$t('common.all'), value: ''});
        }
        return optionItems;
    }

    /**
     * 当前分页状态
     */
    get pageState(): unknown {
        return {
            current: this.pagination.pageIndex,
            pageSize: this.pagination.pageSize,
            total: this.pagination.totalElements,
            showSizeChanger: true,
            pageSizeOptions: ['10', '20', '30', '50', '100'],
            showQuickJumper: true,
            // @ts-ignore
            showTotal: (total, range) => this.$t('common.page_state', {start: range[0], end: range[1], total: total})
        };
    }

    /**
     * 简单分页状态
     */
    get simplePageState(): unknown {
        return {
            current: this.pagination.pageIndex,
            pageSize: this.pagination.pageSize,
            total: this.pagination.totalElements,
            showSizeChanger: true,
            pageSizeOptions: ['10', '20', '30', '50', '100'],
            showQuickJumper: false,
        };
    }


}