// 定义扩展的字段名称
const MIXIN = 'mixins';
const DATA = 'data';
const _toString = Object.prototype.toString;

const isObject = obj => _toString.call(obj) === '[object Object]';

const loopMixin = (mixins, newObj) => {
  if (Array.isArray(mixins)) {
    mixins.forEach(mixin => {
      for (const key in mixin) {
        if (key === MIXIN) {
          const subMixins = mixin[MIXIN];

          if (Array.isArray(subMixins)) {
            loopMixin(subMixins, newObj);
          }
        } else if (key === DATA) {
          newObj[DATA] = Object.assign({}, newObj[DATA], mixin[DATA]);
        } else {
          newObj[key] = mixin[key];
        }
      }
    });
  }
};

export default function PageMixin(option) {
  if (!isObject(option)) {
    throw new Error('配置项必须为函数');
  }

  const newObj = {};

  for (const key in option) {
    if (key === MIXIN) {
      const mixins = option[MIXIN];
      loopMixin(mixins, newObj);
    } else if (key === DATA) {
      newObj[DATA] = Object.assign({}, newObj[DATA], option[[DATA]]);
    } else {
      newObj[key] = option[key];
    }
  }

  return newObj;
}