//****REPLACEMENTFUNCTION****//
console.log('globalJS执行')
var _pagemodel
var _resources
var _sessionid
var _modellist
var _echarts
var _loader
var _webapiprefix
var _page
var _uuid
var _calbacksuccess = []
var _websocketsqlg
var _websocketWrite
var _writeBack
var _storlog
var _moment
var $ = $ ? $ : null
var _router
var _ReconnectingWebSocketobj
var _websocketall
var _websocketprefix
var _ReconnectingWebSocket
var _md5
var _localforage
var WsCommands
//****REPLACEGLOBALFUNCTION****//

function installCode(loader, webapiprefix, sessionid, modellist, pagemodel, resources, page, echarts, ReconnectingWebSocket, websocketprefix, uuid,
    storlog, moment, jquery, router, md5, localforage, WsCommands1) {
    _moment = moment
    _storlog = storlog
    _uuid = uuid
    _loader = loader
    _webapiprefix = webapiprefix
    _pagemodel = pagemodel   
    _resources = resources
    _sessionid = sessionid
    _modellist = modellist
    _echarts = echarts
    _page = page
    $ ? $ = $ : $ = jquery
    _router = router
    _websocketprefix=websocketprefix
    _ReconnectingWebSocketobj = ReconnectingWebSocket
    _md5 = md5
    _localforage = localforage
    WsCommands = WsCommands1 // 新的 websocket
    //  事件注册，应该在加载之后将控件遍历判断其内部事件是否存在
}

function runCode () {  // 执行此js文件的方法
    registerInputValueChange()
    initwebsocket()
    registerLoadedEvent()
    pageFirstLoad()//页面第一次加载时执行
    setTimeout(()=>{
        registerClickEvent()
    }, 2000)
    
}
//SQL 命令对象
var wscomSQL = {
    Name: 'SQL',
    Arguments: [{
        OperationType: null,
        DbName: null,
        MessageGuid: null,
        // PK_UPPER_ENTITY: "7d1bca7b-bc11-4317-a36b-03bdff2e6944",
        SQL: null,
        // SessionID: "2eb8f659-7caf-49ba-8ba1-23f04483738d"
    }]
  }
  //SIM 命令对象 读取变量
  var wscomSIM = {
    Name: "SIMDATAINPIPE",
    Arguments: [{
        Variables: null,
        MessageGuid: null,
        // PK_UPPER_ENTITY: "7d1bca7b-bc11-4317-a36b-03bdff2e6944",
        IsCalcValue: true,
        // SessionID: "2eb8f659-7caf-49ba-8ba1-23f04483738d"
    }]
  }
  //修改变量
  var wscomWRITE = {
    Name: 'BATCHWRITE',
    Arguments: [{
        VariableCodes: [],
        VariableValues: []
    }]
  }
  //连接性
  var wscomCON = {
    Name: 'CONNECTION',
    Arguments: [{}]
  }
  //upper状态
  var wscomSTA = {
    Name: 'STATUS',
    Arguments: []
  }
  //
  var wscomSYS = {
    Name: 'SYSTEMSTATUS',
    Arguments: [{}]
  }
  // 下发
  var wscomDEP = {
    Name: 'DEPLOY',
    Arguments: [{}]
  }
  // 读取归档变量
  var wscomARC = {
    Name: 'ARCHIVEDATA',
    Arguments: [{
        Variables: [],
        IntervalValue: 1,
        Type: 5,
        StartTime: "2020-01-20T01:00:16",
        EndTime: "2019-01-20T01:40:16"
    }]
  }
  // 读取归档报警变量
  var wscomALA = {
    Name: 'ALARMDATA',
    Arguments: [{
        Variables: [],
        IntervalValue: 1,
        Type: 1,
        StartTime: "2020-01-20T01:00:16",
        EndTime: "2020-01-20T01:40:16"
    }]
  }
  // 设备运行状态
  var wscomSIMD = {
    Name: 'SIMDEVICE',
    Arguments: [{
      Devices: [],
    }]
  }
//
function initwebsocket() {  //  初始化websocket对象
    _websocketall = new _ReconnectingWebSocketobj(_websocketprefix, null)
    _websocketall.onmessage = (event) => {
        var obj = JSON.parse(event.data);
        if (obj.CommandName === 'SQL' || obj.CommandName === 'ARCHIVEDATA' || obj.CommandName === 'ALARMDATA') {
            if (obj.Value !== null) {
                if (obj.Value.Ex !== null) {
                    // if (error) {
                        _calbacksuccess.forEach((objsu) => {
                            if (objsu.name === obj.Value.Guid) {                                
                                objsu.callbackerr(obj.Value.Ex);
                                removeSuccessCallBack(objsu.name);
                            }
                        });
                    // }
                } else {
                    _calbacksuccess.forEach((objsu) => {
                        if (objsu.name === obj.Value.Guid) {
                            objsu.callbacksucc(obj.Value);
                            removeSuccessCallBack(objsu.name);
                        }
                    });
                }
            }
        }
    };
    // _websocketall.open();
}
function registerClickEvent() {  // 单击事件
    //****CLICKEVENT****//
    console.log('click事件')
    _modellist.forEach((iteam) => {
        // console.log('对象是', iteam)
    })
}

function registerLoadedEvent() {  //  加载事件
    for (let i = 0; i < _modellist.length; i++) {
        let elementmodel = _modellist[i]
        //****LOADEDEVENT****//
    }
}

function registerInputValueChange() { // 元素值改变事件
    //****INPUTVALUECHANGEEVENT****//
}

function pageFirstLoad() {
    //****RELACEMENTCODE****//
}


// function registerValueChangedEvent(modellist, page, echarts, callback) {  //变量值改变事件
//     // closeWebSocket()
//     return new Promise((resolve, reject) => {
//     })
// }
function getDataByWebsocketWork(modellist, models, ro) {
    let re = /\{[^\}]+\}/g
    let varcodes= []
    ro.forEach((rItem)=>{
        varcodes.push({SVARCODE:rItem.SVARCODE, PK: rItem.PK})
    })
    for (let i = 0; i < modellist.length; i++) {
        for (let j = 0; j < ro.length; j++) {
            //变量代码
            if (modellist[i].variable === ro[j].SVARCODE) {
                modellist[i].PK_VARIABLE = ro[j].PK
                break;
            }

            //变量代码组 [A1,B1]  var tags = [{ name: A1,PK:2219 }, { name: B1 }]
            if (modellist[i].tags !== undefined && modellist[i].tags.arr.length !== 0) {
                modellist[i].tags.arr.forEach((item) => {
                    if (item.FullName === ro[j].SVARCODE) {
                        item.PK = ro[j].PK
                    }
                })
            }

        }
    }
    wscomSIM.Arguments[0].Variables= varcodes
    WsCommands(wscomSIM, (ro)=>{
        var data=ro.PDatasMsg?ro.PDatasMsg:ro.pDataWebSockets
        var isUpper = ro.PDatasMsg?0:1
        data.forEach(variable => {
            modellist.forEach((m) => {
                if (m.PK_VARIABLE === variable.PK) {
                    let newvalue = isUpper==0?getValueFromPDataMessage(variable):variable.Value
                    let haschange = m.text !== newvalue
                    if (haschange) {
                        m.tagValue = isUpper==0?getValueFromPDataMessage(variable):variable.Value
                        m.tagValueCalc = isUpper==0?getValueCalcFromPDataMessage(variable):variable.CalcValue
                        if (m.tagValueCalc === null) {
                            if (m.number !== undefined) {
                                m.number = m.tagValue
                            } else {
                                m.text = m.tagValue
                            }

                        } else {
                            m.text = m.tagValueCalc
                        }
                    }
                }
                //把对象传给modellist[i].tags
                if (m.tags && m.tags.arr.length !== 0) {
                    //获取时间 给没有时间戳的变量赋值
                    const mydate = new Date()                        
                    const timestamp = `${mydate.getTime()}`
                    m.tags.CommandName = 'SIMDATAINPIPE'
                    m.tags.arr.forEach((item) => {
                        if (item.PK === variable.PK) {
                            item.tagValue = isUpper==0?getValueFromPDataMessage(variable):variable.Value
                            item.tagValueCalc = isUpper==0?getValueCalcFromPDataMessage(variable):variable.CalcValue
                            if (item.Timestamp == null) {
                                item.Timestamp = timestamp
                            }
                            item.Quality = variable.Quality
                            item.ErrorCode = variable.ErrorCode

                            m.tags.currentVariable = item

                            valueChangeEvent()
                        }
                    })
                    m.tags.time = timestamp
                }
            })
        })
        // 新加属性绑定变量
        models.forEach((m, i) => {
            if (!m.stopRelaVariable) {
                for (let i = 0; i < m.relaVariable.length; i++) {
                    let item = m.relaVariable[i]
                    let flag = true
                    let str = item.value
                    let varcodes = []
                    item.value.match(re).forEach((code)=>{
                        varcodes.push(code.replace(/{/,'').replace(/}/,''))
                    })
                    let lastStr = ''
                    for (let n = 0; n < varcodes.length; n++) {
                        let code = varcodes[n]
                        let variable = data.find(variable => {
                            if (variable.FullName == code) {
                                return variable
                            }
                        })
                        if (variable) { // 如果变量code正确
                            let newvalue = isUpper==0?getValueCalcFromPDataMessage(variable):variable.CalcValue
                            if (newvalue.toLowerCase() == 'true') {
                                newvalue = 'true'
                            } else if (newvalue.toLowerCase() == 'false') {
                                newvalue = 'false'
                            } else if (newvalue.toLowerCase() == 'undefined') {
                                newvalue = ''
                            }
                            let newValue1 = newvalue == ''? newvalue : ('(' + newvalue + ')')
                            lastStr = lastStr===''?item.value.replace('{'+variable.FullName+'}', newValue1):lastStr.replace('{'+variable.FullName+'}', newValue1)
                            for (let i = 0;i < 1; i++) {
                                let temp = lastStr.replace('{'+variable.FullName+'}', newvalue)
                                if (temp != lastStr) {
                                    lastStr = temp
                                    i--
                                }
                            }
                            str = lastStr
                        } else {
                            flag = false
                            break
                        }
                    }
                    if (flag) {
                        try{
                            let box = $("#errorBox_"+ m.id)
                            if (box[0]) {
                                box.css('display', 'none')
                            }
                            // 将最终计算结果是数字的保留三位小数点
                            if (m[item.property] == undefined) {
                                console.log(item.property, 'undefined')
                            }
                            if (!item.valueType || item.valueType == 'direct') { // 判断是否直接赋值
                                m[item.property] = typeof(eval(str)) == 'undefined'? '' : typeof(eval(str)) === 'number'?Math.round(eval(str)*1000)/1000:eval(str)
                            } else if (item.valueType == 'boolean') {
                                m[item.property] = eval(str) ? item.booleanValue[0]: item.booleanValue[1]
                            }
                        }
                        catch(err) {
                            // console.log(m.controltype+'err:', err)
                            // console.log('原文:', item.value)
                            // m.stopRelaVariable = true
                        }
                    } else { // 如果code出错 显示！图片
                        let box = $("#errorBox_"+ m.id)
                        if (!box[0]) {
                            $('div#813ca38e-b267-4e39-82bb-9a16c7060533').append($(`<div id='errorBox_`+ m.id +`' 
                            style='width:`+ m.width +`px;
                            height:`+ m.height +`px;
                            transform:translate(`+ m.x +`px,`+m.y+`px) rotate(`+m.angle+`deg);
                            z-index:`+ (Number(m.depth+1))+`;
                            background: rgba(0,0,0,0.3);
                            position:absolute'>
                            <svg class="icon" width="100%" height="100%" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg">
                            <path fill="#d81e06" d="M728.387305 512 512 137.205918 295.612695 512 79.225389 886.794082l432.774611 0 432.774611 0L728.387305 512zM543.777751 816.562531c-8.993838 7.992021-19.48682 11.992125-31.478945 11.992125-12.192693 0-22.836101-3.947915-31.928177-11.841699-9.097192-7.892761-13.640672-18.934235-13.640672-33.127492 0-12.389168 4.347005-22.934339 13.041014-31.628348s19.336394-13.041014 31.928177-13.041014 23.333428 4.347005 32.228005 13.041014c8.890484 8.694009 13.340843 19.23918 13.340843 31.628348C557.26902 797.577131 552.772612 808.570509 543.777751 816.562531zM555.170219 477.243405l-12.891611 147.800207c-1.399883 17.58961-4.39817 31.080879-8.993838 40.472783-4.599761 9.397021-12.192693 14.090926-22.784936 14.090926-10.79281 0-18.287505-4.54348-22.485107-13.640672-4.197602-9.092076-7.194866-22.934339-8.993838-41.521672l-9.593496-143.602605c-1.798972-27.979238-2.698458-48.065715-2.698458-60.259432 0-16.58677 4.347005-29.529547 13.041014-38.823214s20.133549-13.9405 34.326806-13.9405c17.187451 0 28.677133 5.948479 34.476209 17.838274 5.794983 11.893888 8.694009 29.033243 8.694009 51.414997C557.26902 450.26189 556.567032 463.653899 555.170219 477.243405z" />
                            </svg></div>`))
                        } else {
                            box.css('display', 'block')
                        }
                        break
                    }
                }
            }
        })
    })
}
function registerValueChangedEvent(modellist, page, echarts, callback) {  //获取实时变量方法 变量值改变事件
    // closeWebSocket()
    return new Promise((resolve, reject) => {
        let varcodes = []
        let models = []
        let re = /\{[^\}]+\}/g
        for (let i = 0; i < modellist.length; i++) {
            if (modellist[i].variable !== undefined && modellist[i].variable !== null && modellist[i].variable !== '') {
                varcodes.push(modellist[i].variable)
            }
            if (modellist[i].variablesArr !== undefined && modellist[i].variablesArr.length !== 0) {
                varcodes.push(...modellist[i].variablesArr)
            }
            if (modellist[i].relaVariable){ // 把需要绑定变量的变量存入
                if (modellist[i].relaVariable.length > 0){
                    modellist[i].stopRelaVariable = false
                    models.push(modellist[i])
                    modellist[i].relaVariable.forEach((item) => {
                        // console.log('line131', item.value.match(re))
                        item.value.match(re).forEach((code)=>{
                            let code1 = code.replace(/{/,'').replace(/}/,'')
                            if(varcodes.indexOf(code1) == -1) varcodes.push(code1)
                        })
                    })
                }
            }
        }
        if (varcodes.length === 0) {
            return
        }
        // getDataByWebsocketWork(modellist, models, varcodes); return // 新 l
        page.getVariablesByCodes(varcodes, _pagemodel.PK_UPPER_ENTITY, (ro) => {
            getDataByWebsocketWork(modellist, models, ro); return // 新 l
            var roArrArr=[]
            var roArr = []
            ro.forEach((item,index) => {
                roArr.push({PK: item.PK,SVARCODE: item.SVARCODE})
                if(!roArrArr[parseInt(index/30)]) {
                    roArrArr[parseInt(index/30)]=[]
                }
                roArrArr[parseInt(index/30)].push({PK: item.PK,SVARCODE: item.SVARCODE})
            })
            // 临时处理分组问题，将带公式（需要多个变量）的变量分在第一组 by leo 2019-9-28
            var codes = [] //所有带多个变量公式变量数组
            modellist.forEach((modelItem,modelIndex)=>{
                if(modelItem.relaVariable){
                    if(modelItem.relaVariable.length > 0){
                        modelItem.relaVariable.forEach((rvItem,rvIndex)=>{
                            if(rvItem.value.match(re).length>1){
                                rvItem.value.match(re).forEach((cItem)=>{
                                    codes.push(cItem)
                                })
                            }
                        })
                    }
                }
            })
            去重
            let result = []
            let obj = {}

            for (let c of codes) {
                if (!obj[c]) {
                    result.push(c)
                    obj[c] = 1
                }
            }
            
            
            // 先将带多个变量公式的变量分到第一组
            roArrArr = []
            roArrArr[0] = []
            roArrArrNo = []
            ro.forEach((rItem)=>{
                var isCodes = 0
                result.forEach((reItem)=>{
                    if(((reItem).replace(/{/,'').replace(/}/,'')) === rItem.SVARCODE){
                        roArrArr[0].push({PK:rItem.PK,SVARCODE:rItem.SVARCODE})
                        isCodes = 1
                    }
                })
                if(!isCodes){
                    roArrArrNo.push({PK:rItem.PK,SVARCODE:rItem.SVARCODE})
                }
            })
            if(roArrArr[0].length>30){
                console.log('多个变量公式的变量超过30，数据将异常！')
            }
            // 再将剩余的变量按照30一组进行分组
            // console.log('line210', roArrArrNo)
            // console.log('line210', roArrArrNo)
            var roi = 1
            roArrArrNo.forEach((roItem,roIndex)=>{
                if(roArrArr[0].length<30){
                    roArrArr[0].push(roItem)
                }else{
                    if(roArrArr[roi]== undefined){
                        roArrArr[roi] = []
                        roArrArr[roi].push(roItem)
                    }else{
                        if(roArrArr[roi].length>=30){
                            roi++
                            roArrArr[roi] = []
                            roArrArr[roi].push(roItem)
                        }else{
                            roArrArr[roi].push(roItem)
                        }
                    }
                    
                }
            })

            for (let i = 0; i < modellist.length; i++) {
                for (let j = 0; j < ro.length; j++) {
                    //变量代码
                    if (modellist[i].variable === ro[j].SVARCODE) {
                        modellist[i].PK_VARIABLE = ro[j].PK
                        break;
                    }

                    //变量代码组 [A1,B1]  var tags = [{ name: A1,PK:2219 }, { name: B1 }]
                    if (modellist[i].tags !== undefined && modellist[i].tags.arr.length !== 0) {
                        modellist[i].tags.arr.forEach((item) => {
                            if (item.FullName === ro[j].SVARCODE) {
                                item.PK = ro[j].PK
                            }
                        })
                    }

                }
            }
            let wscommands = []
            let _ReconnectingWebSockets = []
            for(let i = 0; i < roArrArr.length; i++) {
                // let wscommand = {}
                wscommands[i] = {}
                wscommands[i].Name = 'SIMDATAINPIPE'
                wscommands[i].Arguments = [{
                    Variables: roArrArr[i],
                    PK_UPPER_ENTITY: _pagemodel.PK_UPPER_ENTITY,
                    IsCalcValue: true,
                    SessionID: _sessionid
                }]

                if (_ReconnectingWebSockets[i] === undefined) {
                    _ReconnectingWebSockets[i] = _resources.getWebSocket()
                    // _ReconnectingWebSockets[i].open()
                    _ReconnectingWebSockets[i].onopen = function (event) {
                        _ReconnectingWebSockets[i].send(JSON.stringify(wscommands[i])) // 发送获取状态信息的命令
                    }
                } else {
                    if (_ReconnectingWebSockets[i].readyState !== 1) {
                        // _ReconnectingWebSockets[i].open()
                        _ReconnectingWebSockets[i].onopen = function (event) {
                            _ReconnectingWebSockets[i].send(JSON.stringify(wscommands[i])) // 发送获取状态信息的命令
                        }
                    } else {
                        _ReconnectingWebSockets[i].send(JSON.stringify(wscommands[i])) // 发送获取状态信息的命令
                    }
                }
                _ReconnectingWebSockets[i].onmessage = (event) => {
                
                    //把对象传给modellist[i].tags
                    let obj = JSON.parse(event.data)
                    // console.log('obj: ', obj)
                    if (obj.CommandName === 'SIMDATA') {
                        this.pdata = obj.Value
                        modellist.forEach((m) => {
                            if (m.PK_VARIABLE === obj.Value.PK) {
                                let newvalue = getValueFromPDataMessage(obj.Value)
                                let haschange = m.text !== newvalue
                                if (haschange) {
                                    m.tagValue = getValueFromPDataMessage(obj.Value)
                                    m.tagValueCalc = getValueCalcFromPDataMessage(obj.Value)
                                    if (m.tagValueCalc === null) {
                                        if (m.number !== undefined) {
                                            m.number = m.tagValue
                                        } else {
                                            m.text = m.tagValue
                                        }
    
                                    } else {
                                        m.text = m.tagValueCalc
                                    }
    
                                }
                            }
                            //把对象传给modellist[i].tags
                            if (m.tags && m.tags.arr.length !== 0) {
                                //获取时间 给没有时间戳的变量赋值
                                const mydate = new Date()                        
                                const timestamp = `${mydate.getTime()}`
                                m.tags.time = timestamp
                                m.tags.arr.forEach((item) => {
                                    if (item.PK === obj.Value.PK) {
                                        item.tagValue = getValueFromPDataMessage(obj.Value)
                                        item.tagValueCalc = getValueCalcFromPDataMessage(obj.Value)
                                        if (item.Timestamp == null) {
                                            item.Timestamp = timestamp
                                        }
                                        item.Quality = obj.Value.Quality
                                        item.ErrorCode = obj.Value.ErrorCode
    
                                        m.tags.currentVariable = item
    
                                        valueChangeEvent()
                                    }
                                })
                            }
                        })
                    } else if (obj.CommandName === 'SIMDATAINPIPE') {
                        // console.log('obj.CommandName: ', obj.CommandName)
                        // console.log('obj.Value: ', obj.Value)
                        // console.log('obj.Value.PDatasMsg: ', obj.Value.PDatasMsg)
                        
                        var data=obj.Value.PDatasMsg?obj.Value.PDatasMsg:obj.Value.pDataWebSockets
                        var isUpper = obj.Value.PDatasMsg?0:1
                        data.forEach(variable => {
                            modellist.forEach((m) => {
                                if (m.PK_VARIABLE === variable.PK) {
                                    let newvalue = isUpper==0?getValueFromPDataMessage(variable):variable.Value
                                    let haschange = m.text !== newvalue
                                    if (haschange) {
                                        m.tagValue = isUpper==0?getValueFromPDataMessage(variable):variable.Value
                                        m.tagValueCalc = isUpper==0?getValueCalcFromPDataMessage(variable):variable.CalcValue
                                        if (m.tagValueCalc === null) {
                                            if (m.number !== undefined) {
                                                m.number = m.tagValue
                                            } else {
                                                m.text = m.tagValue
                                            }
            
                                        } else {
                                            m.text = m.tagValueCalc
                                        }
                                    }
                                }
                                //把对象传给modellist[i].tags
                                if (m.tags && m.tags.arr.length !== 0) {
                                    //获取时间 给没有时间戳的变量赋值
                                    const mydate = new Date()                        
                                    const timestamp = `${mydate.getTime()}`
                                    m.tags.CommandName = obj.CommandName
                                    m.tags.arr.forEach((item) => {
                                        if (item.PK === variable.PK) {
                                            item.tagValue = isUpper==0?getValueFromPDataMessage(variable):variable.Value
                                            item.tagValueCalc = isUpper==0?getValueCalcFromPDataMessage(variable):variable.CalcValue
                                            if (item.Timestamp == null) {
                                                item.Timestamp = timestamp
                                            }
                                            item.Quality = variable.Quality
                                            item.ErrorCode = variable.ErrorCode
            
                                            m.tags.currentVariable = item
            
                                            valueChangeEvent()
                                        }
                                    })
                                    m.tags.time = timestamp
                                }
                            })
                        })
                        // 新加属性绑定变量
                        models.forEach((m, i) => {
                            if (!m.stopRelaVariable) {
                                for (let i = 0; i < m.relaVariable.length; i++) {
                                    let item = m.relaVariable[i]
                                    let flag = true
                                    let str = item.value
                                    let varcodes = []
                                    item.value.match(re).forEach((code)=>{
                                        varcodes.push(code.replace(/{/,'').replace(/}/,''))
                                    })
                                    let lastStr = ''
                                    for (let n = 0; n < varcodes.length; n++) {
                                        let code = varcodes[n]
                                        let variable = data.find(variable => {
                                            if (variable.FullName == code) {
                                                return obj
                                            }
                                        })
                                        if (variable) { // 如果变量code正确
                                            let newvalue = isUpper==0?getValueCalcFromPDataMessage(variable):variable.CalcValue
                                            if (newvalue.toLowerCase() == 'true') {
                                                newvalue = 'true'
                                            } else if (newvalue.toLowerCase() == 'false') {
                                                newvalue = 'false'
                                            } else if (newvalue.toLowerCase() == 'undefined') {
                                                newvalue = ''
                                            }
                                            let newValue1 = newvalue == ''? newvalue : ('(' + newvalue + ')')
                                            lastStr = lastStr===''?item.value.replace('{'+variable.FullName+'}', newValue1):lastStr.replace('{'+variable.FullName+'}', newValue1)
                                            for (let i = 0;i < 1; i++) {
                                                let temp = lastStr.replace('{'+variable.FullName+'}', newvalue)
                                                if (temp != lastStr) {
                                                    lastStr = temp
                                                    i--
                                                }
                                            }
                                            str = lastStr
                                        } else {
                                            flag = false
                                            break
                                        }
                                    }
                                    if (flag) {
                                        try{
                                            let box = $("#errorBox_"+ m.id)
                                            if (box[0]) {
                                                box.css('display', 'none')
                                            }
                                            // 将最终计算结果是数字的保留三位小数点
                                            if (m[item.property] == undefined) {
                                                console.log(item.property, 'undefined')
                                            }
                                            if (!item.valueType || item.valueType == 'direct') { // 判断是否直接赋值
                                                m[item.property] = typeof(eval(str)) == 'undefined'? '' : typeof(eval(str)) === 'number'?Math.round(eval(str)*1000)/1000:eval(str)
                                            } else if (item.valueType == 'boolean') {
                                                m[item.property] = eval(str) ? item.booleanValue[0]: item.booleanValue[1]
                                            }
                                        }
                                        catch(err) {
                                            // console.log(m.controltype+'err:', err)
                                            // console.log('原文:', item.value)
                                            // m.stopRelaVariable = true
                                        }
                                    } else { // 如果code出错 显示！图片
                                        let box = $("#errorBox_"+ m.id)
                                        if (!box[0]) {
                                            $('div#813ca38e-b267-4e39-82bb-9a16c7060533').append($(`<div id='errorBox_`+ m.id +`' 
                                            style='width:`+ m.width +`px;
                                            height:`+ m.height +`px;
                                            transform:translate(`+ m.x +`px,`+m.y+`px) rotate(`+m.angle+`deg);
                                            z-index:`+ (Number(m.depth+1))+`;
                                            background: rgba(0,0,0,0.3);
                                            position:absolute'>
                                            <svg class="icon" width="100%" height="100%" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg">
                                            <path fill="#d81e06" d="M728.387305 512 512 137.205918 295.612695 512 79.225389 886.794082l432.774611 0 432.774611 0L728.387305 512zM543.777751 816.562531c-8.993838 7.992021-19.48682 11.992125-31.478945 11.992125-12.192693 0-22.836101-3.947915-31.928177-11.841699-9.097192-7.892761-13.640672-18.934235-13.640672-33.127492 0-12.389168 4.347005-22.934339 13.041014-31.628348s19.336394-13.041014 31.928177-13.041014 23.333428 4.347005 32.228005 13.041014c8.890484 8.694009 13.340843 19.23918 13.340843 31.628348C557.26902 797.577131 552.772612 808.570509 543.777751 816.562531zM555.170219 477.243405l-12.891611 147.800207c-1.399883 17.58961-4.39817 31.080879-8.993838 40.472783-4.599761 9.397021-12.192693 14.090926-22.784936 14.090926-10.79281 0-18.287505-4.54348-22.485107-13.640672-4.197602-9.092076-7.194866-22.934339-8.993838-41.521672l-9.593496-143.602605c-1.798972-27.979238-2.698458-48.065715-2.698458-60.259432 0-16.58677 4.347005-29.529547 13.041014-38.823214s20.133549-13.9405 34.326806-13.9405c17.187451 0 28.677133 5.948479 34.476209 17.838274 5.794983 11.893888 8.694009 29.033243 8.694009 51.414997C557.26902 450.26189 556.567032 463.653899 555.170219 477.243405z" />
                                            </svg></div>`))
                                        } else {
                                            box.css('display', 'block')
                                        }
                                        break
                                    }
                                }
                            }
                        })
                    }
                }
                _ReconnectingWebSockets[i].onerror = function (err) {
                    console.log('err:7777777 ', err)
                }
                callback && callback()
                resolve(_ReconnectingWebSockets[i])
            }
        }, (err) => {
            vue.$message.error(`连接失败！`)
            toastr.showError(err.Message)
            reject(err)
        })
    })
}

function valueChangeEvent () { //变量值改变事件
    //****VALUECHANGEDEVENT****//
}

function loadjs(jsurl, success) {
    let loaderins
    for (let i = 0; i < jsurl.length; i++) {
        if (loaderins == null) {
            loaderins = _loader.load(_webapiprefix + "plugins/" + jsurl[i])
        } else {
            loaderins = loaderins.load(_webapiprefix + "plugins/" + jsurl[i])
        }
    }
    if (loaderins == null) {
        _loader.wait(success)
    } else {
        loaderins.wait(success)
    }
}

function closeWebSocket() {
    try {
        if (_ReconnectingWebSocket && _ReconnectingWebSocket !== null) {
            _ReconnectingWebSocket.close()
        }
    } catch (err) {
        console.log('关闭websocket失败，错误原因是', err)
    }
}

function endEditCallback(editmodel) {
    console.log(editmodel.text)
}

function write(svarcode, svarvalue) {
    // if (!_writeBack) {
    //     _writeBack = {}
    //     _writeBack.svarcodes = svarcode
    //     _writeBack.stopSend = false
    // } else {
    //     if (_writeBack.stopSend) {
    //         let waitDate = new Date(new Date() - _writeBack.stopDate).getSeconds()
    //         if (waitDate >= 30) {
    //             _writeBack.stopSend = true
    //             _writeBack.stopDate = new Date()
    //         } else {
    //             // vue.$message.error(`连接失败！`)
    //             // return
    //         }
    //     } else {
    //         _writeBack.svarcodes = svarcode
    //         _writeBack.stopSend = true
    //         _writeBack.stopDate = new Date()
    //     }
    // }
    if (typeof (_websocketWrite) !== 'undefined') {
        // if (_websocketWrite.readyState !== 1) {
        //     _websocketWrite.open()
        // }
        let wscommand = {}
        wscommand.Name = 'WRITE'
        wscommand.SessionID= _sessionid
        wscommand.Arguments = [{
            VariableCode: svarcode,
            PK_UPPER_ENTITY: _pagemodel.PK_UPPER_ENTITY,
            VariableValue: svarvalue,
            SessionID: _sessionid
        }]
        waitconnection(function () {
            _websocketWrite.send(JSON.stringify(wscommand)) // 发送命令
        }, 1000, _websocketWrite)
        _websocketWrite.onmessage = (event) => {
            var data = JSON.parse(event.data)
            // let flag = data.Value.Result.FullName == _writeBack.svarcodes
            // if (!flag) {
            //     _writeBack.stopSend = true
            // } else {
            //     _writeBack.stopSend = false
            // }
            console.log('data: ', data)
        }
    } else {
        _websocketWrite = _resources.getWebSocket()
        write(svarcode, svarvalue)
    }
}

function writeVariables (svarcodes, svarvalues) {
    if (svarcodes.length == 1 && svarvalues.length == 1) {
        write(svarcodes[0], svarvalues[0])
        return
    }
    // if (!_writeBack) {
    //     _writeBack = {}
    //     _writeBack.svarcodes = svarcodes
    //     _writeBack.stopSend = false
    // } else {
    //     if (_writeBack.stopSend) {
    //         let waitDate = new Date(new Date() - _writeBack.stopDate).getSeconds()
    //         if (waitDate >= 30) {
    //             _writeBack.stopSend = true
    //             _writeBack.stopDate = new Date()
    //         } else {
    //             // vue.$message.error(`连接失败！`)
    //             // return
    //         }
    //     } else {
    //         _writeBack.svarcodes = svarcodes
    //         _writeBack.stopSend = true
    //         _writeBack.stopDate = new Date()
    //     }
    // }
    if (typeof (_websocketWrite) !== 'undefined') {
        // if (_websocketWrite.readyState !== 1) {
        //     _websocketWrite.open()
        // }
        let wscommand = {}
        wscommand.Name = 'BATCHWRITE'
        wscommand.SessionID= _sessionid
        wscommand.Arguments = [{
            VariableCodes: svarcodes,
            PK_UPPER_ENTITY: _pagemodel.PK_UPPER_ENTITY,
            VariableValues: svarvalues,
            SessionID: _sessionid
        }]
        waitconnection(function () {
            _websocketWrite.send(JSON.stringify(wscommand)) // 发送命令
        }, 1000, _websocketWrite)
        _websocketWrite.onmessage = (event) => {
            var data = JSON.parse(event.data)
            // var arr = []
            // let flag = true
            // if (data.Value.Quality == 'BAD') {
            //     _writeBack.stopSend = true
            //     return 
            // }
            // data.Value.Result.forEach((item) =>{
            //     arr.push(item.VariableCode)
            // })
            // _writeBack.svarcodes.forEach((item) => {
            //     if (arr.indexOf(item) == -1) {
            //         flag = false
            //     }
            // })
            // if (!flag) {
            //     _writeBack.stopSend = true
            // } else {
            //     _writeBack.stopSend = false
            // }
            console.log('data: ', data)
        }
    } else {
        _websocketWrite = _resources.getWebSocket()
        writeVariables(svarcodes, svarvalues)
    }
}

function getDataBySQL(sql, sdbname, callbackid, success, error, operationtype) {
    //  _resources.closeWebSocket()
    var objsuc = {}
    objsuc.name = callbackid
    objsuc.sql = sql
    objsuc.callbacksucc = success
    objsuc.callbackerr = error
    _calbacksuccess.push(objsuc)
    // _localforage.getItem(_md5(sql)+'_saveTime').then((value)=>{
        // if(value && ((new Date().getTime())-value)/1000/60/60<1){
        //     _localforage.getItem(_md5(sql)).then((value)=>{
        //         console.log('getDataBySQL缓存读取')
        //         console.log('sql',sql)
        //         console.log('mde(sql)',_md5(sql))
        //         console.log('value:',JSON.parse(value).Value)
        //         success(JSON.parse(value).Value)
        //     })
        // }else{
            if (typeof (_websocketsqlg) !== 'undefined') {
                // if (_websocketsqlg.readyState !== 1) {
                //     _websocketsqlg.open()
                // }
                let wscommand = {}
                wscommand.Name = 'SQL'
                wscommand.SessionID= _sessionid
                wscommand.Arguments = [{
                    OperationType: operationtype,
                    DbName: sdbname,
                    MessageGuid: callbackid,
                    PK_UPPER_ENTITY: _pagemodel.PK_UPPER_ENTITY,
                    SQL: sql,
                    SessionID: _sessionid
                }]
                waitconnection(function () {
                    _websocketsqlg.send(JSON.stringify(wscommand)) // 发送获取状态信息的命令
                }, 1000, _websocketsqlg)
            } else {
                _websocketsqlg = _resources.getWebSocket()
                _websocketsqlg.onmessage = (event) => {
                    let obj = JSON.parse(event.data)
                    if (obj.CommandName === 'SQL') {
                        if (obj.Value !== null) {
                            if (obj.Value.Ex !== null) {
                                // if (error) {
                                    _calbacksuccess.forEach((objsu) => {
                                        if (objsu.name === obj.Value.Guid) {
                                            objsu.callbackerr(obj.Value.Ex)
                                            removeSuccessCallBack(objsu.name)
                                        }
                                    })
                                // }
                            } else {
                                //  if (success) { success(obj.Value.Result) }
                                _calbacksuccess.forEach((objsu) => {
                                    if (objsu.name === obj.Value.Guid) {
                                        // _localforage.setItem(_md5(objsu.sql), event.data)
                                        // _localforage.setItem(_md5(objsu.sql)+'_saveTime', (new Date().getTime())+'')
                                        // console.log('getDataBySQL缓存写入')
                                        // console.log('sql',objsu.sql)
                                        // console.log('value:',obj.Value)
                                        objsu.callbacksucc(obj.Value)
                                        removeSuccessCallBack(objsu.name)
                                    }
                                })
                            }
                        }
                    }
                }
                getDataBySQL(sql, sdbname, callbackid, success, error, operationtype)
            }
        // }
    // }).catch((err)=>{
    //     console.log('line404', err)
    // })
}

function getDataBySQLForModel(wscommand, callbackid, success, error) {
    //  _resources.closeWebSocket()
    var objsuc = {};
    objsuc.name = callbackid;
    objsuc.callbacksucc = success;
    objsuc.callbackerr = error
    _calbacksuccess.push(objsuc);
    if (typeof (_websocketsqlg) !== 'undefined') {
        // if (_websocketsqlg.readyState !== 1) {
        //     _websocketsqlg.open();
        // }
        waitconnection(function () {
            _websocketsqlg.send(JSON.stringify(wscommand)); // 发送获取状态信息的命令
        }, 1000, _websocketsqlg);
    } else {
        _websocketsqlg = _resources.getWebSocket();
        _websocketsqlg.onmessage = (event) => {
            var obj = JSON.parse(event.data);
            if (obj.CommandName === 'SQL' || obj.CommandName === 'ARCHIVEDATA' || obj.CommandName === 'ALARMDATA') {
                if (obj.Value !== null) {
                    if (obj.Value.Ex !== null) {
                        if (error) {
                            _calbacksuccess.forEach((objsu) => {
                                if (objsu.name === obj.Value.Guid) {
                                    error(obj.Value.Ex);
                                    removeSuccessCallBack(objsu.name);
                                }
                            });
                        }
                    } else {
                        _calbacksuccess.forEach((objsu) => {
                            if (objsu.name === obj.Value.Guid) {
                                objsu.callbacksucc(obj.Value);
                                removeSuccessCallBack(objsu.name);
                            }
                        });
                    }
                }
            }
        };
        getDataBySQLForModel(wscommand, callbackid, success, error);
    }
}
function getDataToWebSocket(wscommand, callbackid, success, error) {
    var objsuc = {};
    objsuc.name = callbackid;
    objsuc.callbacksucc = success;
    objsuc.callbackerr = error
    _calbacksuccess.push(objsuc);
    waitconnection(function () {
        _websocketall.send(JSON.stringify(wscommand)); // 发送获取状态信息的命令
    }, 1000, _websocketall)
}
window.onbeforeunload = function () {
    if (_websocketall) {
        _websocketall.close();
    }
}
function waitconnection(callback, interval, websockobj) {
    if (websockobj === undefined || websockobj == null) {
        websockobj = _websocketsqlg
    }
    if (websockobj.readyState === 1) {
        callback()
    } else {
        setTimeout(function () {
            waitconnection(callback, interval, websockobj)
        }, interval)
    }
}
function removeSuccessCallBack(guid) {
    _calbacksuccess.forEach((iteam, index) => {
        if (iteam.name === guid) {
            _calbacksuccess.splice(index, 1)
        }
    })
}
function getDataRowBySQL(sql, sdbname, success, error) {
    _resources.closeWebSocket()
    var websocketsql = _resources.getWebSocket()
    // websocketsql.open()
    websocketsql.onopen = (event) => {
        let wscommand = {}
        wscommand.Name = 'SQL'
        wscommand.SessionID= _sessionid
        wscommand.Arguments = [{
            DbName: sdbname,
            PK_UPPER_ENTITY: _pagemodel.PK_UPPER_ENTITY,
            SQL: sql,
            FetchType: 1,
            SessionID: _sessionid
        }]
        websocketsql.send(JSON.stringify(wscommand)) // 发送获取状态信息的命令
    }

    if (success) {
        websocketsql.onmessage = (event) => {
            let obj = JSON.parse(event.data)
            if (obj.CommandName === 'SQL') {
                if (obj.Value !== null) {
                    if (obj.Value.Ex !== null) {
                        if (error) { error(obj.Value.Ex) }
                    } else {
                        if (success) { success(obj.Value.Result) }
                    }
                }
            }
        }
    } else { }
}

//返回所有的变量信息
function getVariblesAll(success,error) {
    var ResultObject = {}
    var arr=[]
    _page.getVariablesByCodes(arr, _pagemodel.PK_UPPER_ENTITY, success, error)
}

function getModelByID(cellid) {
    for (let i = 0; i < _modellist.length; i++) {
        if (_modellist[i].id === cellid) {
            return _modellist[i]
        }
    }

    return null
}

function getModelByName (modelName) {  // 获取组件标识名对应得组件
    const model = _modellist.find(item => {
        const callStatus = item.hasOwnProperty('name') && item.name && item.name === modelName
        return callStatus
    })

    if (model) { return model }
    else {
        console.log(modelName + '未定义')
        return
    }
}

function getCellTextInDatatableWhenClick(e, colindex) {
    let tdstr = $(e.target)[0].tagName
    if (tdstr === 'TD') {
        let tds = $(e.target).parent('tr').children('td')
        let scode = tds[colindex].innerText
        return scode
    } else {
        return '';
    }
}

function getValueFromPDataMessage(pdatamessage) {
    switch (pdatamessage.ValueType) {
        case 0:
        case 1:
        case 8:
        case 9:
            return pdatamessage.WordValue
        case 2:
        case 3:
        case 7:
            return pdatamessage.FloatValue
        case 4:
            return pdatamessage.DateTimeValue
        case 5:
            return pdatamessage.StringValue
        case 6:
            return pdatamessage.BoolValue
        case 10:
        case 11:
            return pdatamessage.LongValue
        default:
            return ''
    }
}

function getValueCalcFromPDataMessage(pdatamessage) {
    switch (pdatamessage.ValueType) {
        case 0:
        case 1:
        case 8:
        case 9:
            return pdatamessage.WordValueCalc
        case 2:
        case 7:
        case 3:
            return pdatamessage.FloatValueCalc
        case 4:
            return pdatamessage.DateTimeValueCalc
        case 5:
            return pdatamessage.StringValueCalc
        case 6:
            return pdatamessage.BoolValueCalc
        case 10:
        case 11:
            return pdatamessage.LongValueCalc
        default:
            return ''
    }
}

//---------------------------------------------------  
// 判断闰年  
//---------------------------------------------------  
Date.prototype.isLeapYear = function () {
    return (0 == this.getYear() % 4 && ((this.getYear() % 100 != 0) || (this.getYear() % 400 == 0)));
}

//---------------------------------------------------  
// 日期格式化  
// 格式 YYYY/yyyy/YY/yy 表示年份  
// MM/M 月份  
// W/w 星期  
// dd/DD/d/D 日期  
// hh/HH/h/H 时间  
// mm/m 分钟  
// ss/SS/s/S 秒  
//---------------------------------------------------  
Date.prototype.Format = function (formatStr) {
    var str = formatStr;
    var Week = ['日', '一', '二', '三', '四', '五', '六'];

    str = str.replace(/yyyy|YYYY/, this.getFullYear());
    str = str.replace(/yy|YY/, (this.getYear() % 100) > 9 ? (this.getYear() % 100).toString() : '0' + (this.getYear() % 100));

    str = str.replace(/MM/, this.getMonth() > 9 ? this.getMonth().toString() : '0' + this.getMonth());
    str = str.replace(/M/g, this.getMonth());

    str = str.replace(/w|W/g, Week[this.getDay()]);

    str = str.replace(/dd|DD/, this.getDate() > 9 ? this.getDate().toString() : '0' + this.getDate());
    str = str.replace(/d|D/g, this.getDate());

    str = str.replace(/hh|HH/, this.getHours() > 9 ? this.getHours().toString() : '0' + this.getHours());
    str = str.replace(/h|H/g, this.getHours());
    str = str.replace(/mm/, this.getMinutes() > 9 ? this.getMinutes().toString() : '0' + this.getMinutes());
    str = str.replace(/m/g, this.getMinutes());

    str = str.replace(/ss|SS/, this.getSeconds() > 9 ? this.getSeconds().toString() : '0' + this.getSeconds());
    str = str.replace(/s|S/g, this.getSeconds());

    return str;
}

//+---------------------------------------------------  
//| 求两个时间的天数差 日期格式为 YYYY-MM-dd   
//+---------------------------------------------------  
function daysBetween(DateOne, DateTwo) {
    var OneMonth = DateOne.substring(5, DateOne.lastIndexOf('-'));
    var OneDay = DateOne.substring(DateOne.length, DateOne.lastIndexOf('-') + 1);
    var OneYear = DateOne.substring(0, DateOne.indexOf('-'));

    var TwoMonth = DateTwo.substring(5, DateTwo.lastIndexOf('-'));
    var TwoDay = DateTwo.substring(DateTwo.length, DateTwo.lastIndexOf('-') + 1);
    var TwoYear = DateTwo.substring(0, DateTwo.indexOf('-'));

    var cha = ((Date.parse(OneMonth + '/' + OneDay + '/' + OneYear) - Date.parse(TwoMonth + '/' + TwoDay + '/' + TwoYear)) / 86400000);
    return Math.abs(cha);
}


//+---------------------------------------------------  
//| 日期计算  
//+---------------------------------------------------  
Date.prototype.DateAdd = function (strInterval, Number) {
    var dtTmp = this;
    switch (strInterval) {
        case 's':
            return new Date(Date.parse(dtTmp) + (1000 * Number));
        case 'n':
            return new Date(Date.parse(dtTmp) + (60000 * Number));
        case 'h':
            return new Date(Date.parse(dtTmp) + (3600000 * Number));
        case 'd':
            return new Date(Date.parse(dtTmp) + (86400000 * Number));
        case 'w':
            return new Date(Date.parse(dtTmp) + ((86400000 * 7) * Number));
        case 'q':
            return new Date(dtTmp.getFullYear(), (dtTmp.getMonth()) + Number * 3, dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());
        case 'm':
            return new Date(dtTmp.getFullYear(), (dtTmp.getMonth()) + Number, dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());
        case 'y':
            return new Date((dtTmp.getFullYear() + Number), dtTmp.getMonth(), dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());
    }
}

//+---------------------------------------------------  
//| 比较日期差 dtEnd 格式为日期型或者有效日期格式字符串  
//+---------------------------------------------------  
Date.prototype.DateDiff = function (strInterval, dtEnd) {
    var dtStart = this;
    if (typeof dtEnd == 'string') //如果是字符串转换为日期型  
    {
        dtEnd = StringToDate(dtEnd);
    }
    switch (strInterval) {
        case 's':
            return parseInt((dtEnd - dtStart) / 1000);
        case 'n':
            return parseInt((dtEnd - dtStart) / 60000);
        case 'h':
            return parseInt((dtEnd - dtStart) / 3600000);
        case 'd':
            return parseInt((dtEnd - dtStart) / 86400000);
        case 'w':
            return parseInt((dtEnd - dtStart) / (86400000 * 7));
        case 'm':
            return (dtEnd.getMonth() + 1) + ((dtEnd.getFullYear() - dtStart.getFullYear()) * 12) - (dtStart.getMonth() + 1);
        case 'y':
            return dtEnd.getFullYear() - dtStart.getFullYear();
    }
}

//+---------------------------------------------------  
//| 日期输出字符串，重载了系统的toString方法  
//+---------------------------------------------------  
Date.prototype.toString = function (showWeek) {
    var myDate = this;
    var str = myDate.toLocaleDateString();
    if (showWeek) {
        var Week = ['日', '一', '二', '三', '四', '五', '六'];
        str += ' 星期' + Week[myDate.getDay()];
    }
    return str;
}

//+---------------------------------------------------  
//| 日期合法性验证  
//| 格式为：YYYY-MM-DD或YYYY/MM/DD  
//+---------------------------------------------------  
function IsValidDate(DateStr) {
    var sDate = DateStr.replace(/(^\s+|\s+$)/g, ''); //去两边空格;   
    if (sDate == '') return true;
    //如果格式满足YYYY-(/)MM-(/)DD或YYYY-(/)M-(/)DD或YYYY-(/)M-(/)D或YYYY-(/)MM-(/)D就替换为''   
    //数据库中，合法日期可以是:YYYY-MM/DD(2003-3/21),数据库会自动转换为YYYY-MM-DD格式   
    var s = sDate.replace(/[\d]{ 4,4 }[\-/]{ 1 }[\d]{ 1,2 }[\-/]{ 1 }[\d]{ 1,2 }/g, '');
    if (s == '') //说明格式满足YYYY-MM-DD或YYYY-M-DD或YYYY-M-D或YYYY-MM-D   
    {
        var t = new Date(sDate.replace(/\-/g, '/'));
        var ar = sDate.split(/[-/:]/);
        if (ar[0] != t.getYear() || ar[1] != t.getMonth() + 1 || ar[2] != t.getDate()) {
            //alert('错误的日期格式！格式为：YYYY-MM-DD或YYYY/MM/DD。注意闰年。');   
            return false;
        }
    } else {
        //alert('错误的日期格式！格式为：YYYY-MM-DD或YYYY/MM/DD。注意闰年。');   
        return false;
    }
    return true;
}

//+---------------------------------------------------  
//| 日期时间检查  
//| 格式为：YYYY-MM-DD HH:MM:SS  
//+---------------------------------------------------  
function CheckDateTime(str) {
    var reg = /^(\d+)-(\d{ 1,2 })-(\d{ 1,2 }) (\d{ 1,2 }):(\d{ 1,2 }):(\d{ 1,2 })$/;
    var r = str.match(reg);
    if (r == null) return false;
    r[2] = r[2] - 1;
    var d = new Date(r[1], r[2], r[3], r[4], r[5], r[6]);
    if (d.getFullYear() != r[1]) return false;
    if (d.getMonth() != r[2]) return false;
    if (d.getDate() != r[3]) return false;
    if (d.getHours() != r[4]) return false;
    if (d.getMinutes() != r[5]) return false;
    if (d.getSeconds() != r[6]) return false;
    return true;
}

//+---------------------------------------------------  
//| 把日期分割成数组  
//+---------------------------------------------------  
Date.prototype.toArray = function () {
    var myDate = this;
    var myArray = Array();
    myArray[0] = myDate.getFullYear();
    myArray[1] = myDate.getMonth();
    myArray[2] = myDate.getDate();
    myArray[3] = myDate.getHours();
    myArray[4] = myDate.getMinutes();
    myArray[5] = myDate.getSeconds();
    return myArray;
}

//+---------------------------------------------------  
//| 取得日期数据信息  
//| 参数 interval 表示数据类型  
//| y 年 m月 d日 w星期 ww周 h时 n分 s秒  
//+---------------------------------------------------  
Date.prototype.DatePart = function (interval) {
    var myDate = this;
    var partStr = '';
    var Week = ['日', '一', '二', '三', '四', '五', '六'];
    switch (interval) {
        case 'y':
            partStr = myDate.getFullYear();
            break;
        case 'm':
            partStr = myDate.getMonth() + 1;
            break;
        case 'd':
            partStr = myDate.getDate();
            break;
        case 'w':
            partStr = Week[myDate.getDay()];
            break;
        case 'ww':
            partStr = myDate.WeekNumOfYear();
            break;
        case 'h':
            partStr = myDate.getHours();
            break;
        case 'n':
            partStr = myDate.getMinutes();
            break;
        case 's':
            partStr = myDate.getSeconds();
            break;
    }
    return partStr;
}

//+---------------------------------------------------  
//| 取得当前日期所在月的最大天数  
//+---------------------------------------------------  
Date.prototype.MaxDayOfDate = function () {
    var myDate = this;
    var ary = myDate.toArray();
    var date1 = (new Date(ary[0], ary[1] + 1, 1));
    var date2 = date1.dateAdd(1, 'm', 1);
    var result = dateDiff(date1.Format('yyyy-MM-dd'), date2.Format('yyyy-MM-dd'));
    return result;
}

//+---------------------------------------------------  
//| 字符串转成日期类型   
//| 格式 MM/dd/YYYY MM-dd-YYYY YYYY/MM/dd YYYY-MM-dd  
//+---------------------------------------------------  
function StringToDate(DateStr) {

    var converted = Date.parse(DateStr);
    var myDate = new Date(converted);
    if (isNaN(myDate)) {
        //var delimCahar = DateStr.indexOf('/')!=-1?'/':'-';  
        var arys = DateStr.split('-');
        myDate = new Date(arys[0], --arys[1], arys[2]);
    }
    return myDate;
}

function currentTime() {
    var now = new Date();

    var year = now.getFullYear(); //年
    var month = now.getMonth() + 1; //月
    var day = now.getDate(); //日

    var hh = now.getHours(); //时
    var mm = now.getMinutes(); //分
    var ss = now.getSeconds();

    var clock = year + "-";

    if (month < 10)
        clock += "0";

    clock += month + "-";

    if (day < 10)
        clock += "0";

    clock += day + " ";

    if (hh < 10)
        clock += "0";

    clock += hh + ":";
    if (mm < 10) clock += '0';
    clock += mm + ":";

    if (ss < 10) clock += '0';
    clock += ss;
    return (clock);
}

// 测试函数 | 能被设计页面和预览页面调用到
function testSrcs()  {
    alert('Hello World')
}