
import React, { useEffect, useMemo, useRef, useState } from 'react'
import Taro from '@tarojs/taro';
import { ScrollView, View, Image, Text } from '@tarojs/components';
import deleteIcon from '@/assets/icons/landlord/delete.png';
import './style.less'

export default (props) => {
  const { className, action, del, onDelete } = props;

  const contextRef = useRef()
  const contentHeightRef = useRef(0)
  const [actStyle, setActStyle]= useState()

  const uqClass = useMemo(() => `f-${Math.random().toString(36).substring(2)}`, [])
  const classes = [className, 'slideview-wrapper', uqClass].filter(Boolean).join(' ');

  const handleScrollLeft = () => {
    if (contextRef.current) {
      contextRef.current.scrollIntoView('.slideview-content')
    }
  }

  const handleScrollRight = () => {
    if (contextRef.current) {
      contextRef.current.scrollIntoView('.slideview-actions')
    }
  }

  const handleDelete = (e) => {
    if (onDelete) {
      onDelete(e)
    }
  }

  useEffect(() => {
    Taro.nextTick(() => {
      Taro.createSelectorQuery()
      .select(`.${uqClass}`)
      .node()
      .exec((res) => {
        contextRef.current = res[0].node;
      })
    })
  }, [])

  useEffect(() => {
    Taro.nextTick(() => {
      // 不清楚为什么, 此处获取高度一直不准确
      const t = setTimeout(() => {
        Taro.createSelectorQuery()
        .select(`.${uqClass}`)
        .boundingClientRect()
        .exec((res) => {
          if (res && res[0]) {
            const { height } = res[0]
            if (height && height !== contentHeightRef.current) {
              setActStyle({
                height: `${height}px`,
              })
              contentHeightRef.current = height
            }
          }
        })
        clearTimeout(t)
      }, 500)
    })
  })

  return (
    <ScrollView
      className={classes}
      upperThreshold={20}
      lowerThreshold={20}
      scrollX
      scrollWithAnimation
      enhanced
      onScrollToUpper={handleScrollLeft}
      onScrollToLower={handleScrollRight}
    >
      <View className='slideview-content'>{props.children}</View>
      <View className='slideview-actions' style={actStyle}>
        <View className='slideview-action'>
          {
            del && (
              <View className='slideview-action_delete' onClick={handleDelete}>
                <Image src={deleteIcon} />
                <View>删除</View>
              </View>
            )
          }
          {action}
        </View>
      </View>
    </ScrollView>
  )
}
