import { Text, View } from '@tarojs/components'
import classnames from 'classnames'
import { memo, useCallback, useEffect, useMemo, useState } from 'react'
import styles from './index.module.scss'
import Popup from '@/components/popup'
import AddressList from '@/components/AddressList'

export interface AddressInfoParam {
  province_name: string
  city_name: string
  district_name: string
  address_detail: string
  id?: number
  name: string
  phone: string
}
interface Param {
  onSelect?: (val: any) => void // 选择
  defaultValue?: AddressInfoParam|null // 默认值
  disabled?: false|true // true禁用后只用于展示
}
const AddressInfo = ({ onSelect, defaultValue = null, disabled = false }: Param) => {
  const [showAddressList, setShowAddressList] = useState(false)

  // 选择地址
  const [userInfo, setUserInfo] = useState<any>()
  const getAddress = useCallback((val) => {
    setShowAddressList(() => false)
    setUserInfo(() => val)
    onSelect?.(val)
  }, [])

  // 地址格式
  const formatAddress = useMemo(() => {
    if (userInfo) { return userInfo.province_name + userInfo.city_name + userInfo.district_name + userInfo.address_detail }
  }, [userInfo])

  const changeShow = () => {
    if (!disabled) { setShowAddressList(() => true) }
  }
  useEffect(() => {
    setUserInfo(() => defaultValue)
  }, [defaultValue])
  return (
    <View>
      <View className={styles.order_address} onClick={() => changeShow()}>
        <View className={classnames(styles.order_address_icon, 'iconfont icon-daohang')}></View>
        {!userInfo
          ? <>
            <View className={styles.order_address_text_no}>请选择收货地址及信息</View>
            <View className={classnames(styles.order_address_more_icon, 'iconfont icon-a-moreback')}></View>
          </>
          : <>
            <View className={styles.order_address_text_con}>
              <View className={styles.order_address_text_name}>
                <Text>{userInfo?.name}</Text>
                <Text>{userInfo?.phone}</Text>
              </View>
              <View className={styles.order_address_text_title}>{formatAddress}</View>
            </View>
            <View className={styles.updateBtn}>修改</View>
          </>}
      </View>
      {!disabled && <Popup show={showAddressList} showTitle={false} onClose={() => setShowAddressList(false)}>
        <View className={styles.order_address_list}>
          <View className={styles.order_address_title}>请选择收货地址</View>
          <AddressList onSelect={item => getAddress(item)} />
        </View>
      </Popup>}
    </View>
  )
}
export default memo(AddressInfo)
