/**
 * 需求分析
 * A是列表页，B是详情页，C是另一个列表页
 * A=>B=>A A的状态不变
 * A=>C=>A A为初始状态
 * A=>B=>C=>A A为初始状态
 * A=>B=>A=>C=>A A为初始状态
 * A=>B=>A=>C=>A=>B=>A A的状态不变（保持A最新的状态）
 * A=>B=>A=>C=>A=>B=>C=>A A为初始状态
 */

/**
 * 查找指定的组件实例
 * @param {array} components 组件树
 * @param {string} componentName 指定的组件name
 * @returns 找到的组件实例
 */
function getComponent(components, componentName) {
  let result = {};
  components.some(el => {
    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) {
  let { componentOptions, parent = {}, key } = vm.$vnode || {};
  let { cache, keys } = parent.componentInstance || {};
  cache = cache || {};
  keys = Array.isArray(keys) ? keys : [];

  if (!componentOptions) return;

  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));
};
