// components/button/button.ts
Component({
  behaviors: ["wx://form-field-button"],
  observers: {
    loading(this: any, val: boolean) {
      // 当外部声明 loading 时，同步禁用状态
      if (this.data.disableOnClick) this.setData({ isDisabled: !!val });
    },
  },
  lifetimes: {
    attached(this: any) {
      const mode = this.data.block ? "block" : "line";
      const index = this.data.index;
      this.setData({
        src: `../../assets/bg/button-${mode}-${index}.bg.png`,
        className: this.data.block ? "block" : `line-${index}`,
        isDisabled: false,
      });
    },
  },
  properties: {
    block: { type: Boolean, value: false },
    index: { type: Number, value: 1 },
    loading: { type: Boolean, value: false },
    text: { type: String, value: "" },
    // 是否在点击后禁用按钮，避免重复提交
    disableOnClick: { type: Boolean, value: true },
  },
  data: {
    list: [
      {
        name: "保存",
        value: "save",
      },
      {
        name: "提交",
        value: "submit",
      },
      {
        name: "确定",
        value: "confirm",
      },
      {
        name: "取消",
        value: "cancel",
      },
    ],
    src: "",
    isDisabled: false,
  },
  methods: {
    onSubmit(this: any, event: any) {
      if (this.data.isDisabled) return;
      if (this.data.disableOnClick) this.valFailure();
      this.triggerEvent('submit', { target: event.target }, { bubbles: true, composed: true });
    },
    resetState(this: any) {
      this.setData({
        isDisabled: false,
      });
    },

    valFailure(this: any) {
      // 处理失败逻辑
      if (this) this.setData({ isDisabled: true }); // 重置按钮状态
    },
  },
});
