import DICT from '@/utils/dict';

export default {
    data() {
        return {
            tableData: [], // 表格数据
            total: 0, // 表格总条数
            tableLoading: false, // 表格loading
            selectedRows: [], // 已选行数据
            filters: {},
            filtersConfig: {},
            queryParams: {},
            pagination: {
                // 分页初始化数据
                page: 1,
                pageSize: 20,
            },
            btnLoading: false,
            currentRow: null,
            pickerOptions: {
                shortcuts: [
                    {
                        text: '最近一周',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                            picker.$emit('pick', [start, end]);
                        },
                    },
                    {
                        text: '最近一个月',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                            picker.$emit('pick', [start, end]);
                        },
                    },
                    {
                        text: '最近三个月',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                            picker.$emit('pick', [start, end]);
                        },
                    },
                ],
            },
        };
    },
    computed: {
        // 仅勾选一条
        isSingle() {
            return this.selectedRows?.length === 1;
        },
        // 已勾选
        isSelected() {
            return this.selectedRows?.length > 0;
        },
        queryParamsKey() {
            // 列表搜索绑定对象key
            return this.paramsKey || 'filters';
        },
        // 是否默认执行列表接口查询
        initRefresh() {
            return true;
        },
    },
    mounted() {
        if (this.initRefresh === true) this.refresh();
    },
    methods: {
        filterDict(dictKey, val) {
            const def = { label: '', value: val };
            if ([null, undefined, ''].includes(val)) {
                return def;
            }
            return DICT[dictKey].find((item) => item.value === val) || def;
        },
        /**
         * @func 时间选择器选择回调方法
         * @desc
         *  date: [array | string]: '日期组件选中数据',
         *  keys [array | string]: '对应参数的key',
         *  needTime [boolean]: '为时间跨度选择时，是否需要再末尾固定增加时分秒'
         * }
         * @return {}
         * @param date
         * @param keys
         * @param needTime
         */
        handleDates(date, key) {
            const paramsKey = this.queryParamsKey;

            if (Array.isArray(date)) {
                // 时间跨度
                this[paramsKey][key] = [date[0], date[1]];
            } else {
                // 单个选择
                // this[paramsKey][key] = date;
            }
        },

        onReset(refresh = true, def = {}) {
            const paramsKey = this.queryParamsKey;
            this[paramsKey] = { ...this.$options.data()[paramsKey], ...def };

            // 不分页情况
            if (!this.pagination) {
                refresh && this.getData();
                return;
            }

            this.pagination.page === 1;

            const { res_: searchParams } = this.$refs['app-filter'].handleData(this[paramsKey]);
            this.queryParams = this.handleQueryParams(searchParams, this.pagination);
            refresh && this.getData();
        },
        // 查询 data: 查询表单数据
        onQuery(searchConfig, data) {
            const paramsKey = this.queryParamsKey;
            this[paramsKey] = data;

            if (!this.pagination) {
                this.getData();
                return;
            }

            this.queryParams = this.handleQueryParams(searchConfig, { page: 1 });
            this.getData();
        },
        // 刷新
        refresh(resetPageNum = false) {
            if (resetPageNum) this.pagination.page = 1;

            if (!this.pagination) {
                this.getData();
                return;
            }

            this.$nextTick(() => {
                if (this.$refs['app-filter']) {
                    const { res_ } = this.$refs['app-filter'].handleData(this[this.queryParamsKey]);
                    this.queryParams = this.handleQueryParams(res_, this.pagination);
                }
                this.getData();
            });
        },
        // 请求参数处理
        handleQueryParams(params, pageBean) {
            return {
                querys: [...(params || [])],
                pageBean: { ...this.pagination, ...pageBean },
                sorter: this.sorter ? [...this.sorter] : []
            };
        },

        // 请求触发
        async getData(param) {
            this.selectedIds = [];
            this.selectedRows = [];
            this.tableLoading = true;
            // const params = this.queryParams || this.handleQueryParams([], this.pagination);

            typeof this.onBeforeGetData === 'function' && this.onBeforeGetData(this.queryParams, this[this.paramsKey]);
            try {
                if (typeof this.dataMethod === 'function') {
                    const params = !this.pagination ? this[this.queryParamsKey] : this.queryParams;

                    let res = {};
                    if (this?.type === 'sql') {
                        res = await this.dataMethod(params, this.id);
                    } else if (this.type === 'file' || this.type === 'api') {
                        res = await this.dataMethod(params, this.id, this.curNode.id);
                    } else {
                        if (this?.isAuthorizeShow) {
                            res = await this.dataMethod(params, this.selectRowId);
                        } else {
                            if (this.xqfType === '1') {
                                res = await this.dataMethod(params, this.tableId);
                            } else if (this.xqfType === '2' || this.xqfType === '3') {
                                res = await this.dataMethod(params, this.tableId, this.resourceId);
                            } else {
                                res = await this.dataMethod(params);
                            }
                        }
                    }
                    const { rows, total } = res;

                    if (rows) {
                        this.tableData = typeof this.handleResult === 'function' && this.handleResult(rows);
                        this.total = total || 0;
                        typeof this.onAfterGetData === 'function' && this.onAfterGetData(res);
                    } else {
                        this.tableData = res?.data || [];
                        typeof this.handleResult === 'function' && this.handleResult(res?.data || []);
                    }
                }
            } catch (e) {
                console.error(e);
            } finally {
                setTimeout(() => {
                    this.tableLoading = false;
                }, 500);
            }
        },
        // 请求结果处理
        handleResult(list) {
            return list?.length ? [...list] : [];
        },
        // 当前checkbox 已勾选触发
        onSelectionChange(rows) {
            this.selectedRows = rows;
            this.selectedIds = rows.map((item) => item.id);
        },
        // 分页触发
        onPaginationChange(page) {
            this.pagination = page;
            this.refresh();
        },

        /**
         * 用于设置非查询条件组件的其他默认请求参数值
         * @param {Object} queryData 分页请求对象
         * @param {Array} [{ operation: 'EQUAL', property: 'dwCatalogsId', relation: 'AND', value: ''}] 查询条件对象
         * @param {String} key 查询参数字段名 property
         * @param {any} value 查询参数值
         * @return void
         * */
        setFilterValue(queryData, filters, key, value) {
            const targetFilter = filters.filter((item) => item.property === key);
            if (targetFilter && targetFilter.length) {
                targetFilter[0].value = value;
                this.setQuerys(queryData, key, targetFilter[0]);
            } else {
                this.$message.warning('未找到查询参数');
            }
        },

        /**
         * 用于请求参数querys去重设置
         * @param {Object} queryData 分页请求对象
         * @param {String} key 查询参数字段名 property
         * @param {Object} newFilter 查询条件对象
         * @return void
         * */
        setQuerys(queryData, key, newFilter) {
            const { querys = [] } = queryData;
            const targetIndex = querys.findIndex((item) => item.property === key);
            if (targetIndex !== -1) {
                querys.splice(targetIndex, 1, newFilter);
            } else {
                querys.push(newFilter);
            }
            queryData.querys = querys;
        },
    },
};
