/**
 * @keep
 * 人员管理中树
 * Copyright (c) 2015 大华科技
 */
 import fetch from './ajax.js'
 // 子系统需要此模块引用时开启
// ztree
import './ztree/js/jquery.ztree.core.js'
import './ztree/js/jquery.ztree.excheck.js'
import './ztree/js/jquery.ztree.exedit.js'
import './ztree/js/jquery.ztree.exhide.js'
var vue = new Vue()
var zTree, //树
   /* zNodesJson, //树返回的json */
    clickCB = null,
    _searchKey = '',
    treeId = '',
    openV = null,
    _videoShopObj = null, //videoShop页面的components对象
    onlineChannels = [],
    // arg = '',
    handleAsyncSuccess = null,
    _getTreeNodeCountFn = null,
    objectNodeType = [2, 10, 11, 12],
    devNodes = [],
    setting = $.extend(true, { //表格设置
        view: {
            dblClickExpand: true,
            showLine: false,
            addHoverDom: null,
            removeHoverDom: null,
            addDiyDom: (treeId, treeNode) => {
                if (treeNode.nodeType === 3) {
                   devNodes.push(treeNode)
                }

                if (treeNode && treeNode.uniqueCode === '001') {

                    let aObj = $('#' + treeNode.tId + '_ico_item')
                    // let nodes = zTree.transformToArray(zTree.getNodes())
                    // let devNodes = []
                    // nodes.forEach((item) => {
                    //     if (item.nodeType === 3) {
                    //         devNodes.push(item)
                    //     }
                    // })
                    aObj.after(`<span class='show-dev tree-item ${_videoShopObj.hideDev ? 'off-dev' : ''}' id='showDev_${treeNode.uniqueCode}' title="${_videoShopObj.hideDev ? '显示设备' : '隐藏设备'}"></span>`)
                    $(`#showDev_${treeNode.uniqueCode}`).on('click', function () {
                        _videoShopObj.hideDev = !_videoShopObj.hideDev
                        if (_videoShopObj.hideDev) {
                            zTree.showNodes(devNodes)
                            $("#showDev_001").attr('title', '隐藏设备')
                            $("#showDev_001").removeClass("off-dev")
                        } else {
                            zTree.hideNodes(devNodes)
                            $("#showDev_001").attr('title', '显示设备')
                            $("#showDev_001").addClass("off-dev")
                        }
                        _videoShopObj.initShopTree(null)
                    })
                }
            }
        },
        // async: {
        //     enable: false,
        //     autoParam: ["id=parentId", "nodeType=nodeType"],
        //     url: function () {
        //         // arg = arguments[1]
        //         if (_videoShopObj.storeIds.length != 0 && _videoShopObj.activeIndex == 2) {
        //             return basePath + '/membership/tree/zTree'
        //         }
        //         return basePath + '/membership/tree/zTree'
        //         // return '/membership/tree/zTree?type=6&searchKey=' + _searchKey
        //     },
        //     type: "get",
        //     otherParam: {
        //         "type": function() {
        //             return (_videoShopObj.storeIds.length != 0 && _videoShopObj.activeIndex == 2) ? '1;0_' + _videoShopObj.storeIds + ':1:1:1;' + (_videoShopObj.hideDev ? 0 : 1) + ';1::0' : '1;0:0:1:1;' + (_videoShopObj.hideDev ? 0 : 1) + ';1::0'
        //         },
        //         "searchKey": function() {
        //             return decodeURIComponent(_searchKey)
        //         }
        //     },
        //     token: sessionStorage.token || localStorage.token,
        //     dataFilter: function (treeId, parentNode, responseData) {
        //         console.log('videoshop tree dataFilter')
        //         if (responseData.success) {
        //             responseData = responseData.data
        //             console.log('success data:' + JSON.stringify(responseData))
        //             if(!responseData.length) {
        //                 return
        //             }
        //             setIcon(responseData)
        //             if(responseData[0].uniqueCode === '001') {
        //                 responseData[0].iconSkin = 'rootdept'
        //             }
        //             setShowName(responseData)
        //             return responseData
        //         }
        //         console.log(JSON.stringify(responseData))
        //     }
        // },
        data: {
            key: {
                name: 'showName'
            },
            simpleData: {
                enable: true,
                idKey: "id",
                pIdKey: "parentId",
                rootPId: "001"
            }
        },
        callback: {
            // onClick: function (event, treeId, treeNode) { //点击树
            //     console.log('-------------------------onClick videoshop--------------------')
            //     try{console.log(JSON.stringify(treeNode));}catch(e){e && console.log(e.stack);}
            //     let node = treeNode
            //     if(treeNode.nodeType === 3) {
            //         node = treeNode.getParentNode()
            //     }
            //     clickCB && clickCB(node);
            //     //refreshTable(treeNode);
            // },
            onDblClick: function (event, treeId, treeNode) {
                openV && openV([treeNode])
            },
            // onAsyncSuccess: function (event, treeId, treeNode, msg) {
            //     let rootNode = zTree.getNodes()[0]
            //     changeStatus(onlineChannels)
            //     console.log('videoshop tree rootNode: ')
            //     rootNode && console.log(rootNode.name)
            //     _getTreeNodeCountFn(!rootNode)
            //     if (_searchKey) {
            //         _searchKey = ''
            //         let nodes = zTree.transformToArray(zTree.getNodes())
            //         zTree.expandAll(true)
            //         nodes.forEach((item) => {
            //             showDev(item)
            //         })
            //     } else {
            //         if (rootNode) {
            //             zTree.expandNode(rootNode, true, false)
            //         }
            //         showDev(treeNode)
            //     }
            //     vue.isFunction(handleAsyncSuccess) && handleAsyncSuccess(treeNode)
            // },
            // beforeAsync: function () {
            //     console.log('------------------beforeAsync--------------------')
            //     return true
            // },
            onExpand: function (e, treeId, treeNode) {
                console.log('------------------onExpand--------------------')
                console.log(JSON.stringify(treeNode))
            },
            // onAsyncError: function (argument) {
            //     console.log('----------videoshop onAsyncError----------')
            //     console.log(JSON.stringify(argument))
            // }
        }
    })
function showDev(treeNode) {
    if (treeNode && objectNodeType.indexOf(treeNode.nodeType) !== -1) {
        if (_videoShopObj.hideDev) {
            zTree.expandNode(treeNode, true, true, true)
            $(`#${treeNode.tId}_ul>li>span`).addClass('hide-node')
            $(`#${treeNode.tId}_ul>li>a`).addClass('hide-node')
            $(`#${treeNode.tId}_ul>li>ul`).addClass('pdl0')
        } else {
            $(`#${treeNode.tId}_ul>li>span`).removeClass('hide-node')
            $(`#${treeNode.tId}_ul>li>a`).removeClass('hide-node')
            $(`#${treeNode.tId}_ul>li>ul`).removeClass('pdl0')
        }
    }
}
function setShowName(treeNodes) {
    for(let i = 0, length = treeNodes.length; i < length; i++) {
        let onLineChannelNum = treeNodes[i] && treeNodes[i].onLineChannelNum ? treeNodes[i].onLineChannelNum : 0
        let totalChannelNum = treeNodes[i] && treeNodes[i].totalChannelNum ? treeNodes[i].totalChannelNum : 0
        if(treeNodes[i] && (treeNodes[i].nodeType == 1 || objectNodeType.indexOf(treeNodes[i].nodeType) !== -1)) {
            treeNodes[i].showName = treeNodes[i].name + '(' + onLineChannelNum + '/' + totalChannelNum + ')'
        } else {
            treeNodes[i].showName = treeNodes[i].name
        }
        treeNodes[i].children && setShowName(treeNodes[i].children)
    }
}

/**
 * @method openChannel() 过滤通道播放通道
 */
function openChannel(data, treeNode, isCloseAllVideo) {
    let channels = []
    let len = data.length
    for (var i = 0; i < len; i++) {
      if (data[i].nodeType == 3) {
        //设备
        for (var j = 0, jL = data[i].children.length; j < jL; j++) {
            if (data[i].children[j]) {
                //data[i].children[j].devName = data[i].name
                data[i].children[j].parentId = treeNode.uniqueCode
                data[i].children[j].parentName = treeNode.name
                channels.push(data[i].children[j])
            }
        }
      } else if (data[i].nodeType == 4) {
        // 通道
        data[i].parentId = treeNode.uniqueCode
        data[i].parentName = treeNode.parentName
        channels.push(data[i])
      }
    }
    openV && openV(channels, true, isCloseAllVideo)
}
function getChannels(treeNode, bl, isCloseAllVideo) { //获取所有通道
    fetch({
        method: 'get',
        url: '/membership/tree/zTree',
        isSNoTip: true,
        data: {
            params: {
                type: '1;0:0:1:1;1;1::0',
                nodeType: treeNode.nodeType,
                parentId: treeNode.uniqueCode
            }
        },
        onSuccess: function (res) {
            let data = res.data.data
            openChannel(data, treeNode, isCloseAllVideo)
        }
    });
}

// 给树数据设置iconSkin属性为'dept'
function setIcon(data) {
    $.each(data, function (k, node) {
        if (node.nodeType === 2) {
            node.iconSkin = 'shopIcon'
        } else if (node.nodeType === 1) {
            node.iconSkin = 'dept'
        } else if (node.nodeType === 4) {
            if(node.isOnline === 1) {
                node.iconSkin = 'channelIcon'
            } else {
                node.iconSkin = 'channelIconD'
            }
        } else if(node.nodeType === 3) {
            if(node.isOnline === 1) {
                node.iconSkin = 'deviceIcon'
            } else {
                node.iconSkin = 'deviceIconD'
            }
        } else if (node.nodeType === 10) {
            node.iconSkin = 'buildingIcon'
        } else if (node.nodeType === 11) {
            node.iconSkin = 'unitIcon'
        } else if (node.nodeType === 12) {
            node.iconSkin = 'houseIcon'
        }
        node.children && setIcon(node.children)
    })
}

/*
 * @parameter searchKey 树查询参数
 * @parameter refreshTableFn 刷新页面数据的函数(目前都是刷新table)
 * @parameter getTreeNodeCountFn 告诉页面当前树节点数
 */
export let getShopTree = (searchKey, getTreeNodeCountFn, clickCb, video, elm, id, onAsyncSuccess, videoShopObj) => { //树初始化及加载
    handleAsyncSuccess = onAsyncSuccess
    clickCB = clickCb
    openV = video
    _videoShopObj = videoShopObj
    _searchKey = searchKey || ''
    treeId = id
    _getTreeNodeCountFn = getTreeNodeCountFn || function () {return null}
    return $.Deferred(function (defer) {
        fetch({
            // url: '/gateway/device/api/page',
            url: '/admin/dahua/device',
            method: 'POST',
            isNoLock: true,
            isSNoTip: true,
            data: {pageNum: 1, pageSize: 200, searchKey: _searchKey},
            onSuccess: data => {
              let responseData = data.data.data.pageData
            //   console.log('success data:' + JSON.stringify(responseData))
              let channels = []
              if (responseData.length) {
                responseData.forEach(item => {
                    if (item.channelList) {
                        let channelNameArr = []
                        item.channelList.forEach(channel => {
                            channel.deviceId = item.deviceId
                            channel.devPassword = item.devPassword
                            channel.devUsername = item.devUsername
                            channel.showName = channel.channelName
                            channel.ability = item.ability
                            channel.deviceModel = item.deviceModel
                            channel.storeId = item.storeId
                            channel.storeName = item.storeName
                            channel.brand = item.brand
                            channel.accessSource = item.accessSource
                            if(channel.onlineStatus == 0) {
                                channel.iconSkin = 'channelIconD'
                            } else  {
                                channel.iconSkin = 'channelIcon'
                            }
                            if (!channelNameArr.includes(channel.channelName)) {
                                channels.push(channel)
                                channelNameArr.push(channel.channelName)
                            }
                        })
                        // channels = channels.concat(item.channelList)
                    }
                })
              }
              let root = {
                id: "001",
                isChecked: false,
                isInherit: 0,
                isOpen: true,
                isParent: true,
                name: "根节点",
                nodeType: 1,
                uniqueCode: "001",
                iconSkin: 'rootdept',
                showName: '根节点'
              }
              const reg = new RegExp(decodeURIComponent(_searchKey))
              root.children = channels.filter(item => reg.test(item.channelName))
            //   root.children = channels
              zTree = $.fn.zTree.init($(elm), setting, [root])
              defer.resolve(zTree)
            }
        })

    }).promise()
}
/**
 * @method GetLeToken 获取乐橙的token
 */
 export function GetLeToken() {
    return new Promise((resolve, reject) => {
        fetch({
            // url: '/gateway/device/api/lechangeToken',
            url: '/admin/dahua/lechange',
            method: 'post',
            isSNoTip: true,
            isNoLock: true,
            timeout: 1000000,
            onSuccess: data => {
                resolve(data)
            }
        })
    })
}
/*
 * @parameter searchKey 树查询参数
 * @parameter refreshTableFn 刷新页面数据的函数(目前都是刷新table)
 * @parameter getTreeNodeCountFn 告诉页面当前树节点数
 */
export let changeStatus = (param) => {
    onlineChannels = param
    var treeObj = $.fn.zTree.getZTreeObj(treeId);
    for(var i = 0, len = param.length; i < len; i++) {
        var node = treeObj.getNodesByParam("deviceId", param[i].deviceID, null)
        if(node && node.length) {
            for(var j = 0, nlen = node.length; j < nlen; j++) {
               if(node[j].channelId == param[i].channelID) {
                   if(param[i].status == 0) {
                      node[j].iconSkin = 'channelIcon'
                   } else  {
                      node[j].iconSkin = 'conline'
                   }
                    node[j].iconSkin = node[j].onlineStatus === 1 ? node[j].iconSkin : 'channelIconD'
                    treeObj.updateNode(node[j])
               }
            }
        }
    }
}

export function onDataSuccess() {
    let rootNode = zTree.getNodes()[0]
    // changeStatus(onlineChannels)
    console.log('videoshop tree rootNode: ')
    rootNode && console.log(rootNode.name)
    _getTreeNodeCountFn(!rootNode)
    if (_searchKey) {
        _searchKey = ''
        zTree.expandAll(true)
    } else {
        if (rootNode) {
            zTree.expandNode(rootNode, true, false)
        }
        showDev(null)
    }
    vue.isFunction(handleAsyncSuccess) && handleAsyncSuccess()
}

export let setDev = showDev