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

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

export default memo(({onSelect, defaultValue = null, disabled = false}: Param) => {
    const [showAddressList, setShowAddressList] = useState(false)

    useEffect(() => {
        setUserInfo(() => defaultValue)
    }, [defaultValue])

    //选择地址
    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)
    }
    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>
    )
})