<template>
    <div>
        <my-card v-if="$scopedSlots.search">
            <a-form-model :model="queryForm" layout="horizontal">
                <a-row :gutter="16">
                    <slot name="search" :query="queryForm" />
                </a-row>
            </a-form-model>

            <div class="tw-text-right tw-mt-2">
                <a-space>
                    <a-button @click="reset">重置</a-button>
                    <a-button type="primary" @click="getData">查询</a-button>
                </a-space>
            </div>
        </my-card>

        <my-card class="tw-mt-3">
            <a-space class="tw-mb-2.5">
                <a-button v-if="addBtn" type="primary" key="add" v-bind="addBtn.options" @click="add">
                    {{ addBtn.text || '新建' }}
                </a-button>
                <template v-for="btn of buttons">
                    <a-button :type="btn.primary" :key="btn.text">{{ btn.text }}</a-button>
                </template>
            </a-space>
            <div class="tw-mb-2">
                <a-alert
                    v-if="selectedRowKeys.length"
                    :message="`已选择${selectedRowKeys.length}项`"
                    type="success"
                    closable
                    :after-close="handleClose"
                />
            </div>
            <a-table
                :data-source="data"
                :loading="loading"
                v-bind="$attrs"
                :pagination="pagination"
                @change="pageChange"
                :row-selection="isRowSelection"
            >
                <slot />
            </a-table>
        </my-card>

        <!-- 新增 -->
        <a-drawer
            :title="title"
            placement="right"
            :visible="addVisible"
            @close="addDrawerClose"
            v-if="$slots.drawer"
            :maskClosable="addBtn && !!addBtn.maskClosable"
            :drawerStyle="drawerStyle"
            :bodyStyle="bodyStyle"
            :width="(addBtn && addBtn.width) || 600"
            destroyOnClose
        >
            <div class="tw-overflow-y-hidden">
                <div class="tw-overflow-y-auto tw-h-full">
                    <slot name="drawer" />
                </div>
            </div>
            <template v-if="!noFooter">
                <a-divider />
                <a-space>
                    <a-button @click="addVisible = false">取消</a-button>
                    <a-button type="primary" @click="submit" :loading="submitLoading"> 确认 </a-button>
                </a-space>
            </template>
        </a-drawer>
    </div>
</template>

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

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

export default {
    props: {
        url: String,
        buttons: { type: Array, default: () => [] },
        addBtn: { type: Object },
        formatData: Function,
        noPage: Boolean,
        rowSelection: Object, //  radio  OR  checkbox
    },
    data() {
        return {
            initQuery: {
                ...initQuery,
            },
            title: '新增',
            data: [],
            queryForm: {},
            loading: false,
            addVisible: false,
            submitLoading: false,
            drawerStyle: {
                display: 'flex',
                flexDirection: 'column',
                overflowY: 'hidden',
            },
            bodyStyle: {
                flex: 1,
                overflow: 'hidden',
                display: 'flex',
                flexDirection: 'column',
            },
            noFooter: false,
            layout: {
                labelCol: { span: 4 },
                wrapperCol: { span: 20 },
            },
            total: 0,
            selectedRowKeys: [],
            selectedRows: [],
        };
    },
    watch: {
        addVisible(val) {
            if (!val && this.addBtn.onCancel) this.addBtn.onCancel();
        },
    },
    mounted() {
        this.getData();
    },

    computed: {
        pagination() {
            return this.noPage
                ? false
                : {
                      current: this.initQuery.pageNum,
                      pageSize: this.initQuery.pageSize,
                      total: this.total,
                  };
        },
        isRowSelection() {
            return this.rowSelection
                ? {
                      ...this.rowSelection,
                      selectedRowKeys: this.selectedRowKeys,
                      onChange: this.onSelectChange,
                  }
                : undefined;
        },
    },

    methods: {
        async getData() {
            this.loading = true;
            try {
                this.noPage ? await this.getDataNoPage() : await this.getDataWithPage();
            } catch (error) {
                // todo
            }
            this.loading = false;
        },
        async getDataNoPage() {
            const res = await request(this.url, METHOD.GET, this.queryForm);
            if (this.formatData) this.data = this.formatData(res);
            else this.data = res;
        },

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

        add() {
            this.addVisible = true;
        },
        addDrawerClose() {
            this.addVisible = false;
        },
        async submit() {
            this.submitLoading = true;
            try {
                await this.addBtn?.onOk();
                this.addVisible = false;
                this.getData();
            } catch (error) {
                // todo
            }
            this.submitLoading = false;
        },
        show({ type, title, noFooter } = {}) {
            if (type === 0) {
                this.title = '新增';
            }
            if (type === 1) {
                this.title = '编辑';
            }
            if (type === 2) {
                this.title = '查看';
            }
            if (title) {
                this.title = title;
            }
            this.noFooter = noFooter;
            this.addVisible = true;
        },
        reset() {
            this.queryForm = {};
            this.initQuery = { ...initQuery };
            this.getData();
        },
        pageChange(page) {
            this.initQuery.pageNum = page.current;
            this.getData();
        },

        onSelectChange(selectedRowKeys, selectedRows) {
            this.selectedRowKeys = selectedRowKeys;
            this.selectedRows = selectedRows;
        },
        handleClose() {
            this.selectedRowKeys = [];
            this.selectedRows = [];
        },
        getSelectedRowKeys() {
            return this.selectedRowKeys;
        },
        getTableData() {
            return this.data;
        },
    },
};
</script>
