import { View, Text } from '@tarojs/components';
import './index.less';
import { Component } from 'react';
interface Props {
    actions: {
        onClick: (id: any) => void,//按钮事件
        backgroundColor: string,//按钮自义定背景色
        text: string,//按钮自定义文本
        id: string | number,//要操作的数据ID
    }[],//按钮目前最多两个配置 需配置更多按钮需要修改maxOffsetX的值swipe-action-button-1对应的宽度样式
    children: any
}
/**
 * 滑动操作参考书架
 * */
class SwipeAction extends Component<Props> {
    state = {
        offsetX: 0, // 用于控制滑动的偏移
    };

    startX = 0; // 触摸开始的 X 坐标
    maxOffsetX = this.props?.actions?.length != 1 ? -150 : -75; // 操作按钮显示的最大偏移量

    handleTouchStart = (e) => {
        e.stopPropagation()
        // 记录触摸起始位置
        this.startX = e.touches[0].clientX;
    };

    handleTouchMove = (e) => {
        e.stopPropagation()
        // 计算滑动的距离
        const moveX = e.touches[0].clientX - this.startX;
        let offsetX = moveX;

        // 限制滑动的范围
        if (offsetX > 0) {
            offsetX = 0;
        } else if (offsetX < this.maxOffsetX) {
            offsetX = this.maxOffsetX;
        }

        this.setState({ offsetX });
    };

    handleTouchEnd = (e) => {
        e.stopPropagation()
        // 判断滑动的距离，决定是否显示操作按钮
        if (this.state.offsetX < this.maxOffsetX / 2) {
            this.setState({ offsetX: this.maxOffsetX });
        } else {
            this.setState({ offsetX: 0 });
        }
    };
    handlelongPress = () => {
        this.setState({
            offsetX: this.maxOffsetX
        })
    }
    render() {
        const { offsetX } = this.state;
        const { actions, children } = this.props;
        return (
            <View className="swipe-action">
                <View
                    className="swipe-action-content"
                    style={{ transform: `translateX(${offsetX}px)` }}
                    onTouchStart={this.handleTouchStart}
                    onTouchMove={this.handleTouchMove}
                    onTouchEnd={this.handleTouchEnd}
                    onLongPress={this.handlelongPress}
                >
                    {children}
                </View>
                <View className="swipe-action-buttons" style={offsetX != 0 ? { width: `${-this.maxOffsetX}px` } : { opacity: 0 }}>
                    {actions.map((action, index) => (
                        <View
                            key={index}
                            className={`swipe-action-button ${actions.length === 1 ? "swipe-action-button-1" : "swipe-action-button-2"}`}
                            onClick={() => action.onClick && action.onClick(action.id)}
                            style={{ backgroundColor: action.backgroundColor || '#ccc' }}
                        >
                            <Text>{action.text}</Text>
                        </View>
                    ))}
                </View>
            </View>
        );
    }
}

export default SwipeAction;