(function(KDApi, $){
    function HelloWorld (model) {
        this._setModel(model)
    }

    HelloWorld.prototype = {
        _setModel: function(model) {
            this.model = model
        },
        init: function(props){
            // TO DO
            console.log(`init  ${props.isEditor? 'edit': 'render'}  cell!`)
            initFunc.call(this, this.model, props)
        },
        update: function(props){
            // TO DO
            console.log(`update ${props.isEditor? 'edit': 'render'} cell!`)
            updateFunc.call(this, this.model, props)
        },
        destoryed: function(){ 
            // TO DO
            console.log(`destory cell!`)
            this.onFocusLoseHandle && document.removeEventListener('mouseover',this.onFocusLoseHandle ,true)
            this.destroyedRemoveEvent && this.destroyedRemoveEvent()
        },
        handleDirective:function(customProps, methodName ,result){ // 收集表格编辑态自定义控件的指令，编辑态使用。
            console.log('handleDirective', customProps, methodName, result)
        },
        compareValue: function(value,oldValue){// 该方法用来判断编辑态是否更新表格值，值一样会忽略更新。编辑态使用。
            return value === oldValue
        }
    }


    // util

    /**
     * 获取自定义控件唯一标识，通常用作id或者class的前缀
     * @param {*} model
     */
    var getCustomControlUniquePrefix = function(model) {
        const { schemaId, isvId } = model
        return `${isvId}-${schemaId}-`
    }

    /**
     * 获取单元格唯一标识，通常用作id或者class的后缀
     * @param {*} model
     */
    var getUniqueSuffix = function(props){
		if(props!=null&&props.data!=null){
		    const { column, gridRowData } = props
			const { colId } = column
			const { rowKey } = gridRowData
			return '-' + rowKey + '-' + colId
		}
		return '-'
    }


    /**
     * 初始化单元格
     * @param {*} model
     * @param {*} props
     */
    var initFunc = function(model, props) {
        let that = this
        // KDApi.loadFile可以通过路径加载js或css文件，并且在html文件头生成script或者link标签，第一个参数是路径，第二个参数是model，第三个参数是加载完成后执行的回调函数
        // 'https://localhost:8443/ierp/dev/helloworld/css/index.css'
        KDApi.loadFile('./css/index.css', model, function() {
            if(props.isEditor){
                initEidtCell(model, props, that)
            }else{
                initRnederCell(model, props, that)
            }
        })
    }

    /**
     * 编辑态单元格初始化
     * @param {*} model
     * @param {*} props
     * @param {*} context 上下文可根据自身需要传或者调用时绑定
     */
    var initRnederCell = (model, props, context) => {
        /**
         * 单元格编辑态有弹出框的时候，判断点击是否在单元格外，从而取消编辑并更新值。
         * @param {*} model
         * @param {*} props
         */
        var getFocusLoseHandle = function(model, props){
            return (e) => {
                if(!model.dom.parentNode){
                    //dom not ready
                    return
                }
                let isClickOutSide = true
                const activeDom = document.activeElement
                if(model.dom.parentNode.contains(e.target)){
                    isClickOutSide = false
                }

                if(isClickOutSide){
                    const idUniqueSuffix = getUniqueSuffix(props)
                    const input = model.dom.querySelector('#dataInput' + idUniqueSuffix)
                    //props.gridApi.fireCellValueChange(input.value) // 仅更新值
                    //props.gridApi.stopEditing() //停止编辑并fireCellValueChange更新的值发送到后端
                    //document.activeElement = activeDom
                }
				if('涓ユ牸绠℃帶'==(e.target.title) || '涓害璀︾ず'==(e.target.title) || '杞诲害鎻愰啋'==(e.target.title)) {
					//model.invoke('show_verify_html', 'HelloWorld');  
					//model.dom.innerHTML = '<h1>init: Hello World!</h1>'
					var rowIndex = $('.ag-row-hover').attr('row-index');
					model.invoke('show_verify_html', rowIndex);  
				} else {
					//model.invoke('hide_verify_html', 'GameOver');  
					//model.dom.innerHTML = ''
					var a=document.getElementsByClassName("_1QFlAc6R");
					$("._1QFlAc6R").remove();
				}
            }
        }
        context.onFocusLoseHandle = getFocusLoseHandle(model, props, context)
        // 点击单元格外部取消编辑 并更新值
        document.addEventListener('mouseover', context.onFocusLoseHandle ,true)
		
		//$(document).on('mouseover', '.grid-hyper-link', function() {
			//var rowIndex = $('.ag-row-hover').index();
			//model.invoke('show_verify_html', rowIndex);  								
		//});
		//$(document).on('mouseleave', '.grid-hyper-link', function() {
			//model.invoke('hide_verify_html', 'HelloWorld');
			//var a=document.getElementsByClassName("_1QFlAc6R");
			//$("._1QFlAc6R").remove();
		//});
       
    }

    /**
     * 渲染态单元格初始化
     * @param {*} model
     * @param {*} props
     * @param {*} context 上下文可根据自身需要传或者调用时绑定
     */
    var initEidtCell = (model, props, context) => {
        //todo
    }


    /**
     * 绘制单元格
     * @param {*} model
     * @param {*} props
     */
    var updateFunc = function(model, props) {
        var updateText = props.data && props.data.gridRowData && props.data.gridRowData.validateMessage_html || ''
		//model.dom.innerHTML = updateText
    }


    var drawRnederCell = function (model, props, context){
        const { themeNum, data, lock } = props
        model.dom.innerHTML = `<div class="${getCustomControlUniquePrefix(model)}my-custom-cell ${getCustomControlUniquePrefix(model)}my-custom-render-cell">
            <span class="text" style="color:${lock ? '#eeeeee' :themeNum}">${data}</span>
        </div>`

        // 绑定渲染态事件
        bindRenderEvent(model, props, context)
    }

    var drawEidtCell = function (model, props, context){
        const { data } = props
        const idUniqueSuffix = getUniqueSuffix(props)
        const editorDomPosition = model.dom.getBoundingClientRect()

        model.dom.innerHTML = `<div class="${getCustomControlUniquePrefix(model)}my-custom-cell ${getCustomControlUniquePrefix(model)}my-custom-edit-cell">
            <input id="dataInput${idUniqueSuffix}" value="${data}" style="flex-grow: 1;">              
        </div>`


        // 绑定编辑态事件
        bindEditEvent(model, props, context)
    }


    var bindRenderEvent = function(model, props, context){
        removeRenderEvent(model, props, context) //可以在监听时取消上次的监听事件
        //todo...
    }

    var removeRenderEvent = function(model, props, context){
        //todo...
    }

    var bindEditEvent = function(model, props, context){

        const idUniqueSuffix = getUniqueSuffix(props)
        const selector = `.${getCustomControlUniquePrefix(model)}my-custom-cell #dataInput${idUniqueSuffix}`
        // 进入编辑态即设置焦点
        $(selector, model.dom).focus()
        context.destroyedRemoveEvent = () => {
            removeEditEvent(model, props, context)
        }
    }


    var removeEditEvent = function(model, props){
        const idUniqueSuffix = getUniqueSuffix(props)
        const selector = `.${getCustomControlUniquePrefix(model)}my-custom-cell #dataInput${idUniqueSuffix}`
        $(selector, model.dom).off('input')
    }

    KDApi.register('verifyinfo', HelloWorld)
})(window.KDApi, jQuery)