import { options, clearArray } from "./util";
import { Refs } from "./Refs";
import { disposeVnode } from "./dispose";

const dirtyComponents = [];
function mountSorter(u1, u2) {
    //按文档顺序执行
    u1._dirty = false;
    return u1._mountOrder - u2._mountOrder;
}
export function flushUpdaters() {
    if (dirtyComponents.length) {
        var currentQueue = clearArray(dirtyComponents).sort(mountSorter);
        currentQueue.forEach(function(el) {
            delete el._dirty;
        });
        drainQueue(currentQueue);
    }
}

export function enqueueUpdater(updater) {
    if (!updater._dirty) {
        updater.addJob("hydrate");
        updater._dirty = true;
        dirtyComponents.push(updater);
    }
}

export function drainQueue(queue) {
    options.beforePatch();
    //先执行所有元素虚拟DOMrefs方法（从上到下）
    let updater;
    while ((updater = queue.shift())) {
        //queue可能中途加入新元素,  因此不能直接使用queue.forEach(fn)
        if (updater._disposed) {
            continue;
        }

        //console.log(updater.name, updater._jobs+"");
        updater.exec(queue);
      
        var catchError = Refs.catchError;
        if(catchError){
            
            if(catchError.errHook === "componentDidMount"){
                /**
                 * 当一个组件在componentDidMount出错时，其实整个列队也在执行componentDidMount,
                 * 这样让它们都执行完componentDidMount，然后让它们都执行componentWillUnmount,
                 * 这时这些钩子可能会出错，不用管它，最后将医生的componentDidCatch放进去救场
                 */
                for (var i in catchError.children) {
                    var child = catchError.children[i];
                    disposeVnode(child, queue, true);
                }
              
                catchError.addJob("catch");
                queue.push(catchError);
            }else{
                for (var i in catchError.children) {
                   
                    var child = catchError.children[i];
                
                    disposeVnode(child, queue, true);
                }
                var find = false;
                for(var i = 0, el; el = queue[i]; i++){
                    console.log(el.name, "=====");
                    if( el === catchError){
                        queue.splice(0, i, catchError);
                        catchError.addJob("catch");
                        find = true;
                        break;
                    }else{
                        el;
                    }
                }
                if(!find){
                    queue.splice(i, 0, catchError);
                    catchError.addJob("catch");
                }
               
                
                //  queue.push(catchError);
                // queue.length = 0;
            }
            delete Refs.catchError;
            //执行错误边界的didMount/Update钩子
            // catchError.resolve(queue);
        }
    }

    options.afterPatch();
}
