
var $taskVue = new Vue({
    el: "#task-container",
    data: {
        select: {
            currentRow: [],
            rows: {}
        },
        selectCom: {
            model: 'post',
            data: [{ value: 'post', label: 'post' }, { value: 'get', label: 'get' }, { value: 'exec', label: 'exec' }]
        },
        log: {
            index: 0,
            model: false,
            title: 'Log',
            group: '',
            closable: true,
            footerHide: true,
            spin: false,
            page: 0,
            data: []
        },
        isAdd: true,
        closable: false,
        footerHide: true,
        model: false,
        modelMessage: 'Task Manager',
        activedIndex: 0,
        taskValidate: {
            taskName: '', groupName: '', interval: '', link: '', authKey: '', authValue:
                '', describe: '', requestType: ''
        },
        ruleValidate: {
            taskName: [{ required: true, message: 'Task name is required', trigger: 'blur' }],
            groupName: [{ required: true, message: 'Group name  is required', trigger: 'blur' }],
            interval: [{ required: true, message: 'Interval(Cron)  is required', trigger: 'blur' }],
            requestType: [{ required: true, message: 'Request type  is required', trigger: 'change' }],
            link: [{ required: true, message: 'Link  is required', trigger: 'blur' }]
        },
        taskForm: [
            { name: 'taskName', text: 'Task Name', value: '', placeholder: 'Please input task name', readOnly: false },
            { name: 'groupName', text: 'Group Name', value: '', placeholder: 'Please input group name', readOnly: false },
            { name: 'interval', text: 'Interval(Cron)', value: '', placeholder: 'Cron expression：0/0 0/10 * * * ? ' },
            { name: 'link', text: 'Link', value: '', placeholder: "Url Or full class name" },
            { name: 'authKey', text: 'Header(key)', value: '', placeholder: 'Requet key in header Key' },
            { name: 'authValue', text: 'Header(value)', value: '', placeholder: 'Request value in header' },
            {
                name: 'requestType', text: 'Request Type', value: '', onChange: (data,value) => {
                }, placeholder: 'post/get/exec', type: 'select'
            },
            { name: 'describe', text: 'description', value: '', type: 'textarea' }
        ],
        columns: [
            {
                hidden:true,
                title: 'id',
                key: 'id',
                width: 120
            },
            {
                type: 'selection',
                width: 60,
                align: 'center'
            },
            {
                title: 'Task Name',
                key: 'taskName',
                width: 150
            }, {
                title: 'Group Name',
                key: 'groupName',
                width: 150
            },
            {
                title: 'Last Run Time',
                key: 'lastRunTime',
                width: 170
            }, {
                title: 'Inverval(Cron)',
                key: 'interval',
                width: 140
            },
            {
                title: 'Status',
                key: 'status',
                width: 80,
                render: (h, params) => {
                    var style = { color: 'white', background: 'red', padding: '3px 10px', borderRadius: '4px' };
                    var text = '';
                    switch (params.row.status) {
                        case 0:
                            style.background = '#0acb0a';
                            text = 'Normal';
                            break;
                        case 1:
                            style.background = '#ed4014';
                            text = 'Paused';
                            break;
                        case 2:
                            style.background = '#fc2f2f';
                            text = 'Completed';
                            break;
                        case 3:
                            style.background = '#607D8B';
                            text = 'Error';
                            break;
                        case 4:
                            style.background = '#607D8B';
                            text = 'Blocked';
                            break;
                        case 5:
                            style.background = '#607D8B';
                            text = 'Stop';
                            break;
                        default:
                            style.background = '#f90';
                            text = 'Not exist';
                            break;
                    }
                    return h('div', [
                        h('Button', {
                            props: {
                                //type: 'error',
                                size: 'small'
                            }, style: style,
                            on: {
                                click: function () {
                                }
                            }
                        }, text)
                    ]);
                }
            },
            {
                title: 'Descritpion',
                key: 'describe',
                minWidth:180
            },
            {
                title: 'Url or Class Name',
                key: 'link',
                minWidth: 180
            },
            {
                title: 'Request Type',
                key: 'requestType',
                width: 130
            },
            {
                title: 'Operation',
                key: 'operat',
                width: 110,
                render: (h, params) => {
                    var style = { 'font-size': '12px' };

                    return h('div', [
                        h('i-button', {
                            props: {
                                //type: 'error',
                                size: 'small'

                            }, style: style,
                            on: {
                                click: function () {
                                    $taskVue.getJobRunLog(params);
                                }
                            }
                        }, 'Excution logs')
                    ]);
                }
            }
        ],
        rows: []
    }, methods: {
        onChange(item, value) {
            if (item.onChange && typeof item.onChange == "function") {
                item.onChange(value, item);
            }
        },
        getColumns: function () {
            var columns = [];
            this.columns.forEach(function (item) {
                if (!item.hidden) {
                    columns.push(item);
                }
            })
            return columns;
        },
        selectRow: function (selection, row) {
            this.select.currentRow = row;
            this.select.rows = selection;
        },
        first: function () {
            $taskVue.log.index = 0;
            $taskVue.log.page = 0;
            $taskVue.log.data = [];
            this.getJobRunLog(null, true);
        },
        next: function () {
            this.getJobRunLog(null, true);
        },
        getJobRunLog: function (params, next) {
            if (!next) {
                //if (!(params.row.taskName === $taskVue.log.title
                //    && params.row.groupName === $taskVue.log.groupName)) {
                $taskVue.log.page = 0;
                $taskVue.log.index = 0;
                $taskVue.log.title = params.row.taskName;
                $taskVue.log.groupName = params.row.groupName;
                $taskVue.log.data = [];
                //  }
            }
            $taskVue.log.model = true;
            //  $taskVue.log.spin = true;
            $taskVue.log.page++;
            $taskVue.ajax("/Task/GetRunLog", {
                taskName: $taskVue.log.title, groupName: $taskVue.log.groupName, page: $taskVue.log.page
            }, function (data) {
                if (data.length === 0) {
                    if ($taskVue.log.page >= 1) {
                        $taskVue.log.page--;
                    }
                    if (next) {
                        $taskVue.$Message.success('No logs!');
                    }
                    return;
                }
                //  $taskVue.log.spin = false;
                if (next) {
                    $taskVue.log.data = data;
                    // $taskVue.log.data.push(...data);
                } else {
                    $taskVue.log.data = data;
                }
                $taskVue.log.index += $taskVue.log.index ? data.length: 1;
            });
        },
        getTaskValidate: function () {
        },
        add: function () {
            for (var key in this.taskValidate) {
                this.taskValidate[key] = '';
            }
            this.setFormClass(false);
            this.model = true;
        },
        tiggerAction: function (action) {
            if (!this.select.rows.length)
                return $taskVue.$Message.success('Please select a task!');
            this.ajax('/Task/' + action,
                this.select.rows[0], function (data) {
                    if (data.status) {
                        $taskVue.refresh(true);
                    }
                    return $taskVue.$Message.success(data.msg);
                });
        },
        update: function () {
            //   this.tiggerAction('update');
            if (!this.select.rows.length)
                return $taskVue.$Message.success('Please select a task!');
            this.model = true;
            //this.taskValidate = this.select.rows.slice(0, 1)[0];
            for (var key in this.select.rows[0]) {
                this.taskValidate[key] = this.select.rows[0][key];
            }
            this.setFormClass(true);
            //this.taskForm[0]
        },
        refresh: function (_init) {
            this.select.currentRow = [];
            this.select.rows = {};
            this.ajax("/Task/GetJobs", {}, function (data) {
                data.forEach(function (row) {
                    row.cellClassName = { operat: 'view-log' };
                });
                $taskVue.rows = data;
                if (!_init) {
                    return $taskVue.$Message.success('Refresh Successful!');
                }
            });
        },
        handleSelectAll(status) {
            this.$refs.selection.selectAll(status);
        },
        handleSubmit(name) {
            this.$refs[name].validate((valid) => {
                if (!valid) {
                    return this.$Message.error('Some fields is required!');
                }
                this.ajax("/Task/" + (this.isAdd ? 'add' : 'update'), this.taskValidate, function (data) {
                    $taskVue.$Message.success(data.msg || 'Save Successful');
                    if (data.status) {
                        $taskVue.model = false;
                        $taskVue.refresh(true);
                    }
                });
            });

        },
        setFormClass: function (readOnly) {
            this.isAdd = !readOnly;
            this.modelMessage = !readOnly ? 'New Task' : 'Update Task';
            this.taskForm.forEach(x => {
                if (x.name === "taskName" || x.name === "groupName") {
                    x.readOnly = readOnly;
                }
            });
        },
        ajax: function (url, params, fun) {
            axios({
                method: 'post',
                url: url,
                params: params,
                headers: { 'X-Requested-With':'XMLHttpRequest'}
            }).then(function (response) {
                fun && fun(response.data);
                }).catch(function (error) {
                    if (error.response.status === 401) {
                        return window.location.href = '/home/index';
                    }
                $taskVue.$Message.success('Error!');
                console.log(error);
            });
        }
    }, created: function () {
        this.refresh(true);
    }, mounted: function () {
        //$headerVue.activedIndex = 0;
    }
});