Component({
  properties: {
    /** 筛选标签文字 */
    label: {
      type: String,
      value: '',
    },
    /** 选项列表 */
    options: {
      type: Array,
      value: [] as Array<{ value: string; text: string }>,
    },
    /** 当前选中值 */
    value: {
      type: String,
      value: '',
    },
  },

  observers: {
    'value, options'(val: string, opts: Array<{ value: string; text: string }>) {
      const matched = (opts || []).find((o) => o.value === val)
      this.setData({ selectedText: matched ? matched.text : '' })
    },
  },

  data: {
    expanded: false,
    selectedText: '',
    panelTop: 0,
  },

  lifetimes: {
    attached() {
      const { value, options } = this.data
      const matched = (options as Array<{ value: string; text: string }>).find(
        (o) => o.value === value,
      )
      this.setData({ selectedText: matched ? matched.text : '' })
    },
  },

  methods: {
    toggleDropdown() {
      if (!this.data.options || (this.data.options as any[]).length === 0) return

      if (!this.data.expanded) {
        // 展开时计算按钮底部位置，作为面板 top
        this.createSelectorQuery()
          .select('.filter-dropdown')
          .boundingClientRect((rect) => {
            if (rect) {
              this.setData({
                panelTop: rect.bottom,
                expanded: true,
              })
            } else {
              this.setData({ expanded: true })
            }
          })
          .exec()
      } else {
        this.setData({ expanded: false })
      }
    },

    onSelect(e: WechatMiniprogram.TouchEvent) {
      const val = e.currentTarget.dataset.value as string
      const opts = this.data.options as Array<{ value: string; text: string }>
      const matched = opts.find((o) => o.value === val)
      this.setData({
        expanded: false,
        selectedText: matched ? matched.text : '',
      })
      this.triggerEvent('change', { value: val })
    },

    /** 点击遮罩层关闭 */
    onMaskTap() {
      this.setData({ expanded: false })
    },
  },
})
