import { Image, RootPortal, ScrollView, Text, View } from '@tarojs/components'
import React, { FC, forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react'
import classnames from 'classnames'
import Search from '../search'
import Popup from '../popup'
import IconFont from '../iconfont/iconfont'
import SearchInput from '../searchInput'
import styles from './index.module.scss'
import { formatHashTag } from '@/common/format'
import { SelectProductListApi } from '@/api/index'

interface PropsType {
  selectColorId: number
  noAll?: boolean
  onSelect?: Function
  children?: React.ReactNode
}

interface productType {
  code?: string
  default?: boolean
  id: number
  name: string
}

const SelectProduct = (params: PropsType, ref) => {
  const { selectColorId, noAll, onSelect } = params

  const [selectId, setSelectId] = useState(selectColorId)

  const { fetchData } = SelectProductListApi()

  const [selectValue, setSelectValue] = useState()

  const [productList, setProductList] = useState<productType[]>([])

  const [showPopup, setShowPopup] = useState(false)

  const changeName = (item) => {
    console.log('changeName', item)
    if (item) {
      if (item.id) {
        return formatHashTag(item.code, item.name)
      }
      else {
        return item.name
      }
    }
  }
  const clickEvent = () => {
    setShowPopup(true)
  }
  useImperativeHandle(
    ref,
    () => ({
      clickEvent,
    }),
    [clickEvent],
  )
  const originList = useRef<productType[]>([])

  const getSelectData = (item) => {
    setSelectId(item.id)
    setSelectValue(changeName(item))
    setShowPopup(false)
    onSelect && onSelect(item)
  }

  const getProductList = async() => {
    const res = await fetchData()
    // !noAll && res.data.list?.unshift({ name: '全部', id: 0 })
    !noAll && setProductList([{ name: '全部', id: 0 }, ...res.data.list])
    originList.current = [{ name: '全部', id: 0 }, ...res.data.list]
  }

  useEffect(() => {
    getProductList()
  }, [])

  const closeEven = () => {
    setShowPopup(false)
  }

  // 输入了搜索关键字
  const getSearchData = useCallback(
    async(value) => {
      console.log('e==>', value)
      if (value === '') {
        setProductList([...originList.current])
      }
      else {
        const res = await fetchData({
          code_or_name: value,
        })
        if (res.success) {
          setProductList(res.data.list)
        }
      }
    },
    [originList],
  )

  useEffect(() => {
    setSelectId(selectColorId)
    const res = productList.find(item => item.id == selectColorId)
    setSelectValue(changeName(res))
  }, [selectColorId])

  return (
    <>
      <View className={styles.select_input}>
        <SearchInput title="面料名称" showIcon showBorder={false}>
          <View onClick={clickEvent} className={classnames(styles.input_type, selectValue ? '' : 'noCon')}>
            {selectValue || '请选择'}
          </View>
        </SearchInput>
      </View>
      <Popup title="请选择面料名称" showTitle show={showPopup} onClose={closeEven} position="bottom" customStyle={{ zIndex: 9999 }}>
        <View style={{ padding: '0 24rpx' }}>
          <Search placeholder="请输入编号/面料" showBtn={false} changeOnSearch={getSearchData}></Search>
        </View>
        <View className={styles.selectList}>
          <ScrollView className={styles['selectList-scroll-view']} scrollY>
            {productList.map((item) => {
              return (
                <View key={item.id} className={classnames(styles.selectItem, selectId == item.id ? styles.selected : '')} onClick={() => getSelectData(item)}>
                  {changeName(item)}
                </View>
              )
            })}
          </ScrollView>
        </View>
      </Popup>
    </>
  )
}
export default forwardRef(SelectProduct)
