// 定义装饰器
function Component(metaData: {
  selector: string;
  template: string;
  style: { [key: string]: string };
}) {
  return function (Constructor: Function) {
    // 修改类的原型，添加 render 方法
    Constructor.prototype.render = function () {
      let compList = document.querySelectorAll(this.selector);
      compList.forEach((element) => {
        // 应用样式
        Object.keys(this.style).forEach((key) => {
          element.style[key] = this.style[key];
        });
        // 插入模板内容
        element.innerHTML = this.template;
      });
    };

    // 初始化类的属性
    Constructor.prototype.selector = metaData.selector;
    Constructor.prototype.style = metaData.style;
    Constructor.prototype.template = metaData.template;
  };
}

// 定义一个接口来描述 Component 的结构
interface IComponent {
  selector: string;
  template: string;
  style: { [key: string]: string };
  render(): void;
}

// 创建具体的组件类
@Component({
  selector: "card",
  style: {
    margin: "10px",
    border: "solid 1px",
    minWidth: "100px",
    minHeight: "80px",
  },
  template: "我是卡片",
})
class CardComponent implements IComponent {
  selector: string;
  template: string;
  style: { [key: string]: string };

  // 现在 render 方法是由装饰器注入的
  render(): void {
    // 这个方法会被装饰器覆盖
  }
}

@Component({
  selector: "circle",
  style: {
    margin: "10px",
    border: "solid 1px",
    borderRadius: "50%",
    width: "100px",
    height: "80px",
  },
  template: "我是圆形",
})
class CircleComponent implements IComponent {
  selector: string;
  template: string;
  style: { [key: string]: string };

  // 现在 render 方法是由装饰器注入的
  render(): void {
    // 这个方法会被装饰器覆盖
  }
}

// 渲染组件
const cardInstance = new CardComponent();
cardInstance.render();

const circleInstance = new CircleComponent();
circleInstance.render();
