import store from 'store/'
import router from 'router/'
import maincfg from 'api/services/mainconfig'
import folder from 'api/services/folder'
import page from 'api/services/page'
import prog from 'api/services/prog'
import variable from 'api/services/variable'
import database from 'api/services/database'
import device from 'api/services/device'
import channel from 'api/services/channel'
import Vue from 'vue'
import exp from 'api/plugins/exportcsv'
// import config from '../config'
const config = window.config

// import $ from '../global/plugins/jquery.min'
// import bootbox from '../global/plugins/bootstrap/js/bootstrap.min'

export default {
    init,
    loadTree,
    getActivedNode() {
        let node = $(ID).jstree('get_selected', true)[0]
        return node
    },
    getActivedParentNodesWithoutFolder,
    selectNodeByID,
    getNodeByID,
    setUpperConnection,
    UpperEntity
}

// -----------------------------------树的初始化加载，事件绑定---------------------------------
// 初始化树, afterLoad为加载树数据后的回掉方法
let ProjectPK
let UpperEntity = []
let ID = ''

function init(PK, selectedid, afterLoad) {
    UpperEntity = []
    ProjectPK = PK
    const treeData = store.state.company.treeData

    if (!treeData) { // 如果 刷新tree页面 treeData 为null 就从新请求
        maincfg.getConfigData(ProjectPK, (ro) => {
            console.log('当前点击项目PK请求后 tree数据: ', ro)
            loadTree(ro, selectedid)
            if (afterLoad) {
                afterLoad(ro)
            }
        }, (ex) => {
            console.log('ex: ', ex)
            toastr.showError(ex.Message)
        })
    } else {
        loadTree(treeData, selectedid)
        if (afterLoad) {
            afterLoad(treeData)
        }
    }
}

const FilterPKObj = (pks, ObjKeyName, ClassKeyName, data) => { // 检索数据 返回数组
    const arr = []
    pks.forEach(pk => {
        data[ClassKeyName] && data[ClassKeyName].forEach((obj) => {
            if (pk === obj[ObjKeyName]) {
                arr.push(obj)
            }
        })
    })
    return arr
}

const FilterTreedata = (treedata) => { // 根据当前点击项目的PK 过滤所有tree数据
    if (ProjectPK) {
        treedata.Uppers.forEach(obj => {
            if (obj.PK_PROJECT === ProjectPK) { UpperEntity.push(obj.PK) }
        })
        // console.log('UpperEntity: ', UpperEntity)
    }
    // if (config.site === 'cloud') {
    //     UpperEntity = []
    //     UpperEntity.push(router.currentRoute.params.upperpk)
    // }
    const filterdata = {}
    filterdata.Company = treedata.Company

    filterdata.Folders = FilterPKObj([treedata.Company.PK], 'PK_PARENT', 'Folders', treedata) // 公司下的文件夹
    filterdata.Folders.push(...FilterPKObj(UpperEntity, 'PK_UPPER_ENTITY', 'Folders', treedata)) // 上位机下的文件夹
    filterdata.Folders.push(...FilterPKObj([ProjectPK], 'PK_PARENT', 'Folders', treedata)) // 项目下的文件夹
    // const FolderPKs = []
    // filterdata.Folders.forEach((obj, index) => {
    //     FolderPKs.push(obj.PK)
    // }) // 所有文件夹 的PK

    filterdata.Projects = FilterPKObj([ProjectPK], 'PK', 'Projects', treedata) // 添加项目
    filterdata.Channels = FilterPKObj(UpperEntity, 'PK_UPPER_ENTITY', 'Channels', treedata)
    filterdata.Databases = FilterPKObj([ProjectPK], 'PK_PROJECT', 'Databases', treedata)
    filterdata.Devices = FilterPKObj(UpperEntity, 'PK_UPPER_ENTITY', 'Devices', treedata)
    filterdata.Pages = FilterPKObj(UpperEntity, 'PK_UPPER_ENTITY', 'Pages', treedata)
    filterdata.Programs = FilterPKObj(UpperEntity, 'PK_UPPER_ENTITY', 'Programs', treedata)
    filterdata.Roles = []

    filterdata.Uppers = FilterPKObj([ProjectPK], 'PK_PROJECT', 'Uppers', treedata) // 项目下的上位机
    // filterdata.Uppers.push(...FilterPKObj(FolderPKs, 'PK_FOLDER', 'Uppers', treedata)) // 当前目录所有文件夹下的上位机
    filterdata.Uppers.push(...FilterPKObj([null], 'PK_PROJECT', 'Uppers', treedata))

    filterdata.UserType = treedata.UserType
    filterdata.Users = FilterPKObj([treedata.Company.PK], 'PK_COMPANY', 'Users', treedata)
    filterdata.Variables = FilterPKObj(UpperEntity, 'PK_UPPER_ENTITY', 'Variables', treedata)

    // 当树打不开时 执行下面代码找错

    // filterdata.Variables.forEach(item => {
    //     if (item.PK_FOLDER) {
    //         const isPass = filterdata.Folders.some(model => {
    //             return model.PK === item.PK_FOLDER
    //         })
    //         console.log('isPass: ', isPass, item)
    //     } else if (item.PK_DEVICE) {
    //         const isPass = filterdata.Devices.some(model => {
    //             return model.PK === item.PK_DEVICE
    //         })
    //         console.log('isPass: ', isPass, item)
    //     } else if (item.PK_UPPER_ENTITY) {
    //         const isPass = filterdata.Uppers.some(model => {
    //             return model.PK === item.PK_UPPER_ENTITY
    //         })
    //         console.log('isPass: ', isPass, item)
    //     } else {
    //         console.log('item: 三无', item)
    //     }
    // })
    // filterdata.Devices.forEach(item => {
    //     if (item.PK_FOLDER) {
    //         const isPass = filterdata.Folders.some(model => {
    //             return model.PK === item.PK_FOLDER
    //         })
    //         console.log('isPass: ', isPass, item)
    //     } else if (item.PK_CHANNEL) {
    //         const isPass = filterdata.Channels.some(model => {
    //             return model.PK === item.PK_CHANNEL
    //         })
    //         console.log('isPass: ', isPass, item)
    //     } else if (item.PK_UPPER_ENTITY) {
    //         const isPass = filterdata.Uppers.some(model => {
    //             return model.PK === item.PK_UPPER_ENTITY
    //         })
    //         console.log('isPass: ', isPass, item)
    //     } else {
    //         console.log('item: 三无', item)
    //     }
    // })
    // filterdata.Channels.forEach(item => {
    //     if (item.PK_FOLDER) {
    //         const isPass = filterdata.Folders.some(model => {
    //             return model.PK === item.PK_FOLDER
    //         })
    //         console.log('isPass: ', isPass, item)
    //     } if (item.PK_UPPER_ENTITY) {
    //         const isPass = filterdata.Uppers.some(model => {
    //             return model.PK === item.PK_UPPER_ENTITY
    //         })
    //         console.log('isPass: ', isPass, item)
    //     } else {
    //         console.log('item: 三无', item)
    //     }
    // })
    // filterdata.Folders.forEach(item => {
    //     if (item.PK_PARENT) {
    //         const isPass = filterdata.Folders.some(model => {
    //             return model.PK === item.PK_PARENT
    //         })
    //         if (!isPass) {
    //             const hasDevice = filterdata.Devices.some(model => {
    //                 return model.PK === item.PK_PARENT
    //             })
    //             if (!hasDevice) {
    //                 const hasChannel = filterdata.Channels.some(model => {
    //                     return model.PK === item.PK_PARENT
    //                 })
    //                 if (!hasChannel) {
    //                     const hasUpper = filterdata.Uppers.some(model => {
    //                         return model.PK === item.PK_PARENT
    //                     })
    //                     if (!hasUpper) {
    //                         console.log('没有hasUpper: ', hasUpper, item)
    //                     } else {
    //                         console.log('有hasUpper: ', hasUpper, item)
    //                     }
    //                 } else console.log('hasChannel: ', hasChannel, item)
    //             } else console.log('hasDevice', hasDevice, item)
    //         } else console.log('isPass: folder', isPass, item)
    //     } else {
    //         console.log('item: 无PK_PARENT', item)
    //     }
    // })
    return filterdata
}

function loadTree(treedata, selectedid, treeID, callback) {
    callback && callback(UpperEntity)
    let data = []
    let hidedata = []

    const filtedData = FilterTreedata(treedata)
    console.log('filtedData: ', filtedData)
    initData(filtedData, data, hidedata)
    console.log('data: ', data)
    ID = treeID || '#tree'
    console.log('ID: ', ID)

    $(ID).jstree('destroy')
    $(ID).jstree({
            'core': {
                'themes': {
                    'responsive': false // ,
                        // 'variant': 'large'
                },
                // so that create works
                'check_callback': checkCallbackWhenDnd,
                'data': data, // 这里后续考虑吧data还存在local storge中
                'error': function(e) {
                    // console.log(e)
                }
            },
            'contextmenu': {
                items: createTreeContextMenu
            },
            // 'state': { 'key': 'demo2' },
            'dnd': {
                check_while_dragging: true
                    // use_html5: true
            },
            'plugins': ['contextmenu', 'dnd', 'state', 'types']
        })
        .on('ready.jstree', function() {
            if (selectedid) {
                selectNodeByID(selectedid)
            } else {
                let currentnode = $(ID).jstree('get_selected', true)[0]
                clicknode(currentnode)
            }
        })
        .on('loaded.jstree', function() {})
        .on('activate_node.jstree', function(e, data) {
            clicknode(data.node)
        })
        .on("move_node.jstree", moveNode)
        .on('select_node.jstree', (event, data) => {  // 选中节点（单选/多选）事件
            // data.selected.forEach(item => {
            //     const parent = $.jstree.reference(ID).get_parent(item)
            //     console.log('parent: ', parent)
            // })
        })
}

// 初始化数据
function initData(treedata, data, hidedata) {
    // 创建公司
    let company = treedata.Company
    // console.log('company: ', company)
    let jcompany = {
        id: company.PK,
        parent: '#',
        text: company.SCOMPANYNAME,
        icon: 'fa fa-bank font-purple',
        state: {
            opened: true,
            disabled: false,
            selected: false
        },
        li_attr: {},
        a_attr: {},
        model: company,
        modeltype: 'company'
    }
    data.push(jcompany)

    // 创建用户根目录
    let juser = {
        id: 'userroot',
        parent: '#',
        text: '用户',
        icon: '',
        model: null,
        modeltype: 'userroot'
    }
    data.push(juser)

    // 创建角色根目录
    let jrole = {
        id: 'roleroot',
        parent: '#',
        text: '角色',
        icon: '',
        model: null,
        modeltype: 'roleroot'
    }
    data.push(jrole)

    // 创建文件夹
    for (let i = 0; i < treedata.Folders.length; i++) {
        let m = treedata.Folders[i]
        let parentid = m.PK_PARENT
        if (m.BISUSER && m.PK_PARENT === '00000000-0000-0000-0000-000000000000') { parentid = 'userroot' }
        if (m.BISROLE && m.PK_PARENT === '00000000-0000-0000-0000-000000000000') { parentid = 'roleroot' }
        let j = {
                id: m.PK,
                parent: parentid,
                text: m.SFOLDERNAME,
                icon: 'fa fa-folder font-yellow',
                model: m,
                modeltype: 'folder'
            }
            // data.push(j)
        if (m.DR) { hidedata.push(m.PK) } else { data.push(j) }
    }

    // 创建上位机
    for (let i = 0; i < treedata.Uppers.length; i++) {
        let m = treedata.Uppers[i]
        let parent = ''
        if (m.PK_FOLDER == null) {
            if (m.PK_PROJECT == null) {
                parent = m.PK_COMPANY
            } else {
                parent = m.PK_PROJECT
            }
        } else {
            parent = m.PK_FOLDER
        }
        let j = {
            id: m.PK,
            parent: parent,
            text: m.SUPPERNAME + ' (' + m.SUPPERCODE + ')',
            icon: 'fa fa-circle-o font-red',
            model: m,
            modeltype: 'upper'
        }
        data.push(j)
        if (m.DR) { hidedata.push(m.PK) }
    }

    // 创建项目
    for (let i = 0; i < treedata.Projects.length; i++) {
        let project = treedata.Projects[i]
        let parent = ''
        if (project.PK_FOLDER == null) {
            parent = project.PK_COMPANY
        } else {
            parent = project.PK_FOLDER
        }
        let jproject = {
            id: project.PK,
            parent: parent,
            text: project.SPROJNAME,
            icon: 'fa fa-sitemap grey-gallery',
            model: project,
            modeltype: 'project'
        }
        data.push(jproject)
        if (project.DR) { hidedata.push(project.PK) }
    }

    // 创建通道
    for (let i = 0; i < treedata.Channels.length; i++) {
        let m = treedata.Channels[i]
        let parent = ''
        if (m.PK_FOLDER == null) {
            parent = m.PK_UPPER_ENTITY
        } else {
            parent = m.PK_FOLDER
        }
        let j = {
            id: m.PK,
            parent: parent,
            text: m.Protocol.SPROTOCOLNAME + ' - ' + m.SCHANNELCODE + ' (' + m.SCHANNELNAME + ')',
            icon: 'fa fa-arrow-right font-blue',
            model: m,
            modeltype: 'channel'
        }
        data.push(j)
        if (m.DR) { hidedata.push(m.PK) }
    }

    // 创建设备
    for (let i = 0; i < treedata.Devices.length; i++) {
        let m = treedata.Devices[i]
        let parent = ''
        if (m.PK_FOLDER == null) {
            parent = m.PK_CHANNEL
        } else {
            parent = m.PK_FOLDER
        }
        let j = {
            id: m.PK,
            parent: parent,
            text: m.SDEVICECODE + ' (' + m.SDEVICENAME + ')',
            icon: 'fa fa-codepen icon-state-danger',
            model: m,
            modeltype: 'device'
        }
        data.push(j)
        if (m.DR) { hidedata.push(m.PK) }
    }

    // 创建变量
    for (let i = 0; i < treedata.Variables.length; i++) {
        let m = treedata.Variables[i]
        let parent = ''
        if (m.PK_FOLDER == null) {
            if (m.PK_DEVICE === null) {
                parent = m.PK_UPPER_ENTITY
            } else {
                parent = m.PK_DEVICE
            }
        } else {
            parent = m.PK_FOLDER
        }
        let j = {
            id: m.PK,
            parent: parent,
            text: m.SVARCODE + ' (' + m.SVARNAME + ')',
            icon: 'fa fa-link font-purple',
            model: m,
            modeltype: 'variable',
            data: {
                varcategory: m.SVARCATEGORY
            }
        }
        // console.log('j.varcategory: ', j.varcategory)
        data.push(j)
        if (m.DR) { hidedata.push(m.PK) }
    }

    // 创建页面
    for (let i = 0; i < treedata.Pages.length; i++) {
        let m = treedata.Pages[i]
        let parent = ''
        if (m.PK_FOLDER == null) {
            parent = m.PK_UPPER_ENTITY
        } else {
            parent = m.PK_FOLDER
        }
        let j = {
            id: m.PK,
            parent: parent,
            text: m.SPAGECODE + ' (' + m.SPAGENAME + ')',
            icon: 'fa fa-file font-green',
            model: m,
            modeltype: 'page'
        }
        data.push(j)
        if (m.DR) { hidedata.push(m.PK) }
    }

    // 创建数据库
    for (let i = 0; i < treedata.Databases.length; i++) {
        let database = treedata.Databases[i]
        let parent = ''
        if (database.PK_FOLDER == null) {
            if (database.PK_PROJECT === null) {
                parent = database.PK_COMPANY
            } else {
                parent = database.PK_PROJECT
            }
        } else {
            parent = database.PK_FOLDER
        }
        let j = {
            id: database.PK,
            parent: parent,
            text: database.SDBNAME,
            icon: 'fa fa-database icon-state-danger',
            model: database,
            modeltype: 'database'
        }
        data.push(j)
        if (database.DR) { hidedata.push(database.PK) }
    }

    // 创建程序
    for (let i = 0; i < treedata.Programs.length; i++) {
        let m = treedata.Programs[i]
        let parent = ''
        if (m.PK_FOLDER == null) {
            parent = m.PK_UPPER_ENTITY
        } else {
            parent = m.PK_FOLDER
        }
        let j = {
            id: m.PK,
            parent: parent,
            text: m.SPROGCODE,
            icon: 'fa fa-file-code-o blue-chambray',
            model: m,
            modeltype: 'program'
        }
        data.push(j)
        if (m.DR) { hidedata.push(m.PK) }
    }
}

// 构建树的右键菜单
function createTreeContextMenu(o, cb) {
    let actions = {}

    var modeltype = o.original.modeltype
    var foldereditstatues = true
    switch (modeltype) {
        case 'company':
            actions.createproject = {
                separator_before: false,
                separator_after: false,
                label: '新建项目',
                icon: '',
                action: createProject
            }
            // actions.buyupper = {
            //     separator_before: false,
            //     separator_after: true,
            //     label: '购买上位机',
            //     icon: '',
            //     action: buyItem
            // }
            actions.createdatabase = {
                separator_before: false,
                separator_after: true,
                label: '新建数据库',
                icon: '',
                action: createDatabase
            }
            break
        case 'project':
            actions.createdatabase = {
                separator_before: false,
                separator_after: true,
                label: '新建数据库',
                icon: '',
                action: createDatabase
            }
            actions.deleteproject = {
                separator_before: false,
                separator_after: true,
                label: '删除项目',
                icon: '',
                action: ''
            }
            break
        case 'userroot':
            actions.createuser = {
                separator_before: false,
                separator_after: false,
                label: '新建用户',
                icon: '',
                action: ''
            }
            break
        case 'roleroot':
            actions.createrole = {
                separator_before: false,
                separator_after: false,
                label: '新建角色',
                icon: '',
                action: ''
            }
            break
        case 'upper':
            // 上位机层级，可以 增加通道
            actions.createchannel = {
                separator_before: false,
                separator_after: false,
                label: '建立通讯通道',
                icon: '',
                action: createChannel
            }
            actions.createpage = {
                separator_before: false,
                separator_after: false,
                label: '新建页面',
                icon: '',
                action: createPage
            }
            actions.createprogram = {
                separator_before: false,
                separator_after: false,
                label: '新建程序',
                icon: '',
                action: createProgram
            }
            actions.createinnervariable = {
                separator_before: false,
                separator_after: false,
                label: '新建内部变量',
                icon: '',
                action: createInnerVariable
            }

            actions.createwarningvariable = {
                separator_before: false,
                separator_after: true,
                label: '新建报警变量',
                icon: '',
                action: createWarningVariable
            }

            actions.deleteallinnervariable = {
                separator_before: false,
                separator_after: true,
                label: '清空内部变量',
                icon: '',
                action: deleteAllInnerVariable
            }
            actions.resetupperentity = {
                separator_before: false,
                separator_after: true,
                label: '重置上位机',
                icon: '',
                action: resetUpperEntity
            }
            break
        case 'channel':
            actions.createdevice = {
                separator_before: false,
                separator_after: true,
                label: '建立设备',
                cmd: 'add',
                icon: '',
                action: createDevice
            }
            actions.deletechannel = {
                separator_before: false,
                separator_after: true,
                label: '删除通讯通道',
                icon: '',
                action: deleteChannel
            }
            break
        case 'device':
            actions.createvariable = {
                separator_before: false,
                separator_after: false,
                label: '新建变量',
                icon: '',
                action: createVariable
            }
            actions.deletedevice = {
                separator_before: false,
                separator_after: true,
                label: '删除设备',
                icon: '',
                action: deleteDevice
            }
            actions.exportvarbtemplate = {
                separator_before: false,
                separator_after: true,
                label: '导出变量模板',
                icon: '',
                action: exportVarbTemplate
            }
            actions.exportvarb = {
                separator_before: false,
                separator_after: true,
                label: '导出所有变量',
                icon: '',
                action: exportVarb
            }
            actions.inportvarbtemplate = {
                separator_before: false,
                separator_after: true,
                label: '导入变量',
                icon: '',
                action: inportVarbTemplate
            }
            break
        case 'variable':
            actions.createvariable2 = {
                separator_before: false,
                separator_after: false,
                label: '新建变量',
                icon: '',
                action: createVariable2
            }
            actions.deletevariable = {
                separator_before: false,
                separator_after: true,
                label: '删除变量',
                icon: '',
                action: deleteVariable
            }
            break
        case 'database':
            actions.deletedatabase = {
                separator_before: false,
                separator_after: true,
                label: '删除数据库',
                icon: '',
                action: deleteDatabase
            }
            break
        case 'page':
            actions.deletepage = {
                separator_before: false,
                separator_after: true,
                label: '删除页面',
                icon: '',
                action: deletePage
            }
            actions.exportpage = {
                separator_before: false,
                separator_after: true,
                label: '导出当前页面',
                icon: '',
                action: exportPage
            }
            break
        case 'program':
            actions.deleteprogram = {
                separator_before: false,
                separator_after: true,
                label: '删除程序',
                icon: '',
                action: deleteProgram
            }
            break
        case 'folder':
            foldereditstatues = false
            let inst = $.jstree.reference(ID)
            for (let i = 0; i < o.parents.length; i++) {
                let n = inst.get_node(o.parents[i])

                if (o.original.model.STYPE === 1) {
                    actions.exportpage = {
                        separator_before: false,
                        separator_after: true,
                        label: '导出所有页面',
                        icon: '',
                        action: exportPage
                    }

                    actions.inportpage = {
                        separator_before: false,
                        separator_after: true,
                        label: '导入页面',
                        icon: '',
                        action: inportPage
                    }
                }
                if (o.original.model.STYPE === 0) {
                    actions.exportvarb = {
                        separator_before: false,
                        separator_after: true,
                        label: '导出所有变量',
                        icon: '',
                        action: exportVarb
                    }
                    actions.inportvarbtemplate = {
                        separator_before: false,
                        separator_after: true,
                        label: '导入变量',
                        icon: '',
                        action: inportVarbTemplate
                    }
                }
                if (n.original !== undefined && n.original.modeltype === 'upper') {
                    // 上位机层级，可以 增加通道
                    actions.createchannel = {
                        separator_before: false,
                        separator_after: false,
                        label: '建立通讯通道',
                        icon: '',
                        action: createChannel
                    }
                    actions.createpage = {
                        separator_before: false,
                        separator_after: false,
                        label: '新建页面',
                        icon: '',
                        action: createPage
                    }
                    actions.createprogram = {
                        separator_before: false,
                        separator_after: false,
                        label: '新建程序',
                        icon: '',
                        action: createProgram
                    }
                    actions.createinnervariable = {
                        separator_before: false,
                        separator_after: false,
                        label: '新建内部变量',
                        icon: '',
                        action: createInnerVariable
                    }

                    actions.createwarningvariable = {
                        separator_before: false,
                        separator_after: true,
                        label: '新建报警变量',
                        icon: '',
                        action: createWarningVariable
                    }
                    break
                }

                if (n.original !== undefined && n.original.modeltype === 'channel') {
                    actions.createdevice = {
                        separator_before: false,
                        separator_after: true,
                        label: '建立设备',
                        icon: '',
                        action: createDevice
                    }
                    break
                }

                if (n.original !== undefined && n.original.modeltype === 'device') {
                    actions.createvariable = {
                        separator_before: false,
                        separator_after: false,
                        label: '新建变量',
                        icon: '',
                        action: createVariable
                    }
                    break
                }
            }
            break
    }

    // 所有层级都可以添加文件夹
    var bfolder = false
    if (store.getters.login.user.STYPE <= 2) {
        bfolder = true
    } else {
        var pnode = getModelTypeWhichNotFolder(o, 'parent')
        if (pnode === 'company') {
            bfolder = false
        } else {
            bfolder = true
        }
    }

    if (bfolder) {
        actions.copypaste = {
            separator_before: true,
            separator_after: false,
            label: '操作',
            icon: '',
            submenu: [{
                    separator_before: false,
                    separator_after: false,
                    label: '剪切',
                    icon: '',
                    action: function(data) {}
                },
                {
                    separator_before: false,
                    separator_after: false,
                    label: '复制',
                    icon: '',
                    action: function(data) {}
                },
                {
                    separator_before: false,
                    separator_after: true,
                    label: '粘贴',
                    icon: '',
                    action: function(data) {}
                }
            ],
            action: function(data) {}
        }
        actions.folder = {
            separator_before: false,
            separator_after: false,
            label: '文件夹',
            icon: '',
            submenu: [{
                    separator_before: false,
                    separator_after: false,
                    label: '新建',
                    icon: '',
                    action: editfolder
                },
                {
                    separator_before: false,
                    separator_after: true,
                    label: '删除',
                    icon: '',
                    _disabled: foldereditstatues,
                    action: deletefolder
                }
            ],
            action: function(data) {}
        }
    } else {
        if (modeltype !== 'company') {
            actions.copypaste = {
                separator_before: false,
                separator_after: false,
                label: '操作',
                icon: '',
                submenu: [{
                    separator_before: false,
                    separator_after: false,
                    label: '复制',
                    icon: '',
                    action: function(data) {}
                }],
                action: function(data) {}
            }
        }
    }

    return actions
}
// ---------------------------------- end -----------------------------------------

// ----------------------------------节点移动---------------------------------------
// 节点移动时的检查
function checkCallbackWhenDndForProject(nodeParent) {
    if (nodeParent.original.modeltype === 'company') { return true }
    if (nodeParent.original.modeltype === 'folder') { // 如果父节点为folder，则需要判断该folder的第一个非folder父级是否为company，如果不是，则不允许移动
        let ptype = getModelTypeWhichNotFolder(nodeParent, 'parent')
        if (ptype === 'company') {
            return true
        } else {
            return false
        }
    } else {
        return false
    }
}

function checkCallbackWhenDndForUpper(nodeParent) {
    if (nodeParent.original.modeltype === 'project' || nodeParent.original.modeltype === 'company') { return true }
    if (nodeParent.original.modeltype === 'folder') {
        let ptype = getModelTypeWhichNotFolder(nodeParent, 'parent')
        if (ptype === 'company' || ptype === 'project') {
            return true
        } else {
            return false
        }
    } else {
        return false
    }
}

function checkCallbackWhenDndForChannel(nodeParent) {
    if (nodeParent.original.modeltype === 'upper') { return true }
    if (nodeParent.original.modeltype === 'folder') {
        let ptype = getModelTypeWhichNotFolder(nodeParent, 'parent')
        if (ptype === 'upper') {
            return true
        } else {
            return false
        }
    } else {
        return false
    }
}

function checkCallbackWhenDndForDevice(nodeParent) {
    if (nodeParent.original.modeltype === 'channel') { return true }
    if (nodeParent.original.modeltype === 'folder') {
        let ptype = getModelTypeWhichNotFolder(nodeParent, 'parent')
        if (ptype === 'channel') {
            return true
        } else {
            return false
        }
    } else {
        return false
    }
}

function checkCallbackWhenDndForVariable(nodeParent) {
    if (nodeParent.original.modeltype === 'upper') { return true }
    if (nodeParent.original.modeltype === 'device') { return true }
    if (nodeParent.original.modeltype === 'folder') {
        let ptype = getModelTypeWhichNotFolder(nodeParent, 'parent')
        if (ptype === 'upper' || ptype === 'device') {
            return true
        } else {
            return false
        }
    } else {
        return false
    }
}

function checkCallbackWhenDndForPage(nodeParent) {
    if (nodeParent.original.modeltype === 'upper') { return true }
    if (nodeParent.original.modeltype === 'folder') {
        let ptype = getModelTypeWhichNotFolder(nodeParent, 'parent')
        if (ptype === 'upper') {
            return true
        } else {
            return false
        }
    } else {
        return false
    }
}

function checkCallbackWhenDndForProgram(nodeParent) {
    if (nodeParent.original.modeltype === 'upper') { return true }
    if (nodeParent.original.modeltype === 'folder') {
        let ptype = getModelTypeWhichNotFolder(nodeParent, 'parent')
        if (ptype === 'upper') {
            return true
        } else {
            return false
        }
    } else {
        return false
    }
}

function checkCallbackWhenDndForDatabase(nodeParent) {
    if (nodeParent.original.modeltype === 'company') { return true }
    if (nodeParent.original.modeltype === 'project') { return true }
    if (nodeParent.original.modeltype === 'folder') {
        let ptype = getModelTypeWhichNotFolder(nodeParent, 'parent')
        if (ptype === 'company') {
            return true
        } else if (ptype === 'project') {
            return true
        } else {
            return false
        }
    } else {
        return false
    }
}

function checkCallbackWhenDnd(operation, node, nodeParent) {
    // operation can be 'create_node', 'rename_node', 'delete_node', 'move_node' or 'copy_node'
    // in case of 'rename_node' node_position is filled with the new node name
    if (operation === 'move_node') {
        if (nodeParent.original == null) { return false } // 如果父节点为空，则不允许移动
        if (node.original.modeltype === 'company') { return false } // 如果当前移动节点是company，则不允许移动
        if (node.original.modeltype === 'project') { // 如果当前节点是project，则只允许移动到company下或company下的所有folder下
            return checkCallbackWhenDndForProject(nodeParent)
        } else if (node.original.modeltype === 'upper') { // 如果当前移动的节点是upper，则只允许移动到company或project下
            return checkCallbackWhenDndForUpper(nodeParent)
        } else if (node.original.modeltype === 'channel') {
            return checkCallbackWhenDndForChannel(nodeParent)
        } else if (node.original.modeltype === 'device') {
            return checkCallbackWhenDndForDevice(nodeParent)
        } else if (node.original.modeltype === 'variable') {
            return checkCallbackWhenDndForVariable(nodeParent)
        } else if (node.original.modeltype === 'page') {
            return checkCallbackWhenDndForPage(nodeParent)
        } else if (node.original.modeltype === 'program') {
            return checkCallbackWhenDndForProgram(nodeParent)
        } else if (node.original.modeltype === 'database') {
            return checkCallbackWhenDndForDatabase(nodeParent)
        } else if (node.original.modeltype === 'folder') {
            let subtype = getModelTypeWhichNotFolder(node, 'child')
            if (subtype === '') {
                return true // 如果folder没有任何非folder的子节点，则可以任意移动
            } else if (subtype === 'project') {
                return checkCallbackWhenDndForProject(nodeParent)
            } else if (subtype === 'upper') {
                return checkCallbackWhenDndForUpper(nodeParent)
            } else if (subtype === 'channel') {
                return checkCallbackWhenDndForChannel(nodeParent)
            } else if (subtype === 'device') {
                return checkCallbackWhenDndForDevice(nodeParent)
            } else if (subtype === 'variable') {
                return checkCallbackWhenDndForVariable(nodeParent)
            } else if (subtype === 'page') {
                return checkCallbackWhenDndForPage(nodeParent)
            } else if (subtype === 'program') {
                return checkCallbackWhenDndForProgram(nodeParent)
            } else if (subtype === 'database') {
                return checkCallbackWhenDndForDatabase(nodeparent)
            } else {
                return false
            }
        }
        return false
    }
}

// 移动节点，保存至数据库
function moveNode(e, data) {
    if (data.old_parent !== data.parent) {
        let parentnode = $.jstree.reference(ID).get_node(data.parent)
        if (data.node.original.modeltype === "project") {
            moveProjectNode(data.node, parentnode)
        } else if (data.node.original.modeltype === 'upper') {
            moveUpperNode(data.node, parentnode)
        } else if (data.node.original.modeltype === 'channel') {
            moveChannelNode(data.node, parentnode)
        } else if (data.node.original.modeltype === 'device') {
            moveDeviceNode(data.node, parentnode)
        } else if (data.node.original.modeltype === 'variable') {
            moveVariableNode(data.node, parentnode)
        } else if (data.node.original.modeltype === 'page') {
            movePageNode(data.node, parentnode)
        } else if (data.node.original.modeltype === 'database') {
            moveDatabaseNode(data.node, parentnode)
        } else if (data.node.original.modeltype === 'folder') {
            moveFolderNode(data.node, parentnode);
        } else if (data.node.original.modeltype === 'program') {
            moveProgramNode(data.node, parentnode);
        }
    }
}

// 重新请求 tree数据 刷新tree 用在移动拖拽节点后 报错调用
const updataTree = () => {
    maincfg.getConfigData((ro) => {
        console.log('刷新tree页面后所有tree数据: ', ro)
        loadTree(ro)
    }, (ex) => {
        toastr.showError(ex.Message)
    })
}

//节点移动的最终操作，保存到数据库
function moveProjectNode(node, parentnode) {
    let pk_folder = ''
    if (parentnode.original.modeltype === 'folder') {
        pk_folder = parentnode.original.model.PK
    }
    maincfg.moveProject(node.original.model.PK, pk_folder, (ro) => {
        toastr.showSuccess('移动成功')
        // loadTree(ro, node.id)
    }, (ex) => {
        updataTree()
        toastr.showError(ex.Message)
    })
}

function moveUpperNode(node, parentnode) {
    let pk_project = '',
        pk_folder = ''
    if (parentnode.original.modeltype === 'folder') {
        pk_folder = parentnode.original.model.PK
        let pnode = getNodeWhichNotFolder(parentnode, 'parent')
        if (pnode.original.modeltype == 'project') {
            pk_project = pnode.original.model.PK
        }
    } else if (parentnode.original.modeltype === 'project') {
        pk_project = parentnode.original.model.PK
    }
    maincfg.moveUpper(node.original.model.PK, pk_folder, pk_project, (ro) => {
        toastr.showSuccess('移动成功')
        // loadTree(ro, node.id)
    }, (ex) => {
        updataTree()
        toastr.showError(ex.Message)
    })
}

function moveChannelNode(node, parentnode) {
    let pk_upper = '',
        pk_folder = ''
    if (parentnode.original.modeltype === 'folder') {
        pk_folder = parentnode.original.model.PK
        let pnode = getNodeWhichNotFolder(parentnode, 'parent')
        if (pnode.original.modeltype === 'upper') {
            pk_upper = pnode.original.model.PK
        }
    } else if (parentnode.original.modeltype === 'upper') {
        pk_upper = parentnode.original.model.PK
    }
    if (pk_upper !== '') {
        maincfg.moveChannel(node.original.model.PK, pk_folder, pk_upper, (ro) => {
            toastr.showSuccess('移动成功')
            // loadTree(ro, node.id)
        }, (ex) => {
            updataTree()
            toastr.showError(ex.Message)
        })
    }
}

function moveDeviceNode(node, parentnode) {
    let pk_upper = '',
        pk_channel = '',
        pk_folder = ''
    if (parentnode.original.modeltype === 'folder') {
        pk_folder = parentnode.original.model.PK
        let pnode = getNodeWhichNotFolder(parentnode, 'parent')
        if (pnode.original.modeltype === 'channel') {
            pk_channel = pnode.original.model.PK
            pk_upper = pnode.original.model.PK_UPPER_ENTITY
        }
    } else if (parentnode.original.modeltype === 'channel') {
        pk_channel = parentnode.original.model.PK
        pk_upper = parentnode.original.model.PK_UPPER_ENTITY
    }
    if (pk_channel !== '' && pk_upper !== '') {
        maincfg.moveDevice(node.original.model.PK, pk_folder, pk_channel, pk_upper, (ro) => {
            toastr.showSuccess('移动成功')
            // loadTree(ro, node.id)
        }, (ex) => {
            updataTree()
            toastr.showError(ex.Message)
        })
    }
}

function moveVariableNode(node, parentnode) {
    let pk_upper = '',
        pk_folder = '',
        pk_device = ''
    if (parentnode.original.modeltype === 'folder') {
        pk_folder = parentnode.original.model.PK
        let pnode = getNodeWhichNotFolder(parentnode, 'parent')
        if (pnode.original.modeltype === 'upper') {
            pk_upper = pnode.original.model.PK
        } else if (pnode.original.modeltype === 'device') {
            pk_device = pnode.original.model.PK
            pk_upper = parentnode.original.model.PK_UPPER_ENTITY
        }
    } else if (parentnode.original.modeltype === 'upper') {
        pk_upper = parentnode.original.model.PK
    } else if (parentnode.original.modeltype === 'device') {
        pk_device = parentnode.original.model.PK
        pk_upper = parentnode.original.model.PK_UPPER_ENTITY
    }
    if (pk_upper !== '') {
        maincfg.moveVariable(node.original.model.PK, pk_folder, pk_upper, pk_device, (ro) => {
            toastr.showSuccess('移动成功')
            // loadTree(ro, node.id)
        }, (ex) => {
            updataTree()
            toastr.showError(ex.Message)
        })
    }
}

function movePageNode(node, parentnode) {
    let pk_upper = '',
        pk_folder = ''
    if (parentnode.original.modeltype === 'folder') {
        pk_folder = parentnode.original.model.PK
        let pnode = getNodeWhichNotFolder(parentnode, 'parent')
        if (pnode.original.modeltype === 'upper') {
            pk_upper = pnode.original.model.PK
        }
    } else if (parentnode.original.modeltype === 'upper') {
        pk_upper = parentnode.original.model.PK
    }
    if (pk_upper !== '') {
        maincfg.movePage(node.original.model.PK, pk_folder, pk_upper, (ro) => {
            toastr.showSuccess('移动成功')
            // loadTree(ro, node.id)
        }, (ex) => {
            updataTree()
            toastr.showError(ex.Message)
        })
    }
}

function moveDatabaseNode(node, parentnode) {
    let pk_project = '',
        pk_folder = ''
    if (parentnode.original.modeltype === 'folder') {
        pk_folder = parentnode.original.model.PK
        let pnode = getNodeWhichNotFolder(parentnode, 'parent')
        if (pnode.original.modeltype == 'project') {
            pk_project = pnode.original.model.PK
        }
    } else if (parentnode.original.modeltype === 'project') {
        pk_project = parentnode.original.model.PK
    }
    maincfg.moveDatabase(node.original.model.PK, pk_folder, pk_project, (ro) => {
        toastr.showSuccess('移动成功')
        // loadTree(ro, node.id)
    }, (ex) => {
        updataTree()
        toastr.showError(ex.Message)
    })
}

function moveProgramNode(node, parentnode) {
    let pk_upper = '',
        pk_folder = ''
    if (parentnode.original.modeltype === 'folder') {
        pk_folder = parentnode.original.model.PK
        let pnode = getNodeWhichNotFolder(parentnode, 'parent')
        if (pnode.original.modeltype === 'upper') {
            pk_upper = pnode.original.model.PK
        }
    } else if (parentnode.original.modeltype === 'upper') {
        pk_upper = parentnode.original.model.PK
    }
    if (pk_upper !== '') {
        maincfg.moveProgram(node.original.model.PK, pk_folder, pk_upper, (ro) => {
            toastr.showSuccess('移动成功')
            // loadTree(ro, node.id)
        }, (ex) => {
            updataTree()
            toastr.showError(ex.Message)
        })
    }
}

function moveFolderNode(node, parentnode) {
    let pk_project = '',
        pk_upper = '',
        pk_channel = '',
        pk_device = '',
        pk_parent = '',
        bisuser = false,
        bisrole = false
    if (parentnode.original.modeltype === 'project')
        pk_project = parentnode.original.model.PK
    else if (parentnode.original.modeltype === 'upper')
        pk_upper = parentnode.original.model.PK
    else if (parentnode.original.modeltype === 'channel')
        pk_channel = parentnode.original.model.PK
    else if (parentnode.original.modeltype === 'device')
        pk_device = parentnode.original.model.PK

    for (let i = 0; i < parentnode.parents.length; i++) {
        let pnode = $.jstree.reference(ID).get_node(parentnode.parents[i])
        if (pnode.original === undefined) { continue }
        switch (pnode.original.modeltype) {
            case 'project':
                pk_project = pnode.original.model.PK
                break
            case 'upper':
                pk_upper = pnode.original.model.PK
                break
            case 'channel':
                pk_channel = pnode.original.model.PK
                break
            case 'device':
                pk_device = pnode.original.model.PK
                break
            case 'folder':
                break
        }
    }

    if (parentnode.original !== undefined) {
        if (parentnode.original.model !== null) {
            pk_parent = parentnode.original.model.PK
        } else {
            if (parentnode.id === 'userroot') {
                bisuser = true
                bisrole = false
                pk_parent = ''
            } else if (parentnode.id === 'roleroot') {
                bisuser = false
                bisrole = true
                pk_parent = ''
            } else {
                bisuser = false
                bisrole = false
                pk_parent = ''
            }
        }
        maincfg.moveFolder(node.original.model.PK, pk_parent, pk_project, pk_upper, pk_channel, pk_device, bisuser, bisrole, (ro) => {
            toastr.showSuccess('移动成功')
            // loadTree(ro, node.id)
        }, (ex) => {
            updataTree()
            toastr.showError(ex.Message)
        })
    }
}
// --------------------------------------- end ----------------------------------------

// 获取树节点的父级或子集的非folder节点类型
function getModelTypeWhichNotFolder(node, parentorchild) {
    // let stype = ''
    if (node.original === null) { return '' }
    if (node.original.modeltype !== 'folder') { return node.original.modeltype }
    let lst
    if (parentorchild === 'parent') {
        lst = node.parents
    } else {
        lst = node.children_d
    }
    for (let i = 0; i < lst.length; i++) {
        let pnode = $.jstree.reference(ID).get_node(lst[i])
        if (pnode.original !== null && pnode.original.modeltype !== 'folder') {
            return pnode.original.modeltype
        }
    }

    return ''
}

// 获取树节点的父级或子集的非folder节点
function getNodeWhichNotFolder(node, parentorchild) {
    if (node.original === null) { return null }
    if (node.original.modeltype !== 'folder') { return node }
    let lst
    if (parentorchild === 'parent') {
        lst = node.parents
    } else {
        lst = node.children_d
    }
    for (let i = 0; i < lst.length; i++) {
        let pnode = $.jstree.reference(ID).get_node(lst[i])
        if (pnode.original !== null && pnode.original.modeltype !== 'folder') {
            return pnode
        }
    }

    return null
}

// 递归获取父级的所有非folder节点
function getActivedParentNodesWithoutFolder() {
    let currentnode = $(ID).jstree('get_selected', true)[0]

    let parentnodes = {
        PK_COMPANY: '',
        PK_PROJECT: '',
        PK_UPPER_ENTITY: '',
        PK_CHANNEL: '',
        PK_DEVICE: '',
        BISUSER: false,
        BISROLE: false
    }

    getParentNode(parentnodes, currentnode)

    return parentnodes
}

function getParentNode(parentnodes, node) {
    if (node !== undefined && node.original !== undefined) {
        switch (node.original.modeltype) {
            case 'company':
                parentnodes.PK_COMPANY = node.original.model.PK
                break
            case 'project':
                parentnodes.PK_PROJECT = node.original.model.PK
                break
            case 'upper':
                parentnodes.PK_UPPER_ENTITY = node.original.model.PK
                break
            case 'channel':
                parentnodes.PK_CHANNEL = node.original.model.PK
                break
            case 'device':
                parentnodes.PK_DEVICE = node.original.model.PK
                break
            case 'folder':
                break
            case 'userroot':
                parentnodes.BISUSER = true
                break
            case 'roleroot':
                parentnodes.BISROLE = true
                break
        }
    }

    if (node !== undefined && node.parent !== '#') {
        let pnode = $(ID).jstree('get_node', node.parent)
        getParentNode(parentnodes, pnode)
    }
}

function getNodeByID(id) {
    let node = $(ID).jstree('get_node', id)
    return node
}

// 通过id选中节点
function selectNodeByID(id) {
    $(ID).jstree('deselect_all')
    $(ID).jstree('select_node', [id])
    let currentnode = $(ID).jstree('get_selected', true)[0]
    console.log('currentnode: ', currentnode)
    clicknode(currentnode)
}

// 设置上位机的在线状态
function setUpperConnection(id, isonline) {
    let icon = ''
    if (isonline) {
        icon = 'fa fa-circle font-green'
    } else {
        icon = 'fa fa-circle-o font-red'
    }
    $(ID).jstree('set_icon', id, icon)
}

// 点击树节点的总入口
function clicknode(node) {
    console.log('node: ', node)
    if (node !== undefined && node.original !== undefined) {
        // console.log(tabs)
        //store.commit('setParams', node)
        // store.commit('setKey', { key: node.id, isnew: false })
        let title = ''
        if (node.original !== null) {
            switch (node.original.modeltype) {
                case 'upper':
                    // title = '上位机' + node.original.model.SUPPERCODE
                    store.commit('setParams', node.original)
                    router.push(`/main/${ProjectPK}/upper/${node.original.id}`)
                    break
                case 'folder':
                    store.commit('setParams', node.original)
                        // title = '文件夹' + node.original.model.SFOLDERNAME
                    router.push(`/main/${ProjectPK}/folder/` + node.original.id + '/edit')
                    break
                case 'channel':
                    store.commit('setParams', node.original)
                    router.push(`/main/${ProjectPK}/channel/` + node.original.id + '/edit')
                    break
                case 'device':
                    store.commit('setParams', node.original)
                    router.push(`/main/${ProjectPK}/device/` + node.original.id + '/edit')
                    break
                case 'project':
                    store.commit('setParams', node.original)
                    router.push(`/main/${ProjectPK}/project/` + node.original.id + '/edit')
                    break
                case 'page':
                    store.commit('setParams', node.original)
                    router.push(`/main/${ProjectPK}/page/` + node.original.id + '/edit')
                    break
                case 'program':
                    store.commit('setParams', node.original)
                    router.push(`/main/${ProjectPK}/program/` + node.original.id + '/edit')
                    break
                case 'variable':
                    store.commit('setParams', node.original)
                    // if (node.data.varcategory === 1) {
                    //     console.log('node.data.varcategory: ', node.data.varcategory)
                    //     router.push(`/main/${ProjectPK}/variable/` + node.original.id + '/edit')
                    // }
                    // if (node.data.varcategory === 2) {
                    //     console.log('node.data.varcategory: ', node.data.varcategory)
                    //     // router.push(`/main/${ProjectPK}/variable/` + node.original.id + '/edit')
                    // }
                    if (node.data.varcategory === 3) {
                        router.push(`/main/${ProjectPK}/warningvariable/` + node.original.id + '/edit')
                    } else {
                        router.push(`/main/${ProjectPK}/variable/` + node.original.id + '/edit')
                    }
                    // router.push(`/main/${ProjectPK}/variable/` + node.original.id + '/edit')
                    break
                case 'database':
                    store.commit('setParams', node.original)
                    router.push(`/main/${ProjectPK}/database/` + node.original.id + '/edit')
                    break
            }
        }
        // tabs.open({
        //   name: node.original.modeltype,
        //   // title: title,
        //   key: node.id
        // })

    }
}

// 新建文件夹
function editfolder(data) {
    let inst = $.jstree.reference(data.reference)
    let parentnode = inst.get_node(data.reference)
    store.commit('clearParams')
    router.push(`/main/${ProjectPK}/folder/` + parentnode.id + '/new')
        // store.commit('setKey', { key: parentnode.id, isnew: true })
        // tabs.open({
        //   name: 'folder',
        //   key: parentnode.id
        // })
}

// 删除文件夹
function deletefolder(data) {
    bootbox.confirm({
        message: '<h3>这样做将会同时删除下面的内容，确实要删除文件夹么？</h3>',
        buttons: {
            confirm: {
                label: '是',
                className: 'btn-danger'
            },
            cancel: {
                label: '否',
                className: 'btn-success'
            }
        },
        callback: function(result) {
            if (result) {
                let inst = $.jstree.reference(data.reference)
                let currentnode = inst.get_node(data.reference)
                let parentid = currentnode.parent
                let subpk = []
                let subpktype = []
                let parentobj = inst.get_node(parentid)
                for (let i=0; i < parentobj.children_d.length; i++) {
                    let node = inst.get_node(parentobj.children_d[i])
                    if (node.original.modeltype === 'folder' && node.state.selected) {
                        subpk.push(node.original.model.PK)
                        subpktype.push(node.original.modeltype)
                        for (let j = 0; j < node.children_d.length; j++) {
                            let snode = inst.get_node(node.children_d[j])
                            subpk.push(snode.original.model.PK)
                            subpktype.push(snode.original.modeltype)
                        }
                    }
                }
                console.log('当前要删除的类型', subpktype)
                folder.delete(currentnode.original.model.PK, subpk, subpktype, (ro) => {
                    toastr.showSuccess('删除成功')
                    // init(parentid)
                    store.commit('updataTree', null)
                    init(router.currentRoute.params.propk)
                    router.push(`/main/${ProjectPK}`)
                }, (ex) => {
                    toastr.showError('删除失败：' + ex.Message)
                })
            }
        }
    })
}

// 新建通讯通道
function createChannel(data) {
    let inst = $.jstree.reference(data.reference)
    let parentnode = inst.get_node(data.reference)
    store.commit('clearParams')
    router.push(`/main/${ProjectPK}/channel/` + parentnode.id + '/new')
        // store.commit('setKey', { key: parentnode.id, isnew: true })
        // tabs.open({
        //   name: 'channel',
        //   key: parentnode.id
        // })
}

// 新建项目
function createProject(data) {
    let inst = $.jstree.reference(data.reference)
    let parentnode = inst.get_node(data.reference)
    store.commit('clearParams')
    router.push(`/main/${ProjectPK}/project/` + parentnode.id + '/new')
        // store.commit('setKey', { key: parentnode.id, isnew: true })
        // tabs.open({
        //   name: 'project',
        //   key: parentnode.id
        // })
}

// 新建页面
function createPage(data) {
    let inst = $.jstree.reference(data.reference)
    let parentnode = inst.get_node(data.reference)
    store.commit('clearParams')
    router.push(`/main/${ProjectPK}/page/` + parentnode.id + '/new')
        // store.commit('setKey', { key: parentnode.id, isnew: true })
        // tabs.open({
        //   name: 'page',
        //   key: parentnode.id
        // })
}

// 新建程序
function createProgram(data) {
    let inst = $.jstree.reference(data.reference)
    let parentnode = inst.get_node(data.reference)
    store.commit('clearParams')
    router.push(`/main/${ProjectPK}/program/` + parentnode.id + '/new')
}

// 购买上位机
// function buyItem(data) {
//     // let inst = $.jstree.reference(data.reference)
//     // let parentnode = inst.get_node(data.reference)
//     store.commit('clearParams')
//     router.push('/buy/upper')
// }

// 新建设备
function createDevice(data) {
    let inst = $.jstree.reference(data.reference)
    let parentnode = inst.get_node(data.reference)
    store.commit('clearParams')
    router.push(`/main/${ProjectPK}/device/` + parentnode.id + '/new')
}

// 新建变量
function createVariable(data) {
    let inst = $.jstree.reference(data.reference)
    let parentnode = inst.get_node(data.reference)
    store.commit('clearParams')
    router.push(`/main/${ProjectPK}/variable/` + parentnode.id + '/1')
}

// 新建内部变量
function createInnerVariable(data) {
    let inst = $.jstree.reference(data.reference)
    let parentnode = inst.get_node(data.reference)
    store.commit('clearParams')
    router.push(`/main/${ProjectPK}/variable/` + parentnode.id + '/2')
}

// 新建报警变量
function createWarningVariable(data) {
    let inst = $.jstree.reference(data.reference)
    let parentnode = inst.get_node(data.reference)
    store.commit('clearParams')
    router.push(`/main/${ProjectPK}/warningvariable/` + parentnode.id + '/3')
}

// 新建数据库
function createDatabase(data) {
    let inst = $.jstree.reference(data.reference)
    let parentnode = inst.get_node(data.reference)
    store.commit('clearParams')
    router.push(`/main/${ProjectPK}/database/` + parentnode.id + '/new')
}

// 类似创建变量
function createVariable2(data) {
    let inst = $.jstree.reference(data.reference)
    let parentnode = inst.get_node(data.reference)
    store.commit('clearParams')
    store.commit('setParamsForNewVariable', )
    router.push(`/main/${ProjectPK}/variable/` + parentnode.id + '/new')
}

// 删除的通用方法
function deleteCommon(confirmTitle, confirmCallback) {
    bootbox.confirm({
        message: '<h3>' + confirmTitle + '</h3>',
        buttons: {
            confirm: {
                label: '是',
                className: 'btn-danger'
            },
            cancel: {
                label: '否',
                className: 'btn-success'
            }
        },
        callback: function(result) {
            if (result) {
                confirmCallback()
            }
        }
    })
}
// 上传文件的方法
function uploadFile(confirmTitle, confirmCallback) {
    bootbox.dialog({
        title: confirmTitle,
        message: '<div><input id="uploadPageContentEvent" type="file" placeholder="请选择。。" /></div>',
        buttons: {
            "success": {
                "label": "确认",
                "callback": function () {
                    let file = document.getElementById('uploadPageContentEvent')
                    console.log('上传的文件时', file.files[0])
                    confirmCallback(file.files[0])
                }
            },
            "cancel": {
                "label": "取消",
                "callback": function () {}
            }
        }
    })
}

// 删除页面多选删除
function deletePage(data) {
    deleteCommon('确定要删除页面么？', () => {
        let inst = $.jstree.reference(data.reference)
        let currentnode = inst.get_node(data.reference)
        let parentid = currentnode.parent
        let pagearr = []
        let parentobj = inst.get_node(parentid)
        for (let i=0; i < parentobj.children_d.length; i++) {
            let node = inst.get_node(parentobj.children_d[i])
            if (node.original.modeltype === 'page' && node.state.selected) {
                pagearr.push(node.original.model.PK)
            }
        }
        page.delete(pagearr, (ro) => {
            toastr.showSuccess('删除成功')
            store.commit('updataTree', null)
            init(router.currentRoute.params.propk)
            // init(parentid)
            router.push(`/main/${ProjectPK}`)
        }, (ex) => {
            toastr.showError('删除失败：' + ex.Message)
        })
    })
}

// 导出页面
function exportPage(data) {
    deleteCommon('确定导出页面？', () => {
        let inst = $.jstree.reference(data.reference)
        let currentnode = inst.get_node(data.reference)
        console.log('currentnode', currentnode)
        let downloadLink = document.createElement('a')
        if (currentnode.original.modeltype === 'folder') {
            downloadLink.href = config.webapiprefix + 'GetData?sessionid=' + store.getters.login.sessionid + '&prefix=Kingreid.IMR.WebApi&classname=Page&methodname=Export&jsonargs=' + JSON.stringify({upperpk: currentnode.original.model.PK_UPPER_ENTITY, PK: currentnode.children_d})            
        } else if(currentnode.original.modeltype === 'page') {
            downloadLink.href = config.webapiprefix + 'GetData?sessionid=' + store.getters.login.sessionid + '&prefix=Kingreid.IMR.WebApi&classname=Page&methodname=Export&jsonargs=' + JSON.stringify({upperpk: currentnode.original.model.PK_UPPER_ENTITY, PK: [currentnode.id]})            
        }
        console.log('downloadLink.href: ', downloadLink.href)
        document.body.appendChild(downloadLink)
        downloadLink.click()
        document.body.removeChild(downloadLink)
    })
}
// 导入页面
function inportPage(data) {
    uploadFile('导入页面', (file) => {
        console.log('拿到的文件是', file)
        let inst = $.jstree.reference(data.reference)
        let currentnode = inst.get_node(data.reference)
        let paramdata = new FormData()
        paramdata.append('sessionid', store.getters.login.sessionid)
        paramdata.append('prefix', 'Kingreid.IMR.WebApi')
        paramdata.append('classname', 'Page')
        paramdata.append('methodname', 'Inport')
        paramdata.append('file', file)
        paramdata.append('jsonargs', JSON.stringify({upperpk: currentnode.original.model.PK_UPPER_ENTITY, folderpk: currentnode.id}))
        console.log('currentnode', currentnode)
        console.log('当前的response是', paramdata)
        Vue.http.post(config.webapiprefix, paramdata).then((response) => {
            if (response.body.Exception ===null) {
                toastr.showSuccess('导入成功')
            } else {
                toastr.showError('导入失败' + response.body.Exception)
            }
        })
    })
}
// 导出所有变量
function exportVarb (data) {
    deleteCommon('确定导出所有变量？', () => {
        let inst = $.jstree.reference(data.reference)
        let currentnode = inst.get_node(data.reference)
        // let paramdata = new FormData()
        // paramdata.append('sessionid', store.getters.login.sessionid)
        // paramdata.append('prefix', 'Kingreid.IMR.WebApi')
        // paramdata.append('classname', 'Variable')
        // paramdata.append('methodname', 'Export')
        // paramdata.append('jsonargs', JSON.stringify({upperpk: currentnode.original.model.PK_UPPER_ENTITY, PK: currentnode.children_d}))
        // Vue.http.post(config.webapiprefix, paramdata).then((response) => {
        //     console.log('当前的response是', response)
        // })
        let downloadLink = document.createElement('a')
        downloadLink.href = config.webapiprefix + 'GetData?sessionid=' + store.getters.login.sessionid + '&prefix=Kingreid.IMR.WebApi&classname=Variable&methodname=Export&jsonargs=' + JSON.stringify({upperpk: currentnode.original.model.PK_UPPER_ENTITY, PK: currentnode.children_d})
        document.body.appendChild(downloadLink)
        downloadLink.click()
        document.body.removeChild(downloadLink)
    })
}
// 导出变量模板
function exportVarbTemplate (data) {
    let inst = $.jstree.reference(data.reference)
    let currentnode = inst.get_node(data.reference)
    console.log('currentnode', currentnode)
    let paramdata = new FormData()
    paramdata.append('sessionid', store.getters.login.sessionid)
    paramdata.append('prefix', 'Kingreid.IMR.WebApi')
    paramdata.append('classname', 'Variable')
    paramdata.append('methodname', 'ExportTemp')
    Vue.http.post(config.webapiprefix, paramdata,{headers: 'charset="utf-8"'}).then((response) => {
        if (response.body.Exception !== null) {
            toastr.showError('导出失败', response.body.Exception)
        } else {
            toastr.showSuccess('导出成功')
            let download = {}
            let title = []
            let bindname = []
            let arr = String(response.body.Value).split('#')
            arr.forEach((obj) => {
                switch(obj)
                {
                    case 'SVARCODE':
                    title.push('变量代码')
                    bindname.push('SVARCODE')
                    break;
                    case 'SVARNAME':
                    title.push('变量含义')
                    bindname.push('SVARNAME')
                    break;
                    case 'SVARTYPE':
                    title.push('变量类型')
                    bindname.push('SVARTYPE')
                    break;
                    case 'SVARADDRESS':
                    title.push('变量地址')
                    bindname.push('SVARADDRESS')
                    break;
                    case 'SFORMULA':
                    title.push('计算公式')
                    bindname.push('SFORMULA')
                    break;
                    case 'PK_DB':
                    title.push('归档数据库')
                    bindname.push('PK_DB')
                    break;
                    case 'SARCHIVEMODE':
                    title.push('归档模式')
                    bindname.push('SARCHIVEMODE')
                    break;
                    case 'IARCHIVEPERIOD_VALUE':
                    title.push('归档周期')
                    bindname.push('IARCHIVEPERIOD_VALUE')
                    break;
                    case 'SARCHIVEPERIOD_TYPE':
                    title.push('归档周期类型')
                    bindname.push('SARCHIVEPERIOD_TYPE')
                    break;
                    case 'IUPDATEPERIOD':
                    title.push('更新周期')
                    bindname.push('IUPDATEPERIOD')
                    break;
                    case 'SOPCUAPATH':
                    title.push('OCPUA发布路径')
                    bindname.push('SOPCUAPATH')
                    break;
                    case 'SMEMO':
                    title.push('备注')
                    bindname.push('SMEMO')
                    break;
                    case 'SVARCATEGORY':
                    title.push('变量类别')
                    bindname.push('SVARCATEGORY')
                    break;
                }
            })
            download.title = title
            download.bindname = bindname
            download.data = []
            download.portname = 'Template'
            exp.expodata(download)
        }
    })
}
// 导入变量模板
function inportVarbTemplate (data) {
    uploadFile('导入变量模板', (file) => {
        let inst = $.jstree.reference(data.reference)
        let currentnode = inst.get_node(data.reference)
        let paramdata = new FormData()
        paramdata.append('sessionid', store.getters.login.sessionid)
        paramdata.append('prefix', 'Kingreid.IMR.WebApi')
        paramdata.append('classname', 'Variable')
        paramdata.append('methodname', 'Inport')
        paramdata.append('file', file)
        paramdata.append('jsonargs', JSON.stringify({upperpk: currentnode.original.model.PK_UPPER_ENTITY, devicepk: currentnode.id}))
        console.log('paramdata: ', paramdata)
        Vue.http.post(config.webapiprefix, paramdata).then((response) => {
            if (response.body.Value > 0) {
                toastr.showSuccess('导入成功' + response.body.Value)
            } else {
                toastr.showError('导入失败' + response.body.Value + response.body.Exception)
            }
        })
    })
}
// 删除程序
function deleteProgram(data) {
    deleteCommon('确定要删除程序么？', () => {
        let inst = $.jstree.reference(data.reference)
        let currentnode = inst.get_node(data.reference)
        let parentid = currentnode.parent
        prog.delete(currentnode.original.model.PK, (ro) => {
            toastr.showSuccess('删除成功')
            store.commit('updataTree', null)
            init(router.currentRoute.params.propk)
            // init(parentid)
            router.push(`/main/${ProjectPK}`)
        }, (ex) => {
            toastr.showError('删除失败：' + ex.Message)
        })
    })
}

// 删除变量
function deleteVariable(data) {
    deleteCommon('确实要删除变量么？', () => {
        let inst = $.jstree.reference(data.reference)
        let currentnode = inst.get_node(data.reference)
        let parentid = currentnode.parent
        let parentnode = inst.get_node(parentid)
        let pkarr = []
        for (let i=0; i < parentnode.children_d.length; i++) {
            let node = inst.get_node(parentnode.children_d[i])
            if (node.original.modeltype === 'variable' && node.state.selected) {
                pkarr.push(node.original.model.PK)
            }
        }
        variable.delete(pkarr, (ro) => {
            toastr.showSuccess('删除成功')
            // init(parentid)
            store.commit('updataTree', null)
            init(router.currentRoute.params.propk)
            router.push(`/main/${ProjectPK}`)
        }, (ex) => {
            toastr.showError('删除失败：' + ex.Message)
        })
    })
}

//删除数据库
function deleteDatabase(data) {
    deleteCommon('确实要删除该数据库么？', () => {
        let inst = $.jstree.reference(data.reference)
        let currentnode = inst.get_node(data.reference)
        let parentid = currentnode.parent
        console.log('当前要删除的数据库的pk时', currentnode.original.model.PK)
        database.delete(currentnode.original.model.PK, (ro) => {
            toastr.showSuccess('删除成功')
            store.commit('updataTree', null)
            init(router.currentRoute.params.propk)
        }, (ex) => {
            toastr.showError('删除失败：' + ex.Message)
        })
    })
}
// 删除设备
function deleteDevice(data) {
    deleteCommon('确实要删除该协议设备么？', () => {
        let inst = $.jstree.reference(data.reference)
        let currentnode = inst.get_node(data.reference)
        let parentid = currentnode.parent
        let parentnode = inst.get_node(parentid)
        let pkarr = []
        for (let i=0; i < parentnode.children_d.length; i++) {
            let node = inst.get_node(parentnode.children_d[i])
            if (node.original.modeltype === 'device' && node.state.selected) {
                pkarr.push(node.original.model.PK)
            }
        }
        device.delete(pkarr, (ro) => {
            toastr.showSuccess('删除成功')
            // init(parentid)
            store.commit('updataTree', null)
            init(router.currentRoute.params.propk)
            router.push(`/main/${ProjectPK}`)
        }, (ex) => {
            toastr.showError('删除失败：' + ex.Message)
        })
    })
}

// 删除通道
function deleteChannel(data) {
    deleteCommon('确实要删除通讯通道么？', () => {
        let inst = $.jstree.reference(data.reference)
        let currentnode = inst.get_node(data.reference)
        let parentid = currentnode.parent
        channel.delete(currentnode.original.model.PK, (ro) => {
            toastr.showSuccess('删除成功')
            // init(parentid)
            store.commit('updataTree', null)
            init(router.currentRoute.params.propk)
            router.push(`/main/${ProjectPK}`)
        }, (ex) => {
            toastr.showError('删除失败：' + ex.Message)
        })
    })
}

// 删除所有内部变量
function deleteAllInnerVariable(data) {
    deleteCommon('确实要清空所有内部变量么？', () => {
        let inst = $.jstree.reference(data.reference)
        let currentnode = inst.get_node(data.reference)
        let parentid = currentnode.parent
        upper.deleteAllInnerVariable(currentnode.original.model.PK, (ro) => {
            toastr.showSuccess('删除成功')
            // init(parentid)
            store.commit('updataTree', null)
            init(router.currentRoute.params.propk)
            router.push(`/main/${ProjectPK}`)
        }, (ex) => {
            toastr.showError('删除失败：' + ex.Message)
        })
    })
}

// 重置上位机
function resetUpperEntity(data) {
    deleteCommon('确实要重置上位机么？这将清空上位机中的所有数据', () => {
        let inst = $.jstree.reference(data.reference)
        let currentnode = inst.get_node(data.reference)
        let parentid = currentnode.parent
        upper.resetUpperEntity(currentnode.original.model.PK, (ro) => {
            toastr.showSuccess('重置成功')
            // init(parentid)
            store.commit('updataTree', null)
            init(router.currentRoute.params.propk)
        }, (ex) => {
            toastr.showError('重置失败：' + ex.Message)
        })
    })
}