/**
 * 查找指定的组件实例
 * @param {array} components 组件树
 * @param {string} componentName 指定的组件name
 * @returns 找到的组件实例
 */
function getComponent(components, componentName) {
  let result = {};
  components.some(el => {
    // console.log(el.$options.name);
    if (el.$options.name == componentName) {
      result = el;
    } else if (Array.isArray(el.$children)) {
      result = getComponent(el.$children, componentName);
    }
    return result.$el;
  });
  return result;
}

/**
 * 清除指定组件的缓存
 * @param {object} vm 组件实例
 */
function delCache(vm) {
  if (!vm.$vnode) return;
  let { componentOptions, parent, key } = vm.$vnode || {};
  let { cache, keys } = parent.componentInstance || {};
  cache = cache || {};
  keys = Array.isArray(keys) ? keys : [];

  if (!key) {
    const { Ctor, tag } = componentOptions;
    key = Ctor.cid + (tag ? `::${tag}` : '');
  }
  if (cache[key]) {
    if (Array.isArray(keys)) {
      vm.$vnode.parent.componentInstance.keys = keys.filter(v => v != key);
    }
    delete vm.$vnode.parent.componentInstance.cache[key];
  }
}

export default (components, componentName) => {
  delCache(getComponent(components, componentName));
};