<template>
    <div>
        <my-breadcrumb />        

        <search
            v-loading="loading"
            class="search"
            :data="searchData"
            :response-data="responseData"
            @search="onSearch"
            @reset="onReset"
        />

        <el-button-group class="btn-group" v-if="hasGlobalAction">
            <el-button v-if="hasAddAction" type="primary" icon="el-icon-plus" @click="onCreate">添加</el-button>
        </el-button-group>

        <el-table
            class="table"
            v-loading="loading"
            :data="data">
            <el-table-column
                v-for="item in tableData"
                :key="item.name"
                :prop="item.name"
                :label="item.title">
            </el-table-column>
            <el-table-column label="操作" v-if="hasRowAction">
                <template slot-scope="scope">
                    <el-button
                        v-if="hasUpdateAction"
                        size="mini"
                        @click="onUpdate(scope.row)">修改</el-button>
                    <el-button
                        v-if="hasDeleteAction"
                        size="mini"
                        type="danger"
                        @click="onDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination
            class="pagination"
            background
            v-loading="loading"
            layout="total, sizes, prev, pager, next"
            :current-page.sync="pagination.currentPage"
            :page-size.sync="pagination.pageSize"
            :total="pagination.total"
            :page-sizes="pagination.pageSizes"
            @current-change="fetch"
            @size-change="fetch">
        </el-pagination>
    </div>
</template>

<script>
import axios from 'axios'
import PaginationMixin from '../mixins/pagination.js'
import MyBreadcrumb from '../components/MyBreadcrumb'
import Search from '../components/Search'
import routes from '../route.js'

const GlobalActions = [
    'add'
]
const RowActions = [
    'delete'
]

export default {
    mounted() {
        this.fetch()
    },
    components: {
        MyBreadcrumb,
        Search
    },
    mixins: [
        PaginationMixin
    ],
    props: {
        name: String,
        fetchUrl: String,
        searchData: Array,
        tableData: Array,
        actions: Array,
        addData: Array,
    },
    watch: {
        '$route' (newVal) {
            if (newVal.name === this.name) {
                this.fetch()
            }
        }  
    },
    computed: {
        hasGlobalAction () {
            return this.existsActions(GlobalActions)
        },
        hasRowAction () {
            return this.existsActions(RowActions)
        },
        hasAddAction () {
            return this.findActionByName('add')
        },
        hasUpdateAction () {
            return this.findActionByName('update')
        },
        hasDeleteAction () {
            return this.findActionByName('delete')
        }
    },
    data() {
        return {
            data: [],
            search: '',
            loading: false,
            responseData: null
        }
    },
    methods: {
        fetch() {
            this.loading = true
            axios.get(this.fetchUrl, {
                params: {
                    search: this.search,
                    page: this.pagination.currentPage,
                    pageSize: this.pagination.pageSize, 
                }
            }).then(this.handleResponse).catch(this.handleError)
        },
        handleResponse (response) {
            this.loading = false
            const responseData = response.data
            const {data, meta} = responseData
            this.data = data
            this.setPagination(meta.pagination)

            this.responseData = responseData
        },
        handleError () {
            this.loading = false
        },
        onSearch(search) {
            const page = this.search == search ? this.pagination.currentPage : 1
            this.search = search
            this.loading = true
            axios.get(this.fetchUrl, {
                params: {
                    search,
                    page,
                    pageSize: this.pagination.pageSize, 
                }
            }).then(this.handleResponse).catch(this.handleError)
        },
        onReset () {
            this.loading = true
            axios.get(this.fetchUrl, {
                params: {
                    page: 1,
                    pageSize: this.pagination.pageSize, 
                }
            }).then(this.handleResponse).catch(this.handleError)
        },
        onDelete (row) {
            this.$confirm('此操作将删除该条记录, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.loading = true
                axios.delete(`${this.fetchUrl}/${row.id}`)
                    .then(() => {
                        this.loading = false
                        this.fetch()
                    })
                    .catch(() => {
                        this.loading = false
                    })
            }).catch(() => {

            })
        },
        findActionByName (name) {
            return this.actions.findIndex(action => action === name) > -1
        },
        existsActions (targetActions) {
            if (this.actions && this.actions instanceof Array && this.actions.length > 0) {
                const result = targetActions.filter(action => this.findActionByName(action))
                if (result && result.length > 0) {
                    return true
                }
            }
            return false
        },
        onCreate () {
            let params = {}
            if (this.addData instanceof Array) {
                this.addData.forEach(key => {
                    if (this.responseData[key]) {
                        params[key] = this.responseData[key]
                    }
                })
            }
            const path = `${this.$route.path}/create`
            const route = routes[1].children.find(item => item.path == path)
            if (route) {
                this.$router.push({
                    name: route.name,
                    params
                })
            }
        },
        onUpdate (row) {
            let params = {}
            if (this.addData instanceof Array) {
                this.addData.forEach(key => {
                    if (this.responseData[key]) {
                        params[key] = this.responseData[key]
                    }
                })
            }
            const path = `${this.$route.path}/update`
            const route = routes[1].children.find(item => item.path == path)
            if (route) {
                this.$router.push({
                    name: route.name,
                    query: {
                        id: row.id
                    },
                    params
                })
            }
        }
    }
}
</script>

<style lang="less" scoped>
.search {
    background-color: #fff;
    padding: 20px;
    margin-bottom: 10px;
}
.btn-group {
    background-color: #fff;
    padding: 10px;
    width: 100%;
    box-sizing: border-box;
}
.table {
    width: 100%;
    padding: 20px;
}
.pagination {
    text-align: right;
    padding: 20px;
    background-color: #fff;
    margin-top: 10px;
}
</style>