Component({
  properties: {
    visible: {
      type: Boolean,
      value: false,
    },
    customerName: {
      type: String,
      value: '',
    },
  },

  data: {
    content: '',
    error: false,
    keyboardHeight: 0,
    canSave: false,
  },

  observers: {
    visible(val: boolean) {
      if (val) {
        // 打开弹窗时重置
        this.setData({
          content: '',
          error: false,
          keyboardHeight: 0,
          canSave: false,
        })
      } else {
        // 关闭时重置键盘高度
        this.setData({ keyboardHeight: 0 })
      }
    },
    // 内容变化时重新计算 canSave
    content(val: string) {
      this.setData({
        canSave: val.trim().length > 0,
      })
    },
  },

  methods: {
    /** 文本输入 */
    onContentInput(e: WechatMiniprogram.CustomEvent<{ value: string }>) {
      this.setData({ content: e.detail.value, error: false })
    },

    /** 键盘弹出 */
    onTextareaFocus(e: WechatMiniprogram.InputEvent) {
      let height = (e as any).detail?.height ?? 0
      // 修复：首次激活时键盘高度可能为0，需要设置最小值确保弹窗移动
      if (height === 0) {
        height = 260  // 微信小程序默认键盘高度约 260px
      }
      this.setData({ keyboardHeight: height })
    },

    /** 键盘收起 */
    onTextareaBlur() {
      this.setData({ keyboardHeight: 0 })
    },

    /** 确认放弃 */
    onConfirm() {
      if (!this.data.canSave) {
        this.setData({ error: true })
        return
      }

      this.triggerEvent('confirm', {
        reason: this.data.content.trim(),
      })
    },

    /** 取消 */
    onCancel() {
      this.triggerEvent('cancel')
    },

    /** 阻止冒泡 */
    noop() {},
  },
})
