<template>
    <div class="backup">
        <div class="search">
            <el-form
                ref="searchForm"
                :model="form"
                label-width="100px"
                inline
            >
                <el-form-item
                    label="备份时间"
                    prop="backTime"
                    label-width="60px"
                >
                    <el-date-picker
                        v-model="form.backTime"
                        size="small"
                        type="datetimerange"
                        range-separator="至"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                    >
                    </el-date-picker>
                </el-form-item>
                <el-form-item
                    label="还原时间"
                    prop="recoveryTime"
                >
                    <el-date-picker
                        v-model="form.recoveryTime"
                        size="small"
                        type="datetimerange"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                    >
                    </el-date-picker>
                </el-form-item>
                <el-button
                    type="primary"
                    icon="el-icon-search"
                    style="margin-left: 20px;"
                    v-privilege="activeMenu + 'SEARCH'"
                    @click="search"
                    size="small"
                >查询</el-button>
                <div>
                    <el-form-item
                        label="还原选项"
                        prop="backTable"
                        label-width="60px"
                    >
                        <el-checkbox-group v-model="form.backTable">
                            <el-checkbox label="SYS_USER,SYS_USER_ROLE">用户</el-checkbox>
                            <el-checkbox label="SYS_ROLE,SYS_AUTHORIZE">角色</el-checkbox>
                            <el-checkbox label="SYS_ORG">机构</el-checkbox>
                            <el-checkbox label="SYS_MENU">菜单</el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>    
                </div>
            </el-form>
            <div class="button">
                <el-checkbox v-model="icoreFilterFlag" style="float:left;margin-top: 9px;">过滤</el-checkbox>
                <el-button
                    type="primary"
                    icon="el-icon-upload"
                    v-privilege="activeMenu + 'BACKUP'"
                    @click="backVisible = true"
                    size="small"
                >备份</el-button>
                <el-button
                    type="primary"
                    icon="el-icon-refresh"
                    v-privilege="activeMenu + 'REDUCTION'"
                    :loading="buttonLoading"
                    @click="recordAction"
                    size="small"
                >还原</el-button>
            </div>
        </div>
        <el-table stripe
            ref="backUpTable"
            v-loading="tableLoading"
            :height="tableHeight"
            @row-click="nodeClick"
            border
            @icoreFilterChange="icoreFilterChange"
            :icore-filter-flag="icoreFilterFlag"
            highlight-current-row
            :data="restoreData"
        >
            <el-table-column
                :show-overflow-tooltip="true"
                prop="flashbackTime"
                label="备份时间"
                type="noFilter"
                sortable
                width="200"
                align="center"
            ></el-table-column>
            <el-table-column
                :show-overflow-tooltip="true"
                prop="updDate"
                sortable
                label="还原时间"
                type="noFilter"
                width="200"
                align="center"
            >
            </el-table-column>
            <el-table-column
                :show-overflow-tooltip="true"
                prop="restoreData"
                label="还原数据"
                width="200"
                align="center"
            >
            </el-table-column>
            <el-table-column
                :show-overflow-tooltip="true"
                prop="crtUserCode"
                label="备份用户"
                width="80"
                align="center"
            >
            </el-table-column>
            <el-table-column
                :show-overflow-tooltip="true"
                prop="updUserCode"
                label="还原用户"
                width="80"
                align="center"
            >
            </el-table-column>
            <el-table-column
                :show-overflow-tooltip="true"
                prop="memo"
                label="备注"
                align="center"
            >
            </el-table-column>
        </el-table>
        <el-dialog
            title="备份所有表数据"
            :visible.sync="backVisible"
            width="40%"
        >
            <p>是否备份当前所有表数据？</p>
            <el-form>
                <el-input
                    type="textarea"
                    placeholder="详细信息，最多只允许输入100个字符。"
                    maxlength="100"
                    show-word-limit
                    v-model="textMemo"
                ></el-input>
            </el-form>

            <div
                slot="footer"
                class="dialog-footer"
            >
                <el-button
                    @click="backVisible = false"
                    :loading="buttonLoading"
                >
                    取 消
                </el-button>
                <el-button
                    type="primary"
                    @click="backUpRoles"
                    :loading="buttonLoading"
                >
                    确 定
                </el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { formatDate } from "@/utils/util.js";
export default {
    name: 'backup',
    data () {
        return {
            form: {
                backTable: ['SYS_USER,SYS_USER_ROLE', 'SYS_ROLE,SYS_AUTHORIZE', 'SYS_ORG', 'SYS_MENU'],
                backTime: ['', ''],
                // backTime: [
                //     formatDate(new Date(new Date().getTime() - 24 * 60 * 60 * 1000 * 2), 'yyyy-MM-dd HH:mm:ss'),
                //     formatDate(new Date(), 'yyyy-MM-dd HH:mm:ss')
                // ],
                recoveryTime: [],
            },
            backVisible: false,
            buttonLoading: false,
            tableHeight: 600,
            icoreFilterFlag: false,
            tableLoading: false,
            restoreData: [],
            textMemo: '',
            activeRow: undefined
        }
    },
    mounted () {
        this.getRecorList();
        this.$nextTick(() => {
            //
            this.tableHeight = this.getTreeHeight(this.$refs['backUpTable'].$el) - 70;
        });
    },
    created () {
        this.activeMenu = window.localStorage.getItem('activeMenu');
    },
    methods: {
        search () {
            //do something
            this.getRecorList();
        },
        getRecorList () {
            let that = this;
            let data = {
                bcs: this.form.backTime && this.form.backTime.length === 2 ? this.form.backTime[0] : '',
                bce: this.form.backTime && this.form.backTime.length === 2 ? this.form.backTime[1] : '',
                res: this.form.recoveryTime && this.form.recoveryTime.length === 2 ? this.form.recoveryTime[0] : '',
                ree: this.form.recoveryTime && this.form.recoveryTime.length === 2 ? this.form.recoveryTime[1] : ''
            };
            that.tableLoading = true;
            that.axios.get("pass/v1/sysbackups/selectAll/?bckStartTime=" + data.bcs + "&backEndTime=" + data.bce + "&resStartTime=" + data.res + "&resEndTime=" + data.ree).then(res => {
                if (res.code === "0") {
                    that.restoreData = res.data;
                    that.total = res.data.length
                } else {
                    that.$message.error(res.message);
                }
                that.tableLoading = false;
            })
                .catch(res => {
                    console.log(res);
                    that.tableLoading = false;
                });
        },
        //  计算树区域高度
        getTreeHeight (dom) {
            return window.innerHeight - dom.offsetTop;
        },
        nodeClick (item) {
            //选中行
            this.activeRow = item;
        },
        icoreFilterChange () {
            //do something
        },
        // 备份
        backUpRoles () {
            let that = this;
            try {
                let rule = {
                    max: 100,
                    required: true,
                    errName: '备份说明'
                };
                that.checkCharLength(rule, that.textMemo);
                that.buttonLoading = true;
                that.axios
                    .post("pass/v1/sysbackups/backupData/?memo=" + that.textMemo)
                    .then(res => {
                        if (res.code === "0") {
                            that.$message.success("备份成功");
                            that.getRecorList();
                            that.backVisible = false;
                            that.textMemo = "";
                        } else {
                            that.$message.error(res.message);
                        }
                        that.buttonLoading = false;
                    })
                    .catch(res => {
                        that.buttonLoading = false;
                    });
            } catch (err) {
                this.$message.error(err.message)
            }

        },
        recordAction (type) {
            let that = this;
            // 获取选中的还原项目
            if (!this.form.backTable || this.form.backTable.length < 1) {
                that.$message.error('请选择需要还原的表')
                return false;
            }
            if (!this.activeRow) {
                that.$message.error('请选择一条备份记录进行还原')
                return false;
            }
            if (this.activeRow.updUserCode) {
                that.$message.error('备份记录只能还原一次')
                return false;
            }
            let flashbackTime = this.activeRow.flashbackTime;
            let nowDate = new Date();
            let selDate = new Date(flashbackTime);
            // if (nowDate - selDate < 180000) {
            //     this.$message.error("只能选择15分钟之前的备份进行还原");
            //     return false;
            // }
            that.buttonLoading = true;
            let tabIds = "";
            for (let i = 0; i < this.form.backTable.length; i++) {
                if (i === 0) {
                    tabIds = this.form.backTable[i];
                } else {
                    tabIds = tabIds + "," + this.form.backTable[i];
                }
            }
            let parmID = this.activeRow.id;
            that.axios.post("pass/v1/sysbackups/restoreData/" + flashbackTime + "?tableName=" + tabIds).then(res => {
                if (res.code === "0") {
                    that.$message.success("还原成功");
                    that.restoreVisible = false;
                    that.axios.put("pass/v1/sysbackups/" + parmID, { 'restoreData': tabIds }).then((res) => {
                        if (res.code === '0') {
                            that.getRecorList();
                        }
                        that.buttonLoading = false;
                        that.doNotClose = true;
                    })
                } else {
                    that.$message.error(res.message);
                    that.buttonLoading = false;
                    that.doNotClose = true;
                }
            })
                .catch(res => {
                    that.buttonLoading = false;
                    that.doNotClose = true;
                });
        },
        // 校验方法
        checkCharLength (rule, value, msg) {
            if (value) {
                let chineseLen = 3;
                let iLen = chineseLen > 1 ? this._charLength(value, chineseLen) : value.length;
                if (rule.min && rule.min > 0 && iLen < rule.min) {
                    throw new Error(rule.errName + '最少输入' + rule.min + '个字符（一个中文占' + chineseLen + '个字符）')
                }
                if (rule.max && rule.max > 0 && iLen > rule.max) {
                    throw new Error(rule.errName + '最多输入' + rule.max + '个字符（一个中文占' + chineseLen + '个字符）')
                }
            }
        },
        _charLength (str, chineseLen) {
            if (!str || str.length <= 0) { return 0; };
            // str = mytrim(str);
            let chineseLength = 3; // utf-8编码，中文长度
            if (chineseLen && chineseLen > 0) {
                chineseLength = chineseLen
            }
            let objValue = str;
            let objLength = 0;
            let compareChar = '';
            let regExp = new RegExp("^[A-Za-z0-9 -_`~!@#$%^&*()-+=|,<.>/?;:'\\\"]$");
            for (let count = 0; count < objValue.length; count++) {
                compareChar = objValue.substring(count, count + 1);
                if (regExp.test(compareChar)) {
                    objLength += 1;
                } else if (compareChar === '\\') {
                    objLength += 1;
                } else {
                    objLength += chineseLength;
                }
            }
            return objLength;
        }
    }

}
</script>

<style lang="less" scoped>
.backup {
    height: 100%;
    padding: 15px;
    box-sizing: border-box;
    height: 100%;
    min-width: 800px;
    overflow: auto;
    .search {
        width: 100%;
        margin: 0 auto;
        margin-top: 10px;
        // min-height: 142px;
        // .el-form {
        //     box-sizing: border-box;
        //     width: 500px;
        //     float: left;
        // }
        .button {
            text-align: right;
        }
    }
}
</style>

