import { Text, View } from '@tarojs/components'
import { useEffect, useState } from 'react'
import styles from './index.module.scss'
import IconFont from '@/components/iconfont/iconfont'
import SelectAddress from '@/components/selectAddress'

export interface AddressItem {
  id: number
  address_title?: string
  address_name?: string
  address_phone?: string
}
interface Param {
  onSelect: (val: AddressItem) => void
  defaultValue?: AddressItem
}

export default (props: Param) => {
  const { defaultValue } = props
  const [data, setData] = useState({
    id: 0,
    address_title: '',
    address_name: '',
    address_phone: '',
    address_mode: '物流',
  })

  useEffect(() => {
    setData(e => ({
      ...e,
      id: e.id,
      address_title: defaultValue?.address_title || '',
      address_name: defaultValue?.address_name || '',
      address_phone: defaultValue?.address_phone || '',
    }))
  }, [defaultValue])

  const [showList, setShowList] = useState(false)
  const getAddress = (e) => {
    props.onSelect({
      id: e.id,
      address_title: e.province_name + e.district_name + e.city_name + e.address_detail,
      address_name: e.name,
      address_phone: e.phone,
    })
    setData(val => ({
      ...val,
      address_title: e.province_name + e.district_name + e.city_name + e.address_detail,
      address_name: e.name,
      address_phone: e.phone,
    }))
  }
  return <>
    <View className={styles.address_con} onClick={() => setShowList(true)}>
      <IconFont name="icon-dingwei" size={50} />
      <View className={styles.message}>
        <View className={styles.info_address}>
          <View className={styles.address_name}>{data.address_title || '请选择收货地址'}</View>
          <IconFont name="icon-rukou" color="#979797FF" />
        </View>
        <View className={styles.info_phone}>
          <Text>{`${data.address_name}  ${data.address_phone}`}</Text>
          <Text>{data.address_mode}</Text>
        </View>
      </View>
    </View>
    <SelectAddress show={showList} onClose={() => setShowList(false)} onSelect={getAddress} />
  </>
}
