// module/health/components/horizontal-scrollable/horizontal-scrollable.ts
const { shared, spring, runOnJS } = wx.worklet;
Component({
  lifetimes: {
    ready() {
    },
    attached() {
      const x = shared(0);
      const offset = shared(1);
      (<any>this).applyAnimatedStyle('.scrollable', () => {
        'worklet';
        return { transform: `translate(${x.value}px)`, };
      });
      (<any>this).x = x;
      (<any>this).offset = offset;
    }
  },
  properties: {
    dataset: { type: Array, value: [] },
  },
  data: {

  },
  methods: {
    handleHorizontalDrag(event: { deltaX: number }) {
      'worklet';
      if ((<any>this).offset.value === 1) runOnJS(this.start.bind(this))();
      else {
        const value = Math.max((<any>this).x.value + event.deltaX, (<any>this).offset.value);
        (<any>this).x.value = Math.min(value, 0)
      }
    },

    start() {
      console.log('触发');

      const query = this.createSelectorQuery()
      query.select('.scrollable').boundingClientRect();
      query.selectAll('.scheme__card').boundingClientRect();
      query.exec(([box, sub]) => {
        const subWidth = sub[sub.length - 1].right - sub[0].left;
        const boxWidth = box.width;
        (<any>this).offset.value = subWidth > boxWidth ? box.width - subWidth : 0;
      })
    },
    preview(event: WechatMiniprogram.TouchEvent) {
      const url = event.target.dataset?.url ?? '';
      const sources = this.data.dataset.filter(item => ['image', 'video'].includes(item.type));
      const current = Math.max(sources.findIndex(item=>item.url === url), 0);
      wx.previewMedia({sources, current})
    }
  }
})