<style lang="less" scoped>
.log {
    background-color: black;
    color: white
}
.gap {
    margin-top: 15px
}
</style>
<template>
    <div class="main main-font">
        <div class="main-header">
            <el-breadcrumb>
                <el-breadcrumb-item>{{query.state}}列表</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="main-filters">
            <el-form :inline="true" :model="query" @submit.native.prevent>
                <el-form-item>
                    <el-select v-model="query.type" placeholder="类型">
                        <el-option key="" label="" value=""></el-option>
                        <el-option
                            v-for="item in types"
                            :key="item"
                            :label="item"
                            :value="item">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-input placeholder="关键字搜索" v-model="q" @change="search"></el-input>
                </el-form-item>
            </el-form>
        </div>
        <div class="main-actions">
            <div class="main-actions-label">
                共
                <em>{{count[query.state + 'Count']}}</em>条数据
                <span v-show="2">，当前选中
                    <em>{{selectedItems.length}}</em>
                </span>
            </div>
            <div class="main-actions-btns">
                <el-button @click="showDeleteLog = !showDeleteLog">范围删除</el-button>
                <el-button :disabled="!(selectedItems.length)" @click="deleteAll">批量删除</el-button>
                <el-button :disabled="!(selectedItems.length)" @click="retryAll">批量重试</el-button>
            </div>
        </div>
        <el-table
            border
            :data="items"
            @sort-change="onSortItems"
            @selection-change="onSelect"
        >
            <el-table-column type="selection" width="50"></el-table-column>
            <el-table-column sortable="custom" prop="id" label="ID" width="80"></el-table-column>
            <el-table-column prop="type" label="任务类型"></el-table-column>
            <el-table-column prop="data" label="详细" inline-template>
                 <div class="name">
                    <p v-for="(item, key) in row.data">
                        {{key}} : {{item}}
                    </p>
                </div>
            </el-table-column>
            <el-table-column prop="progress" label="进度"  width="80"></el-table-column>
            <el-table-column prop="priority" label="优先级"  width="80"></el-table-column>
            <el-table-column prop="duration" label="duration(ms)" width="100">
            </el-table-column>
            <el-table-column prop="state" label="状态" inline-template width="100">
                <el-tag :type="statusAlias[row.state].icon">{{statusAlias[row.state].name}}</el-tag>
            </el-table-column>
             <el-table-column prop="attempts" label="重试" inline-template  width="80">
                 <div>
                     {{row.attempts.made}} / {{row.attempts.max}}
                 </div>
            </el-table-column>
            <el-table-column label="时间" width="240" inline-template>
                 <div>
                    <p>created: {{row.created_at | date}}</p>
                    <p>updated: {{row.updated_at | date}}</p>
                </div>
            </el-table-column>
            <el-table-column label="操作" inline-template width="100">
                <div class="item-menus">
                    <el-button size="small" type="primary" @click="retry(row)">重试</el-button>
                    <el-button @click="deleteItem(row)" type="danger">删除</el-button>
                    <el-button @click="getLogs(row)" type="gray">日志</el-button>
                </div>
            </el-table-column>
        </el-table>
        <el-pagination
            v-if="items.length"
            layout="prev, pager, next, jumper"
            :total="count[query.state + 'Count']"
            :current-page="query.page_num"
            :page-size="query.page_size"
            @current-change="onPageChange"
        >
        </el-pagination>
        <!-- item model editor -->
        <el-dialog title="任务日志" v-model="showlog" size="tiny">
            <div class="log">
                <p v-for="item in logs"> {{item}}</p>
            </div>
        </el-dialog>

        <el-dialog title="设置范围删除任务" v-model="showDeleteLog" size="tiny">
            <div>
                <el-row>
                    <span>开始：</span><el-input-number v-model="delete_start"></el-input-number>
                </el-row>
                <el-row class="gap">
                    <span>结束：</span><el-input-number v-model="delete_end"></el-input-number>
                </el-row>
                <el-row class="gap">
                    <el-button native-type="submit" type="primary" @click="scopeDelete">删除</el-button>
                </el-row>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import api from '../lib/http';
import Promise from 'bluebird';
import moment from 'moment';


export default {
    data() {
        return {
            query: {
                state: 'inactive',
                page_size: 20,
                page_num: 1,
                order: 'desc',
                type: ''
            },
            delete_start: 0,
            delete_end: 0,
            q: '',
            interval: null,
            items: [],
            logs: [],
            showlog: false,
            showDeleteLog: false,
            selectedItems: [],
            count: {},
            types: [],
            statusAlias: {
                'inactive': {
                    icon: 'gray',
                    name: 'inactive'
                },
                'active': {
                    icon: 'primary',
                    name: 'active'
                },
                'failed': {
                    icon: 'danger',
                    name: 'failed'
                },
                'delayed': {
                    icon: 'warning',
                    name: 'delayed'
                },
                'complete': {
                    icon: 'success',
                    name: 'success'
                }
            },
        };
    },
    methods: {
        onSortItems({prop, order}) {
            let sort = '';
            if(prop && order) {
                sort = `${order !== 'ascending' ? 'desc' : 'asc'}`;
            }

            this.query.order = sort;

            return api.getJobs(this.query)
            .then(data => {
                this.items = data.data;
                this.startInterval()
            });
        },
        onSelect(items) {
            if(this.interval) {
                clearInterval(this.interval);
            }
            this.selectedItems = items;
        },
        startInterval() {
            if(this.interval) {
                clearInterval(this.interval);
            }

            this.interval =  setInterval(() => {
                api.getStats(this.query)
                .then(data => {
                    this.count = data.data;
                })
                api.getJobs(this.query)
                .then(data => {
                    this.items = data.data;
                });
            }, 10000);
        },
        onPageChange(num) {
            this.query.page_num = +num || 1;
            api.getJobs(this.query)
            .then(data => {
                this.items = data.data;
                return this.startInterval();
            });
        },
        deleteAll() {
            const promises = [];
            this.selectedItems.map(item => {
                 promises.push(api.delete(item.id));
            });
           return Promise.all(promises)
           .then(() => {
                return api.getJobs(this.query)
                .then(data => {
                    this.$message({
                        message: '删除成功',
                        type: 'success'
                    });
                    this.items = data.data;
                    this.startInterval()
                });
           })
        },
        scopeDelete() {
            if(this.delete_start && this.delete_end && this.delete_start < this.delete_end) {
                const promises = [];
                while(this.delete_start < this.delete_end) {
                     promises.push(api.delete(this.delete_start));
                     this.delete_start ++;
                }
                return Promise.all(promises)
                .then(() => {
                    return api.getJobs(this.query)
                    .then(data => {
                        this.$message({
                            message: '删除成功',
                            type: 'success'
                        });
                        this.delete_start = 0;
                        this.delete_end = 0;
                        this.showDeleteLog = false;
                        this.items = data.data;
                        this.startInterval()
                    });
                });
            };
            return this.$message({
                message: '删除范围不合法',
                type: 'error'
            });
        },
        retryAll() {
            const promises = [];
            this.selectedItems.map(item => {
                 promises.push(api.retry(item.id));
            });
            return Promise.all(promises)
            .then(() => {
                return api.getJobs(this.query)
                .then(data => {
                    this.$message({
                        message: '重试成功',
                        type: 'success'
                    });
                    this.items = data.data;
                    this.startInterval()
                });
            })
        },
        deleteItem(row) {
            this.$confirm('确认删除？')
            .then(() => {
                return api.delete(row.id)
                .then(() => {
                    return api.getJobs(this.query)
                    .then(data => {
                        this.$message({
                            message: '删除成功',
                            type: 'success'
                        });
                        this.items = data.data;
                        this.startInterval()
                    });
                });
            })
            .catch(err => {
                throw new Error(err);
            });
        },
        retry(row) {
            this.$confirm('确认重新执行？')
            .then(() => {
                 return api.retry(row.id)
                .then(data => {
                    return api.getJobs(this.query)
                    .then(data => {
                        this.$message({
                            message: '重试成功！',
                            type: 'success'
                        });
                        this.items = data.data;
                        this.startInterval()
                    });
                });
            })
            .catch(err => {
                throw new Error(err);
            });
        },
        loadTypes() {
            return api.types()
            .then(data => {
                this.types = data.data;
            });
        },
        search() {
            if(this.interval) {
                clearInterval(this.interval);
            }
            if(!this.q) {
                this.interval();
            }
            api.search(this.q)
            .then(data => {
                this.items = data.data;
            });
        },
        getLogs(row) {
            return api.getLogs(row.id)
            .then(data => {
                this.showlog = true;
                this.logs = data.data || [];
            })
        }
    },
    created() {
        this.query.state = this.$route.params.state;
        return api.getStats(this.query)
        .then(data => {
            this.count = data.data;
            return api.getJobs(this.query)
            .then(data => {
                this.items = data.data;
            }).then(() => {
                return Promise.all([
                    api.getJobs(this.query)
                    .then(data => {
                        this.items = data.data;
                        this.startInterval()
                    }),
                    this.loadTypes()
                ]);
            });
        });
    },
    watch: {
        $route() {
            this.query.page_num = 1;
            this.query.state = this.$route.params.state;
            api.getJobs(this.query)
            .then(data => {
                this.items = data.data;
                this.startInterval()
            });
        }
    }
};
</script>
