<template>
    <div class="oo-page">
        <div class="oo-server">
            <div class="table-search">
                <Form :model="model" :label-width="100" ref="searchForm">
                    <Row :gutter="12">
                        <i-col span="5">
                            <FormItem label="任务名称：" prop="nameLike">
                                <Input v-model="model.nameLike" placeholder="请输入任务名称" clearable></Input>
                            </FormItem>
                        </i-col>
                        <i-col span="5">
                        <FormItem label="命令：" prop="commandLike">
                            <Input v-model="model.commandLike" placeholder="请输入命令" clearable></Input>
                        </FormItem>
                    </i-col>
                        <i-col span="6">
                            <FormItem label="起止日期：" prop="timerange">
                                <DatePicker v-model="model.timerange"
                                            format="yyyy-MM-dd HH:mm:ss" type="datetimerange" placeholder="请选择时间范围"></DatePicker>
                            </FormItem>
                        </i-col>
                        <!-- <i-col span="5">
                            <FormItem label="状态：" prop="status">
                                <i-select v-model="model.status" multiple>
                                    <i-option v-for="(key,value) in statusMap" :value="value">{{key}}</i-option>
                                </i-select>
                            </FormItem>
                        </i-col> -->
                         <i-col span="5">
                            <FormItem label="执行类型：" prop="executeType">
                                <i-select v-model="model.executeType" clearable>
                                    <i-option v-for="item in executeTypeList" :value="item.key">{{ item.value}}</i-option>
                                </i-select>
                            </FormItem>
                        </i-col>
                        <i-col span="2" >
                            <div class="table-search-btns">
                                <Button type="primary" icon="ios-search" @click="searchTable">搜索</Button>
                            </div>
                        </i-col>
                    </Row>
                </Form>
            </div>
            <cs-dynamic-table ref="child" :prop="csTable" :parent="this">
                <template slot="form" scope="props">
                    <command-form :model="props.obj" :action="props.action" :tableVm="props.tableVm" @closeModal="props.closeModal" :tableInfo="props.tableInfo" ref="form"></command-form>
                </template>
            </cs-dynamic-table>
             <Modal v-model="modelFlag" title="任务明细" width="80" :mask-closable="false" @on-cancel="closeModal" >
                <cmd-run-result  ref="result" @closeModal="closeModal"> </cmd-run-result>
                <div slot="footer"></div>
            </Modal>

            <Modal v-model="recurringFlag" title="轮询任务明细" width="80" :mask-closable="false" @on-cancel="closeModalRecurring" >
                <cmd-recurring  ref="result2" @closeModal="closeModalRecurring"> </cmd-recurring>
                <div slot="footer"></div>
            </Modal>
        </div>
    </div>
</template>

<script lang="ts">
    import { Component, Vue } from "vue-property-decorator";
    import CommandForm from "./command-form.vue";
    import CmdRunResult from "./cmd-run-result.vue";
    import CmdRecurring from "./command-recurring.vue";

    import {formatDateTime} from "@/libs/util";
    @Component({
        components: {
            CommandForm,
            CmdRunResult,
            CmdRecurring
        }
    })
    export default class Command extends Vue {
        modelFlag : boolean = false;
        recurringFlag : boolean = false;
        // cancelLoading : boolean =false;
        // resumeLoading : boolean = false;

        private activeModel : any = {
            code:"",
            name:"",
            description:"",
            roleMenus:[]
        };

        private model : any = {
            commandLike:"",
            timerange:"",
            status:""
        };
        private statusMap: any = {"0":"中止","1":"活跃","2":"取消","3":"删除","4":"失败","5":"等待","6":"成功"
        ,"7":"未知","8":"警告","9":"篡改","10":"TAMPERED","11":"阻塞","12":"重复","13":"过期","14":"僵死","15":"停止中","16":"已停止"};

        starts = {"a":"b"};
        private executeTypeList: any=[{key:"RUNNING_EXE_TYPE",value:"立即执行"},{key:"RECURRING_EXE_TYPE",value:"调度执行"}];
        private actions :Array<any> = [
            [{
                icon: 'ios-eye',
                action: 'detail',
                label: '明细',
                type:'primary'
            }],
            [{
                icon: 'ios-eye',
                action: 'detail',
                label: '明细',
                type:'primary'
            },{
                icon: 'ios-play',
                action: 'resume',
                label: '恢复',
                type:'success',
                loading:false
            }],
            [{
                icon: 'ios-eye',
                action: 'detail',
                label: '明细',
                type:'primary'
            },{
                icon: 'ios-pause',
                action: 'cancel',
                label: '挂起',
                type:'warning',
                loading:false

            }],
        ]
        private csTable : any = {
            formWidth: 70,
            parentVm: this,
            dataSrc: this.$msPrefix.automation+"/api/v1/data/list/commandTask",
            delSrc: this.$msPrefix.automation+"/api/v1/data/delete/commandTask/",
            batchDelUri: this.$msPrefix.automation+"/api/v1/data/batch/commandTask",
            dataProp: "data.content",
            postMethod: true,
            pageableProp: {
                pageSize: "data.size",
                total: "data.totalElements",
                currentPage: "data.number",
            },
            disableFun:this.buildTable,
           order: "job.startTime,DESC",
           showIndex: true,
            emptyModel:  {
                name:""
            },
            actions: { //表头操作按钮
                replace:false,
                def: [
                    // {
                    //     name: "新建执行任务",
                    //     icon: "md-add",
                    //     type: 'primary',
                    //     action: () => {
                    //         this.addModel();
                    //     }
                    // },
                    // {
                    //     name: "删除",
                    //     icon: "md-trash",
                    //     type: 'error',
                    //     action: () => {
                    //         (this.$refs.child as any).batchDeleteRequest();
                    //     }
                    // }
                ]
            },
            columns: [
                {
                    type: 'selection',
                    width: 60,
                    align: 'center',
                },{
                    key: 'name',
                    title: '任务名称',
                    align: 'center',
                    ellipsis: true,
                    tooltip: true,
                    sortable:'custom'
                }, {
                    key: 'command',
                    title: '命令',
                    align: 'center',
                    ellipsis: true,
                    tooltip: true,
                    sortable:'custom'
                } ,{
                    key: 'executeType',
                    title: '执行类型',
                    align: 'center',
                    ellipsis: true,
                    tooltip: true,
                    sortable:'custom',
                    render: (h, params) => {
                    let value=params.row.job.executeType;
                    console.log("status",value);
                    switch (value) {
                        case "RUNNING_EXE_TYPE":value = "立即执行";break;
                        default:value="调度执行";
                    }
                    return h('span',value)
                }
                } ,{
                    key: 'job.startTime',
                    title: '开始时间',
                    align: 'center',
                    ellipsis: true,
                    tooltip: true,
                    sortable:'custom',
                    render: (h, params) => {
                        let value=params.row.job.startTime;
                        return h('span',value)
                    }
                } ,{
                    key: 'job.endTime',
                    title: '结束时间',
                    align: 'center',
                    ellipsis: true,
                    tooltip: true,
                    sortable:'custom',
                    render: (h, params) => {
                        let value=params.row.job.endTime;
                        return h('span',value)
                    }
                } ,{
                    key: 'job.status',
                    title: '状态',
                    align: 'center',
                    ellipsis: true,
                    tooltip: true,
                    sortable:'custom',
                    render: (h, params) => {
                        let value=params.row.job.status;
                        console.log("status",this.statusMap[value]);
                        return h('span',this.statusMap[value])
                    }
                },
                {
                    title: '操作',
                    key: 'action',
                    width:200,
                    align: 'left',
                    render: (h, params) => {
                        let clickEvent = this.clickEvent;
                        return h('div', [
                            h('CsButton', {
                                props: {
                                    actions: params.row.actions,
                                    click: clickEvent,
                                    data: params.row,
                                    size:"small",
                                    styleCss:"marginRight:5px"
                                },
                            })
                        ]);
                    }
                }]
        }

        buildTable(table){
            table.forEach(item=>{
                let index = item.executeType=='RECURRING_EXE_TYPE' ? ( item.job.status=='3' ? 1 : 2) : 0;
                item.actions=this.actions[index];
            })
        }

        clickEvent(name:string, obj:any,index : number, action : any) {
          if(name == 'detail'){
                let data=_.cloneDeep(obj);
                if("RUNNING_EXE_TYPE"==data.executeType){
                    this.modelFlag=!0;
                    this.$nextTick(()=>{
                        (this.$refs.result as any).postTableData(data.job.id,data.command,true);
                    })
                }else{
                    this.recurringFlag = !0;
                    (this.$refs.result2 as any).postTableData(data.job.id,data.command,true);
                }

            }else if(name == "cancel"){
              action.loading=true;
              this.getApiData("post", this.$msPrefix.automation + "/api/v1/command/cancel",obj, res => {
                    if(res.rtnCode==0){
                      this.$tools.message('success', '挂起任务成功！')
                    }else{
                        this.$tools.error('error', '挂起任务失败！')
                    }
                    (this.$refs.child as any).getData();
                   action.loading=false;
                  },
                  err => {
                      this.$tools.error('error', '挂起任务失败！')
                      action.loading=false;
                  });
            }else if(name == "resume"){
              action.loading=true;
              this.getApiData("post", this.$msPrefix.automation + "/api/v1/command/resume",obj, res => {
                      if(res.rtnCode==0){
                          this.$tools.message('success', '恢复任务成功！')
                      }else{
                          this.$tools.error('error', '恢复任务失败！')
                      }
                      (this.$refs.child as any).getData();
                      action.loading=false;
                  },
                  err => {
                      this.$tools.error('error', '恢复任务失败！')
                      action.loading=false;
                  });
            }

        }

        getPostData() {
            var data = _.cloneDeep(this.model);
            var postData  : any = {};
            this.filterData(postData, data);
            if(data.timerange[0] && data.timerange[1]) {
                postData["job.startTimeBetween"] = [formatDateTime(new Date(data.timerange[0]), 'yyyy-MM-dd hh:mm:ss')+","+formatDateTime(new Date(data.timerange[1]), 'yyyy-MM-dd hh:mm:ss')];
                delete postData.timerange
            }

            if(postData.status){
                var status : any = postData.status[0].split(",");
                if (status != ""){
                    postData["job.status"]=status;
                }
                delete postData.status;
            }
            this.csTable.postData = postData;
        }
        filterData(postData, data) {
            var keys = Object.keys(data);
            keys.forEach((item) => {
                if([0,false].includes(data[item])||(data[item]&&data[item])){
                    postData[item] = [""+data[item]]
                }
            })
        }

        searchTable(){
            this.getPostData();
            (this.$refs.child as any).getData();
        }


        addModel(){
           (this.$refs.child as any).formInfo.title =  "新建执行任务";
            (this.$refs.child as any).formInfo.action = "save";
            (this.$refs.child as any).formInfo.model = {};
            (this.$refs.child as any).dialogVisible = true;
        }

        closeModal(){
            ((this.$refs.result as any).$refs.child as any).tableData=[];
            (this.$refs.result as any).clearTime();
            this.modelFlag=!1;
        }

        closeModalRecurring(){
            ((this.$refs.result2 as any).$refs.child as any).tableData=[];
            this.recurringFlag=!1;
        }

        // setCancelLoading(){
        //     return this.cancelLoading;
        // }
        // setResumeLoading(){
        //     return this.resumeLoading;
        // }

    }
</script>
