import { ScrollView, Text, View } from '@tarojs/components'
import { Children, memo, useEffect, useMemo, useRef, useState } from 'react'
import classnames from 'classnames'
import styles from './index.module.scss'
import Popup from '@/components/popup'
import { ReturnExplainApi, ReturnReasonApi } from '@/api/salesAfterOrder'

// 原因选择
interface Param { id: number; name: string; typle?: number }
interface ReasonInfoParam {
  show?: boolean // 显示
  onClose?: () => void // 关闭
  title?: string // 标题
  list?: { id: number; name: string; typle?: number }[] // 数据列表
  onSelect?: (val: object) => void // 选择
  onHeaderSelect?: (val: object) => void // 点击头部标题
  defaultValue?: number // 默认选中
  dataLength?: number // 可显示的数据列数
}
const ReasonPopup = ({ show = false, onClose, title = '', list = [], onSelect, onHeaderSelect, defaultValue, dataLength = 1 }: ReasonInfoParam) => {
  const [initList, setInitList] = useState<typeof list>([])

  useEffect(() => {
    setInitList(list)
  }, [list])
  const [selectIndex, setSelectIndex] = useState(1)
  const [headerList, setHeaderList] = useState<{ id: number; name: string }[]>([])
  const onSelectData = (item) => {
    if (selectIndex <= dataLength) {
      headerList[selectIndex - 1] = { id: item.id, name: item.name }
      onSelect?.({ data: headerList, index: selectIndex })
      setSelectIndex(selectIndex == dataLength ? dataLength : selectIndex + 1)
      setHeaderList(e => [...e])
      if (selectIndex == dataLength) { onClose?.() }
    }
  }

  const onHeaderClick = ({ val, index }) => {
    const list = headerList.slice(0, index + 1)
    setSelectIndex(index + 1)
    setHeaderList(list)
    onHeaderSelect?.({ data: val, index: index + 1 })
  }

  return (
    <Popup showIconButton={false} show={show} title={title} onClose={onClose} >
      <View className={styles.reason_return_con}>
        <View className={styles.reason_title}>
          {headerList.map((item, index) => {
            return <Text key={item.id} onClick={() => onHeaderClick({ val: item, index })} className={classnames(styles.selectName, (headerList.length == index + 1) && styles.select_bottom)}>{item.name}</Text>
          })}
          {dataLength > headerList.length && <Text className={styles.tips}>请选择</Text>}
        </View>
        <ScrollView scrollY className={styles.reason_scroll}>
          <View className={styles.reason_list}>
            {initList.map(item => <View onClick={() => onSelectData(item)} key={item.id} className={classnames(styles.reason_item, item.id == defaultValue && styles.select_item)}>{item.name}</View>)}
          </View>
        </ScrollView>
      </View>
    </Popup>
  )
}
export default memo(ReasonPopup)
