import { ScrollView, View } from '@tarojs/components'
import Taro, { useDidShow, usePullDownRefresh, useRouter } from '@tarojs/taro'
import React, { ReactNode, forwardRef, memo, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react'
import classnames from 'classnames'
import Tabs from '../tabs'
import styles from './index.module.scss'
import { alert } from '@/common/common'
import { formatDateTime, formatPriceDiv, formatWeightDiv } from '@/common/format'
import DropDownItem from '@/components/dropDown-item'
import { GetAddressListApi } from '@/api/addressList'
import IconFont from '@/components/iconfont/iconfont'

interface Props {
  handCity?: (province: any, city: any) => void
  value?: any
  onCloseOverlay?: () => void
}

export default memo(forwardRef((props: Props, ref) => {
  const DropDownItemRef = useRef<any>()
  const close = () => {
    DropDownItemRef.current.closePopup()
  }
  useImperativeHandle(
    ref,
    () => {
      return {
        show: DropDownItemRef?.current?.show,
        showPopup: DropDownItemRef?.current.showPopup,
        closePopup: DropDownItemRef?.current?.closePopup,
      }
    },
    [DropDownItemRef?.current],
  )

  // 获取地址
  const { fetchData } = GetAddressListApi()
  useEffect(() => {
    getProvince()
  }, [])

  // 获取省
  const getProvince = async() => {
    const res = await fetchData({ parent_id: 1 })
    if (res.data) {
      setlist([...res.data.list])
    }
  }

  // 已选的集合市
  // const [choseCityArr, setchoseCityArr] = useState<any[]>([])
  const choseCityArr = useRef<any>({ list: [] })

  // 省数组
  const [list, setlist] = useState<any[]>([])
  // 区数组
  const [cityList, setcityList] = useState<any[]>([])

  // 区分在哪一栏
  const [currentValue, setCurrentValue] = useState<number>(1)

  // 顶部栏
  const [TarBarList, setTarBarList] = useState<any[]>([{ id: 1, name: '选择省', showBorder: true }, { id: 2, name: '选择市', showBorder: false }])
  const handChose = (item) => {
    TarBarList.map((it) => {
      if (it.id === item.id) {
        it.showBorder = true
      }
      else {
        it.showBorder = false
      }
      setTarBarList([...TarBarList])
      setCurrentValue(item.id)
    })
  }

  // 选择省
  const handProvince = (item) => {
    list.map((it) => {
      if (item.id == it.id) {
        it.check = true
      }
      return it
    })
    setlist([...list])
    getCity(item.id)
    setCurrentValue(2)
    TarBarList.map((it) => {
      if (it.id == currentValue) {
        it.name = item.name
        it.showBorder = false
      }
      else {
        it.showBorder = true
      }

      return it
    })
    setTarBarList([...TarBarList])
  }

  // 获取市
  const getCity = async(id) => {
    const res = await fetchData({ parent_id: id })
    if (res.data) {
      res.data.list.map((item) => {
        choseCityArr.current.list.forEach((it) => {
          if (item.id == it.id) {
            item.check = true
          }
        })
        return item
      })
      setcityList([...res.data.list])
    }
    const provinceArr = list.filter((next) => { return next.check })
    props.handCity?.(provinceArr, choseCityArr.current.list)
  }

  // 选择市
  const handCity = (item) => {
    cityList.map((it) => {
      if (item.id == it.id) {
        it.check = !it.check
      }
      return it
    })
    setcityList([...cityList])
    const cityArr = cityList.filter((next) => { return next.check })
    if (item.check) {
      choseCityArr.current.list.push(item)
    }
    else {
      deleteById(item.id, choseCityArr.current.list)
    }
    // 将市区的全部不选后，该省的颜色不高亮
    if (cityArr.length == 0) {
      list.map((item) => {
        if (cityList[0]?.parent_id == item.id) {
          item.check = false
        }
        return item
      })
      setlist([...list])
    }
    const provinceArr = list.filter((next) => { return next.check })
    props.handCity?.(provinceArr, choseCityArr.current.list)
  }

  /**
     * 根据id删除数组项
     * @param {Number} id 需要删除的id
     * @param {Array} list 目标数组
     *
     * @return {Array}
     */
  function deleteById(id, list) {
    for (let index = list.length - 1; index >= 0; index--) {
      if (list[index] && list[index].id === id) {
        list.splice(index, 1)
      }
    }
    return list
  }

  // 重置
  const handReset = () => {
    TarBarList.map((item, index) => {
      if (index == 0) {
        item.name = '选择省'
        item.showBorder = true
      }
      else {
        item.showBorder = false
      }
      return item
    })
    setTarBarList([...TarBarList])
    setCurrentValue(1)
    choseCityArr.current.list = []
    list.map((item) => {
      item.check = false
      return item
    })
    setlist([...list])
    cityList.map((item) => {
      item.check = false
      return item
    })
    setcityList([...cityList])
    props.handCity?.('', '')
  }
  return (
    <DropDownItem ref={DropDownItemRef} title="所有省市" value={-1} activeColor="#337fff" onCloseOverlay={props?.onCloseOverlay}>
      <View className={styles.mainBox}>
        <Tabs list={TarBarList} handChose={item => handChose?.(item)} handReset={() => handReset()}></Tabs>
        {
          currentValue == 1 && <ScrollView scrollY className={styles.scrollView}>
            {
              list.map((item) => {
                return (
                  <View className={styles.itemBox} onClick={() => handProvince(item)}>
                    <View className={classnames(item.check ? styles.activeitemProvince : styles.itemProvince)}>{item.name}</View>
                    <IconFont name="icon-chakanquanbukehu" size={50} color="#d8d8d8"></IconFont>
                  </View>
                )
              })
            }
          </ScrollView>
        }
        {
          currentValue == 2 && <ScrollView scrollY className={styles.scrollView}>
            {
              cityList.map((item) => {
                return (
                  <View className={styles.itemBox} onClick={() => handCity(item)}>
                    <View className={classnames(item.check ? styles.activeitemProvince : styles.itemProvince)}>{item.name}</View>
                    {/* <IconFont name={'icon-chakanquanbukehu'} size={50} color={'#d8d8d8'}></IconFont> */}
                  </View>
                )
              })
            }
          </ScrollView>
        }
      </View>
    </DropDownItem>
  )
}))
