const NEW_ESTABLISH_TASK = {}

var scriptGroupID

var NEW_USER_NAME = {}

var windowUser = 'Administrator', linuxUser = "root"

let scriptTypeCode = { 1: 'shell', 2: 'bat', 3: 'perl', 4: 'python', 5: 'Powershell' };

let system = '自动发现'

let addOrEdite;

var editor = CodeMirror.fromTextArea($("#code2")[0], { //script_once_code为你的textarea的ID号
    lineNumbers: true,//是否显示行号
    mode: "python",　//默认脚本编码
    lineWrapping: true, //是否强制换行
    autofocus: true
});
editor.setOption("theme", 'ambiance')
editor.setOption("mode", "python")

var newTaskParam = {}
$(".open-new-script").on("click", function() {
    $(".bs-establish-modal-lg").modal("show")
    $("#form4_demo1").find("input").eq(0).val('')
    $("#form4_demo1").find("input").eq(1).val('')
    $("#form4_demo1").find("input").eq(2).val('')
    $("#form4_demo1").find("input").eq(3).val('-1')
    editor.setValue("")
    editor.refresh()
})

$(".new-establish-script").on("click", newEstablishScript)

var $selectedScript = $("#table_demo2 tbody").find(".delete-task");
$selectedScript.on("click", function () {
    var findname = $(this).data("name")
    post("mission/deleteMission/", JSON.stringify({ "findName": findname })).then(info => {
        console.log(info)
    })
})

getWindowHeight()
$(window).resize(getWindowHeight)

$(".bs-establish-modal-lg").on("shown.bs.modal", function( ) {
    editor.refresh()
})

updataTree()


function updataTree() {
    $.ajax({
        url: "script/getScriptGroup",
        type: "get",
        dataType: "json",
        success: function (info) {
            console.log(info)
            var data = info.data.scriptGroup
            scriptGroupID = data[0].children[0].id
            var template = createTree(data) 
            
            $('#plugin12_demo2 ul').html(template) 
            treeEvent()
            updateTable($("#table_script_list"), info.data.scriptGroup[0].children[0].id)
        }
    })
}

function treeEvent() {
    $("#plugin12_demo2 .list-group .group-script").on("click", function(e) {
        // alert($(this).data("nodeid"))
        e.stopPropagation()
        if($(this).next()[0].style.display == 'none') {
            $(this).find("span").removeClass('glyphicon glyphicon-chevron-up').addClass("glyphicon glyphicon-chevron-down")
        } else {
            $(this).find("span").removeClass('glyphicon glyphicon-chevron-down').addClass("glyphicon glyphicon-chevron-up")
        }
        
        $(this).next().slideToggle()
    })
    $("#plugin12_demo2 .list-group").on("click", "a", function() {
        $("#plugin12_demo2 .list-group").find("a").removeClass("group-active")
        $(this).addClass("group-active")
    })

    $("#plugin12_demo2 .list-group").on("mouseover", "a", function() {
        $(this).children(".opt").show()
    })

    $("#plugin12_demo2 .list-group").on("mouseout", "a", function() {
        $(this).children(".opt").hide()
    })
}
 

//编辑脚本
function editeScript(e, infoid, infoname, groupname, groupid) {
    addOrEdite = 1
    e.stopPropagation()
    var option = [{id: groupid, name: groupname}]
    
    var tem = selecedOption(option)
    $("#exite-script-group").html(tem)
        
    $("#plugin12_demo2").hide(200, function() {
        $(".edite-adding-script").show()
    })

    $(".el-input__inner").val(infoname)
    $(".el-input__inner").attr("id", infoid)
}   

//删除脚本
function deleteScript(e, id) {
    e.stopPropagation()
    var tag = confirm("确定删除此脚本组吗？")
    if(tag) {
        post("script/deleteScriptGroup/",JSON.stringify({scriptGroupID: id})).then(info => {
            if(info.result) {
                toastr["success"](info.message)
                updataTree()
            } else {
                toastr["warning"](info.message)
            }
        })
    }
    
}

function getScript(id) {
    // alert(id)
    updateTable($("#table_script_list"), id)
    scriptGroupID = id;
}
 
$(".bs-establish-modal-lg").on("hide.bs.modal", function () {
    editor.setValue("")
})



//面包屑导航
$('#myTab2 a').click(function (e) {
    e.preventDefault()
    var title = $(this).data('title')
    $(".king-page-topbar li.active").html(title)
    switch(title) {
        case "发现任务":
            vm.$data.isDetail = false;
            vm.$data.isResult = false;
            break;
    }
})

//新增
$(".add-script-group").on("click", function() {
    addOrEdite = 0
    get("script/getScriptGroup").then(info => {
        if(info.result) {
            var tem = selecedOption(info.data.scriptGroup)
            $("#exite-script-group").html(tem)
        }
    })
    $("#plugin12_demo2").hide(200, function() {
        $(".edite-adding-script").show()
    })
    
})

//

$(".search-btn").on("click", function() {
    search()
})

$(".search-input-ku").on("keyup", function(e) {
    if(e.keyCode == 13) {
        search()
    }
})

function search() {
    var keyword = $(".search-input-ku").val()
    console.log(keyword)
    $(".script-list table tbody tr").each(function() {
        
        var scriptName = $(this).data("name")
        if(scriptName.indexOf(keyword) > -1) {
            $(this).show()
        } else {
            $(this).hide()
        }
    })
}

function cancelAdd() {
    $(".edite-adding-script").hide(100, function() {
        $("#plugin12_demo2").show()
    })
}

// script/addScriptGroup/
function comfirmAdd() {
    var url = ""
    if(addOrEdite == 0) {
        url = "script/addScriptGroup/"
    } else {
        url = "script/updateScriptGroup/"
    }
    var parentID = $("#exite-script-group").val()
    var scriptGroupName = $(".el-input__inner").val() 
    var scriptGroupID = $(".el-input__inner").attr('id') 
    if(scriptGroupName == '') {
        $(".validata-name").show()
    } else {
        var param
        if(addOrEdite == 0) {
            param = {parentID: parentID, scriptGroupName: scriptGroupName}
        } else {
            param = {parentID: parentID, scriptGroupName: scriptGroupName, scriptGroupID: scriptGroupID}
        }
        post(url, JSON.stringify(param)).then(info => {
            console.log(info)
            if(info.result) {
                toastr['success'](info.message)
                cancelAdd()
                updataTree()
                $(".el-input__inner").val('') 
            } else {
                $(".validata-name").html(info.message).show() 
            }
        })
    }
    
}

function validataName(e) {
    var el = e.target
    if($(el).val() !== '') {
        $(".validata-name").hide()
    }

}

function newEstablishScript () {
    var param = {};
    var url
    var eleInput = $(".select-script-type-new").find("input")
    for (var i = 0; i < eleInput.length; i++) {

        if (eleInput.eq(i).prop("checked")) {
            param.scriptType = eleInput.eq(i).data('val')
        }
    }
    param.name = $("#form4_demo1").find("input").eq(0).val()

    param.description = $("#form4_demo1").find("input").eq(1).val()
    param.scriptText = editor.getValue()
    param.inputParam = null
    param.outParam = null;
    param.createUser = $(".user-name").text()
    param.groupID = scriptGroupID;
    if ($("#form4_demo1").find("input").eq(3).val() != -1) {
        param.scriptID = $("#form4_demo1").find("input").eq(2).val()
        url = 'script/updateScript/'
    } else {
        url = 'script/addScript/'
    }

    post(url, JSON.stringify(param)).then(info => {
        if (info.result) {
            updateTable($("#table_script_list"), scriptGroupID)
            $(".bs-establish-modal-lg").modal("hide")
            $("#form4_demo1").find("input").eq(0).val('')
            $("#form4_demo1").find("input").eq(1).val('')
            $("#form4_demo1").find("input").eq(2).val('')
            $("#form4_demo1").find("input").eq(3).val('-1')
            editor.setValue("")
            editor.refresh()
            toastr["success"]("<br>当前提示类型：" + info.message)
        }
    })
}

function getWindowHeight() {
    var h = document.documentElement.offsetHeight || document.body.offsetHeight;
    $(".king-page-box").height(h - 51)
}

function updateTable(el, id) {
    // el.find("tbody tr").remove();
    post("script/getScript/", JSON.stringify({ 'scriptGroupID': id })).then(info => {
        if(info.data.scriptList) {
            $(".inexistence-data").hide()
            var $childEl = template(info.data.scriptList)
            el.find("tbody").html($childEl)
            el.find("tbody .update-script").on("click", function () {

                $(".bs-establish-modal-lg").modal("show")
                editor.focus();
                editor.setValue($(this).find("span").text())

                $("#form4_demo1").find("input").eq(0).val($(this).data("name"))
                // $("#form4_demo1").find("input").eq(1).val($(this).data("scripttype"))
                $("#form4_demo1").find("input").eq(1).val($(this).data("description"))
                $("#form4_demo1").find("input").eq(2).val($(this).data("scriptid"))
                $("#form4_demo1").find("input").eq(3).val('0')
                $(".select-script-type-new").find('input').eq((Number($(this).data("scripttype")) - 1)).prop("checked", true)
            })
            el.find("tbody .delete-script").on("click", function () {
                var a = confirm("确定删除此脚本吗？")
                console.log(a)
                if (a) {
                    post("script/deleteScript/", JSON.stringify({ "scriptID": $(this).data("scriptid") })).then(info => {
                        if (info.result) {
                            updateTable($("#table_script_list"), scriptGroupID)
                            toastr['info']('<br>当前提示类型：' + info.message);
                        }
                    })
                }

            })
        }else {
            el.find("tbody").html('')
            $(".inexistence-data").show()
            toastr['info']('<br>当前提示类型：' + info.message);
        }
    })
}


function transfromData(arr) {
    var temArr = []
    for (var i = 0; i < arr.length; i++) {
        var temObj = { text: "", href: "", groupID: "", tags: [], nodes: [] }
        temObj.text = arr[i].name
        temObj.groupID = arr[i].id
        temObj.href = "#" + arr[i].id
        temObj.tags.push(arr[i].children.length)
        for (var j = 0; j < arr[i].children.length; j++) {
            var temObj1 = { text: "", href: "", tags: [], node: [] }
            temObj1.text = arr[i].children[j].name
            temObj1.href = "#" + arr[i].children[j].id
            temObj1.groupID = arr[i].children[j].id
            temObj.nodes.push(temObj1)
        }
        temArr.push(temObj)
    }
    return temArr
}

function addScriptGroup(node) {
    
}



//优化脚本库的代码

function CodeLib() {
    this.newConstruct = $(".open-new-script")  //新建脚本
    this.tbody = $(".script-list table tbody")
    this.editeScript = 0
    this.formInput = $("#form4_demo1").find("input")
    this.modalDialog = $(".bs-establish-modal-lg")
    this.confirmEdite = $(".new-establish-script")
    this.selectScript = $(".select-script-type-new").find("input")
}

CodeLib.prototype = {
    constructor: CodeLib,
    init() {
        this.addEvent()
    },
    addEvent() {
        var that = this
        this.newConstruct.on("click", this.addScript.bind(that))
        this.confirmEdite.on("click", this.confirmAddScript.bind(that))
        this.tbody = $(".script-list table tbody").on("click", '.update-script', )
    },
    addScript() {
        // console.log("haha")
        $(".bs-establish-modal-lg").modal("show")
        // for (var i = 0; i < this.formInput.length; i++) {
        //     this.formInput.eq(i).val("1")
        // }
        this.editeScript = 
        this.clearValue(this.formInput)
        editor.setValue("")
        editor.refresh()
    },
    clearValue(nodes) {
        for (var i = 0; i < nodes.length; i++) {
            nodes.eq(i).val("")
        }
    },
    confirmAddScript() {
        var param = {};
        var url
        // var eleInput = $(".select-script-type-new").find("input")
        for (var i = 0; i < this.selectScript.length; i++) {

            if (this.selectScript.eq(i).prop("checked")) {
                param.scriptType = this.selectScript.eq(i).data('val')
            }
        }
        param.name = this.formInput.eq(0).val()

        param.description = this.formInput.eq(1).val()
        param.scriptText = editor.getValue()
        param.inputParam = null
        param.outParam = null;
        param.createUser = $(".user-name").text()
        param.groupID = scriptGroupID;
        if (this.editeScript == -1) {
            param.scriptID = this.formInput.eq(2).val()
            url = 'script/updateScript/'
        } else {
            url = 'script/addScript/'
        }

        post(url, JSON.stringify(param)).then(info => {
            if (info.result) {
                updateTable($("#table_script_list"), scriptGroupID)
                this.modalDialog.modal("hide")
                this.clearValue(this.formInput)
                editor.setValue("")
                editor.refresh()
                toastr["success"]("<br>当前提示类型：" + info.message)
            }
        })
    },
    updateScript() {
        $(".bs-establish-modal-lg").modal("show")
        editor.focus();
        editor.setValue($(this).find("span").text())

        $("#form4_demo1").find("input").eq(0).val($(this).data("name"))
        // $("#form4_demo1").find("input").eq(1).val($(this).data("scripttype"))
        $("#form4_demo1").find("input").eq(1).val($(this).data("description"))
        $("#form4_demo1").find("input").eq(2).val($(this).data("scriptid"))
        $("#form4_demo1").find("input").eq(2).val('0')
        $(".select-script-type-new").find('input').eq((Number($(this).data("scripttype")) - 1)).prop("checked", true)
    },
    updateTable() {
        post("script/getScript/", JSON.stringify({ 'scriptGroupID': id })).then(info => {
            var $childEl = template(info.data.scriptList)
            el.find("tbody").html($childEl)
            el.find("tbody .update-script").on("click", function () {
    
                
            })
            el.find("tbody .delete-script").on("click", function () {
                var a = confirm("确定删除此脚本吗？")
                console.log(a)
                if (a) {
                    post("script/deleteScript/", JSON.stringify({ "scriptID": $(this).data("scriptid") })).then(info => {
                        if (info.result) {
                            updateTable($("#table_script_list"), scriptGroupID)
                            toastr['info']('<br>当前提示类型：' + info.message);
                        }
                    })
                }
    
            })
        })
    }
}

// var codelib = new CodeLib
// codelib.init()


var vm = new Vue({
    el: "#demo1",
    data: {
        findexcuteList: [],
        isDetail: false,
        machineList: [],
        detail: {},
        excuteResultInfo: [],
        isResult: false,
        stateCode: {
            0: '正在执行', 1: '未执行', 2: '正在执行', 3: '执行成功', 4: '执行失败', 5: '跳过',
            6: '忽略错误', 7: '等待用户', 8: '手动结束', 9: '状态异常',
            10: '步骤强制终止中', 11: '步骤强制终止成功', 12: '步骤强制终止失败'
        },
        scriptTypeCode: { 1: 'shell', 2: 'bat', 3: 'perl', 4: 'python', 5: 'Powershell' },
        total: 150,     // 记录总条数
        display: 50,   // 每页显示条数
        current: 1,   // 当前的页数
        loadingList: false,
        taskID: ''
    },
    methods: {
        get(url) {
            return new Promise((resolve, reject) => {
                $.ajax({
                    url: url,
                    dataType: "json",
                    type: "get",
                    success: function (info) {
                        resolve(info)
                    },
                    error: function (err) {
                        reject(err)
                    }
                })
            })
        },
        post(url, param) {
            return new Promise((resolve, reject) => {
                $.ajax({
                    url: url,
                    data: param,
                    type: "post",
                    dataType: "json",
                    before: function (xhr) {
                        xhr.setRequestHeader("Content-Type", "application/json;");
                    },
                    success: function (info) {
                        resolve(info)
                    },
                    error: function (err) {
                        reject(err)
                    }
                })
            })
        },
        excute(name) {
            var t = confirm("是否启动任务？")

            this.commitOp("mission/enableMission/", JSON.stringify({ "findName": name }), t)
        },
        updateTable() {
            this.loadingList = true
            this.post("mission/getMissionList/", JSON.stringify({ "currentPage": this.current })).then(info => {
                console.log("info", info)
                this.findexcuteList = info.data.display_list
                this.total = info.data.count
                this.loadingList = false;
            }).catch(err => {
                console.log(err)
            })
        },
        stopTask(name) {
            var t = confirm("是否停止任务？")

            this.commitOp("mission/disableMission/", JSON.stringify({ "findName": name }), t)
            // swal({
            //     title: '确定删除吗？', 
            //     text: '你将无法恢复它！', 
            //     type: 'warning',
            //     showCancelButton: true, 
            //     confirmButtonColor: '#3085d6',
            //     cancelButtonColor: '#d33',
            //     confirmButtonText: '确定！', 
            //     cancelButtonText: '取消！',
            //     confirmButtonClass: 'btn btn-success',
            //     cancelButtonClass: 'btn btn-danger',
            //     buttonsStyling: false
            //   }).then(function() {
            //     swal(
            //       '已删除！',
            //       '你的文件已经被删除。',
            //       'success'
            //     ); 
            //   }, function(dismiss) {
            //     // dismiss的值可以是'cancel', 'overlay',
            //     // 'close', 'timer'
            //     if (dismiss === 'cancel') {
            //       swal(
            //         '已取消！',
            //         '你的虚拟文件是安全的:)',
            //         'error'
            //       ); 
            //     } 
            //   })
        },
        deleteTask(name) {
            var t = confirm("是否删除任务？")
            this.commitOp("mission/deleteMission/", JSON.stringify({ "findName": name }), t)
        },
        commitOp(url, param, t) {

            if (t) {
                post(url, param).then(info => {
                    // console.log(info);
                    toastr['info']('<br>当前提示类型：' + info.message, {
                        positionClass: "toast-top-center"
                    });
                    this.updateTable()
                })

            }
        },
        showDetail(item) {
            this.detail = item
            this.loadingList = true;
            this.taskID = item.taskID
            this.post("mission/getTaskAgentList/", JSON.stringify({ "taskID": item.taskID })).then(info => {
                if (!info.result) {
                    toastr["info"]("<br>当前提示类型：当前脚本无任务")
                } else {
                    this.isDetail = true;
                    this.machineList = info.data.displayList
                }
                this.loadingList = false;
            }).catch(err => {
                console.log(err)
            })
        },
        goBack() {
            if (this.isResult) {
                this.isResult = false;
            } else {
                this.isDetail = false;
            }
        },
        excuteResult(item) {
            this.excuteResultInfo = []
            this.isResult = true
            this.loadingList = true
            this.post("mission/getTaskAgentInfo/", JSON.stringify({ 'taskId': this.taskID, 'ip': item.ip })).then(info => {
                // console.log(info)
                // var resultInfo = []
                // resultInfo.push(info.data.result)
                this.excuteResultInfo = info.data
                this.loadingList = false;
            })
        },
        pagechange(current) {
            this.current = current;
            this.updateTable()
        },
        editMission(detail) {
            $(".new-mission").tab("show");
            newBuildTask.$data.isNew = false;
            newBuildTask.$data.newScriptParam = detail;
            newBuildTask.$data.scriptSelected = detail;
            console.log(detail)
        }
    },
    mounted() {
        this.updateTable()
    },
    watch: {
        findexcuteList() {
            toastr['success']('<br>当前提示类型：更新列表');
        }
    }

})