<template>
    <div class="p-4">
        <div class="backup-header">
            <div class="search-box">
                <div class="search-item">
                    <div class="search-name">数据库：</div>
                    <a-input v-model:value="searchValue" placeholder="输入关键字查询" allow-clear />
                </div>
                <div class="search-item">
                    <div class="search-name">备份时间：</div>
                    <a-range-picker style="width: 400px" v-model:value="searchDate" :disabled-date="disabledDate"
                        :show-time="{ format: 'HH:mm:ss' }" format="YYYY-MM-DD HH:mm:ss" />
                </div>
            </div>
            <div class="handle-btns">
                <a-button class="btn" @click="resetTable">重置</a-button>
                <a-button class="btn" type="primary" @click="searchTable">查询</a-button>
            </div>
        </div>

        <div class="backup-body">
            <BasicTable @register="registerTable">
                <template #toolbar>
                    <Button type="primary" @click="handleSetScheduledTask">
                        定时备份策略
                    </Button>
                    <Button type="primary" @click="handleAddDataBackUp">
                        新增备份
                    </Button>
                    <Button type="primary" danger :disabled="hasSelected" @click="handleDelAllDataBackUp">
                        批量删除
                    </Button>
                </template>
                <template #action="{ record }">
                    <TableAction :actions="[
                        {
                            label: '删除',
                            tooltip: '删除',
                            onClick: handleDelDataBackUp.bind(null, record),
                        },
                        {
                            label: '下载',
                            tooltip: '下载',
                            onClick: handleDownloadDataBackUp.bind(null, record),
                        }
                    ]" />
                </template>
            </BasicTable>
        </div>
        <AddDataBackUpModal @register="registerModal" @success="onSubmit"></AddDataBackUpModal>
        <ScheduledTaskModal @register="registerTaskModal" @success="onSubmit"></ScheduledTaskModal>
    </div>
</template>

<script>
import { defineComponent, reactive, ref, toRefs, computed, onMounted } from 'vue';
// 导入表格组件，表格事件
import { BasicTable, useTable, TableAction } from '/@/components/Table';
import { useModal } from '/@/components/Modal';
import { Button, message } from 'ant-design-vue';
import moment from 'moment'
import { getBackupsList, downloadDBFile, delDataBackup } from '/@/api/sys/dataBackUp';
import uiTool from '/@/utils/uiTool';
import AddDataBackUpModal from './AddDataBackUpModal.vue';
import ScheduledTaskModal from './ScheduledTaskModal.vue';

export default defineComponent({
    name: 'backup',
    components: { BasicTable, TableAction, Button, AddDataBackUpModal, ScheduledTaskModal },
    setup() {
        const [registerModal, { openModal }] = useModal();
        const [registerTaskModal, { openModal: openTaskModal }] = useModal();
        // 搜索数据
        const data = reactive({
            searchValue: "",//查询值
            searchDate: []
        });
        // 禁选时间
        const disabledDate = (current) => {
            return current && current > moment().endOf('day');
        };
        //获取所有备份数据
        const getDataBackUp = () => {
            return new Promise((resolve, reject) => {
                let params = {
                    keyStr: data.searchValue,
                    satrttime: data.searchDate.length ? moment(data.searchDate[0]).format('YYYY-MM-DD HH:mm:ss') : null,
                    endtime: data.searchDate.length ? moment(data.searchDate[1]).format('YYYY-MM-DD HH:mm:ss') : null
                }
                getBackupsList(params).then((res) => {
                    if (res.resp_code === 0 && res.datas) {
                        resolve(res.datas.pageData)
                    }
                    else {
                        resolve([])
                        message.error(res.resp_msg)
                    }
                })
            })

        }
        //表格列
        const columns = [
            {
                title: '数据库IP',
                align: 'center',
                dataIndex: 'dbIp',
                key: 'dbIp',
            },
            {
                title: '数据库名称',
                align: 'center',
                dataIndex: 'dbName',
                key: 'dbName',
            },
            {
                title: '备份说明',
                align: 'center',
                dataIndex: 'description',
                key: 'description'
            },
            {
                title: '操作人',
                align: 'center',
                dataIndex: 'optUser',
                key: 'optUser'
            },
            {
                title: '备份时间',
                align: 'center',
                dataIndex: 'optTime',
                key: 'optTime'
            }
        ];
        // 重置
        const resetTable = () => {
            data.searchValue = '';
            data.searchDate = [];
            reload();
        }
        // 查询
        const searchTable = () => {
            reload();
        }
        // 判断是否选中数据
        const hasSelected = computed(() => {
            const rowSelection = getRowSelection();
            return !rowSelection.selectedRowKeys?.length;
        });
        // 设置定时备份策略
        const handleSetScheduledTask = () => {
            openTaskModal(true)
        }
        // 新增备份数据
        const handleAddDataBackUp = () => {
            openModal(true)
        }
        // 删除选中的所有备份数据
        const handleDelAllDataBackUp = () => {
            uiTool.delModal('确定删除选中的备份数据？', (() => {
                const rowKeys = getSelectRowKeys();
                let ids = rowKeys.toString()
                let param = {
                    fid: ids
                }
                delDataBackup(param).then(res => {
                    if (res.resp_code === 0) {
                        message.success('操作成功');
                        reload();
                        setSelectedRowKeys([])
                    }
                })
            }))
        }
        // 删除备份数据
        const handleDelDataBackUp = (record) => {
            uiTool.delModal('确定删除该备份数据？', (() => {
                let param = {
                    fid: record.fid
                }
                delDataBackup(param).then(res => {
                    if (res.resp_code === 0) {
                        reload();
                        setSelectedRowKeys([])
                    }
                })
            }))
        }
        // 下载备份数据
        const handleDownloadDataBackUp = (record) => {
            let param = {
                fid: record.fid
            }
            downloadDBFile(param).then(res => {
                if (res.resp_code === 0) {
                    reload();
                    setSelectedRowKeys([])
                }
            })
        }
        // 弹窗确认
        const onSubmit = () => {
            reload();
        }
        const [
            registerTable,
            { reload, collapseAll, getRowSelection, getSelectRowKeys, setSelectedRowKeys },
        ] = useTable({
            title: '数据备份列表', //'菜单列表'
            api: getDataBackUp, //加载数据，暂时没有接口用假数据
            // dataSource: restoreData,//假数据
            columns: columns,
            useSearchForm: false,     //开启搜索区域
            bordered: false,
            showTableSetting: true,  // 显示表格设置
            showIndexColumn: true,
            pagination: {
                // pageSize: 10,
                hideOnSinglePage: false
            },
            rowKey: (record) => record.fid,
            actionColumn: {
                width: 200,
                title: '操作',
                dataIndex: 'action',
                slots: { customRender: 'action' },
            },
            rowSelection: {
                type: 'checkbox',
            },
            tableSetting: {
                redo: true,
                size: true,
                setting: false,
                fullScreen: false
            },
        });
        return {
            disabledDate,
            columns,
            hasSelected,
            ...toRefs(data),
            // func
            registerTable,
            registerModal,
            registerTaskModal,
            resetTable,
            searchTable,
            handleSetScheduledTask,
            handleAddDataBackUp,
            handleDelAllDataBackUp,
            handleDelDataBackUp,
            handleDownloadDataBackUp,
            onSubmit
        };
    },
});
</script>

<style lang="less" scoped>
.p-4 {
    height: 100%;

    .backup-header {
        // padding: 10px;
        padding: 0 20px;
        width: 100%;
        height: 70px;
        background-color: #fff;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .search-box {
            display: flex;

            .search-item {
                display: flex;
                align-items: center;

                &:last-child {
                    margin-left: 20px;
                }

                .search-name {
                    margin-right: 10px;
                    // width: 100px;
                    white-space: nowrap
                }
            }
        }

        .handle-btns {
            // margin-right: 20px;
            display: flex;
            align-items: center;

            .label {
                width: 150px;
            }

            .btn {
                margin-left: 10px;
            }
        }
    }

    .backup-body {
        padding: 0 30px;
        margin-top: 20px;
        width: 100%;
        // height: 800px;
        height: calc(100% - 90px);
        background-color: #fff;

        .body-header {
            display: flex;
            height: 80px;
            width: 100%;
            justify-content: space-between;
            align-items: center;

            .item-title {
                height: 40px;
                line-height: 40px;
                font-size: 16px;
                user-select: none;
            }

            .table-btns {
                .btn {
                    margin-right: 10px;

                    &:last-child {
                        margin-right: 0;
                    }
                }
            }
        }

        .body-content {
            padding-bottom: 20px;
            height: calc(100% - 80px);

            a {
                margin-right: 10px;
            }
        }
    }
}
</style>