<template>
    <div :style="`min-width: ${width}px`" class="tw-overflow-x-auto">
        <my-card v-if="$scopedSlots.search" class="tw-mb-2.5">
            <div class="tw-flex">
                <slot name="search" :query="queryForm" />
            </div>

            <div class="tw-text-right tw-mt-2">
                <a-space>
                    <a-popover v-if="$scopedSlots.moreSearch" trigger="click">
                        <template slot="content">
                            <div :class="$style.moreSearch">
                                <slot name="moreSearch" :query="queryForm" />
                            </div>
                        </template>
                        <a-button>更多查询</a-button>
                    </a-popover>
                    <a-button @click="reset">重置</a-button>
                    <a-button type="primary" @click="getData">查询</a-button>
                </a-space>
            </div>
        </my-card>

        <my-card :class="noPadding ? 'tw-p-0' : ''">
            <a-space class="tw-mb-2">
                <a-button type="primary" v-if="newBtn" @click="addBtnClick">
                    {{ newBtn.text || '新增' }}
                </a-button>
                <slot name="operation" />
            </a-space>

            <a-table
                :data-source="data"
                :loading="loading"
                v-bind="$attrs"
                :scroll="scroll"
                :rowKey="rowKey"
                :pagination="pagination"
                @change="pageChange"
                v-on="$listeners"
                :row-selection="selected ? rowSelection : undefined"
            >
                <slot />
                <a-table-column
                    :title="newButtons.title"
                    v-if="this.newButtons"
                    v-bind="this.newButtons.options"
                    fixed="right"
                    width="180"
                >
                    <template #default="row">
                        <my-ac-btn :row="row" :buttons="newButtons.data" />
                    </template>
                </a-table-column>
            </a-table>
        </my-card>

        <slot name="other" />

        <a-drawer
            v-if="$scopedSlots.drawer"
            placement="right"
            :visible="visible"
            :drawerStyle="drawerStyle"
            :bodyStyle="bodyStyle"
            destroyOnClose
            :width="dWidth"
            @close="hidden"
            :maskClosable="false"
            :title="title"
            :afterVisibleChange="afterVisibleChange"
        >
            <slot name="drawer" :hidden="hidden" :refresh="getData" :type="type" :row="row" />
        </a-drawer>
    </div>
</template>

<script>
import { request, METHOD } from '@/utils/requestUtil';

const assign = Object.assign;

const initQuery = {
    pageSize: 10,
    pageNum: 1,
};

const defaultTitle = '新增';

export default {
    props: {
        url: String,
        addBtn: [Object, Boolean],
        buttons: [Array, Object],
        noPage: Boolean,
        formatData: Function,
        rowKey: [String, Function],
        selected: Object,
        drawerWidth: {
            type: Number,
            default: 600,
        },
        noPadding: Boolean,
        scroll: Object,
        width: { type: Number, default: 900 },
        defaultQuery: {
            type: Object,
            default: () => ({}),
        },
        otherQuery: {
            type: Object,
            default: () => ({}),
        },
    },

    data() {
        const newBtn = this.addBtn ? (typeof this.addBtn === 'object' ? this.addBtn : {}) : this.addBtn;
        return {
            initQuery: {
                ...initQuery,
            },
            data: [],
            queryForm: { ...this.defaultQuery },
            loading: false,
            total: 0,
            visible: false,
            title: newBtn.title ?? defaultTitle,
            drawerStyle: {
                display: 'flex',
                flexDirection: 'column',
                overflowY: 'hidden',
            },
            bodyStyle: {
                flex: 1,
                overflow: 'hidden',
            },
            type: null,
            row: null,
            dWidth: this.drawerWidth,
        };
    },

    watch: {
        otherQuery: {
            handler(val) {
                this.otherQuery = val;
            },
            deep: true,
            immediate: true,
        },
    },

    mounted() {
        this.getData();
    },

    computed: {
        newBtn() {
            return this.addBtn ? (typeof this.addBtn === 'object' ? this.addBtn : {}) : this.addBtn;
        },
        newButtons() {
            return this.buttons
                ? Array.isArray(this.buttons)
                    ? { data: this.buttons, title: '操作' }
                    : this.buttons
                : null;
        },
        pagination() {
            return this.noPage
                ? false
                : {
                      current: this.initQuery.pageNum,
                      pageSize: this.initQuery.pageSize,
                      total: this.total,
                      showQuickJumper: true,
                  };
        },
        rowSelection() {
            return {
                onChange: (selectedRowKeys, selectedRows) => {
                    this.$emit('update:selected', { keys: selectedRowKeys, rows: selectedRows });
                },
            };
        },
    },

    methods: {
        async getData() {
            this.loading = true;
            try {
                this.noPage ? await this.getDataNoPage() : await this.getDataWithPage();
            } catch (error) {
                // todo
            }
            this.loading = false;
        },

        async getDataWithPage() {
            const res = await request(this.url, METHOD.GET, {
                ...this.initQuery,
                ...this.queryForm,
                ...this.otherQuery,
            });
            this.total = res.total;
            if (this.formatData) this.data = this.formatData({ ...res });
            else this.data = res.records;
        },

        async getDataNoPage() {
            const res = await request(this.url, METHOD.GET, { ...this.queryForm, ...this.otherQuery });
            if (this.formatData) this.data = this.formatData(res);
            else this.data = res;
        },

        pageChange(page) {
            this.initQuery.pageNum = page.current;
            this.getData();
        },

        hidden() {
            this.visible = false;
        },
        afterVisibleChange(visible) {
            if (!visible) {
                this.title = this.addBtn?.title ?? defaultTitle;
                this.type = null;
                this.row = null;
                this.dWidth = this.drawerWidth;
            }
        },

        show(params) {
            this.visible = true;
            assign(this, params);
        },

        reset() {
            this.queryForm = { ...this.defaultQuery };
            this.initQuery = { ...initQuery };
            this.getData();
        },

        refreshView() {
            this.data = [...this.data];
        },

        addBtnClick() {
            const { click } = typeof this.addBtn === 'object' ? this.addBtn : {};
            click && click();
            this.visible = true;
        },
    },
};
</script>

<style module lang="less">
.moreSearch {
    display: flex;
    flex-direction: column;
    width: 400px;
    padding: 15px 0 0 0;

    > div {
        @apply tw-mb-3;
    }
}
</style>
