<template>
<el-dialog title="选择角色" :visible.sync="show" append-to-body :before-close="onCancel">
    <div class="scope">
        <el-row>
            <el-col :span="17">
                <el-input v-model="searchName" @keyup.enter.native="searchRole" placeholder="请输入搜索关键词"></el-input>
            </el-col>
            <el-col :span="6" style="margin-left: 14px;">
                <el-button type="primary" @click="searchRole">查找</el-button>
                <el-button @click="resetSearch">重置</el-button>
            </el-col>
        </el-row>
         <el-table class="mt15" :data="list" border v-loading="loading">
            <el-table-column prop="name" align="center" label="角色名称"/>
            <el-table-column prop="describle" label="描述" align="center" show-overflow-tooltip />
            <el-table-column prop="action" label="操作" align="center" width="150">
                <template slot-scope="scope">
                    <el-button size="small" type="primary" @click="onConfirm(scope.row)">选择</el-button>
                </template>
            </el-table-column>
        </el-table>
        <Page :page="query.page" :size="query.size" :total="total" @pageChange="pageChange"></Page>
    </div>
</el-dialog>
</template>

<script>
import { getRoles } from '@/api/role';
import { notEmpty, formatDate } from '@/utils/tool';

export default {
    props: ['show'],
    data () {
        return {
            searchName: '',
            query: {
                page: 1,
                size: 10,
                sort: 'create_time desc',
            },
            total: 0,
            loading: false,
            list: [],
        }
    },
    computed: {
        pageTotal() {
            const page = Math.ceil(this.total / this.query.size);
            return page > 0 ? page : 1;
        },
    },
    mounted () {
        this.loadData();
    },
    methods: {
        resetSearch() {
            this.searchName = '';
            this.query.page = 1;
            this.loadData();
        },
        searchRole() {
            this.query.page = 1;
            this.loadData();
        },
        pageChange(page, size) {
            this.query.page = page;
            this.query.size = size;
            this.loadData();
        },
        loadData() {
            this.loading = true;
            let query = '';
            if (notEmpty(this.searchName)) {
                query = `name==*${this.searchName.trim()}*`;
            }
            this.query.query = query;
            getRoles(this.query).then(res => {
                this.total = res.total || 0;
                this.list = res.data || [];
                this.loading = false;
            });
        },
        onCancel() {
            this.$emit('update:show', false);
        },
        onConfirm(row) {
            this.$emit('confirm', {
                id: row.id,
                name: row.name,
            });
        },
    }
}
</script>

<style lang="scss" scoped>

</style>