import { EditSaleOrderAddressApi, EditSaleOrderShipmentModeApi } from "@/api/order";
import { alert } from "@/common/common";
import { debounce } from "@/common/util";
import AddressList from "@/components/AddressList";
import Popup from "@/components/popup";
import { Text, View } from "@tarojs/components"
import classnames from "classnames";
import { forwardRef, memo, useCallback, useEffect, useImperativeHandle, 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禁用后只用于展示
    shipment_mode?: 1|2, //1自提 2物流
    onChangeShipmentMode?: (val: number) => void, //返回收货方式
    orderId?: number //订单id
}

export default memo(forwardRef(({onSelect, onChangeShipmentMode, defaultValue = null, orderId = 0, shipment_mode = 1}: Param, ref) => {
    const [showAddressList, setShowAddressList] = useState(false)

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

    const [userInfo, setUserInfo] = useState<any>()

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

    const changeShow = () => {
        if(receivingStatus == 2)
            setShowAddressList(() => true)
    }
    
    useEffect(() => {
        setReceivingStatus(() => shipment_mode)
    }, [shipment_mode])

    //把内部方法提供给外部
    useImperativeHandle(ref, () => ({
        changeShow
    }))

    //收货方法,1:自提，2物流
    const [receivingStatus, setReceivingStatus] = useState(1)
    const {fetchData: shipmentModeFetchData} = EditSaleOrderShipmentModeApi()
    const onReceivingStatus = (value, e) => {
        e.stopPropagation()
        changeReceivingStatus(value)
    }
    const changeReceivingStatus = debounce(async (value) => {
        alert.loading('正在修改')
        const res = await shipmentModeFetchData({id: orderId, shipment_mode:value})
        if(res.success) {
            alert.success('收货方式修改成功')
            onChangeShipmentMode?.(value)
            setReceivingStatus(value)
        } else {
            alert.none(res.msg)
        }
    }, 10)

    //修改地址
    const {fetchData: addressFetchData} = EditSaleOrderAddressApi()
    const getAddress = async (value) => {
        alert.loading('正在修改')
        const res = await addressFetchData({id: orderId, address_id: value.id})
        if(res.success) {
            alert.success('地址修改成功')
            onSelect?.(value)
            setShowAddressList(() => false)
            setUserInfo(() => value)
        } else {
            alert.none(res.msg)
        }
    }

    return (
        <View>
            <View className={styles.order_address} onClick={() => changeShow()}>
                <View className={classnames(styles.order_address_icon, 'iconfont', receivingStatus == 2?'icon-daohang':'icon-fahuo')}></View>
                <View className={styles.order_address_text_con}>
                    <View className={styles.order_address_text_title}>
                        <Text>{formatAddress}</Text>
                        {(receivingStatus == 2)&&<Text className={classnames(styles.moreIconfont,'iconfont icon-a-moreback')}></Text>}
                    </View>
                    <View className={styles.order_address_text_name}>
                        <Text>{userInfo?.name}</Text>
                        <Text>{userInfo?.phone}</Text>
                    </View>
                </View>
                <View className={styles.updateBtn}>
                    <View className={styles.updateBtn_list}>
                        <View className={classnames(styles.updateBtn_item, receivingStatus==1&&styles.updateBtn_item_select)} onClick={(e) => onReceivingStatus(1,e)}>自提</View>
                        <View className={classnames(styles.updateBtn_item, receivingStatus==2&&styles.updateBtn_item_select)} onClick={(e) => onReceivingStatus(2,e)}>物流</View>
                    </View>
                    <View style={{transform: receivingStatus==1?'translateX(0)':'translateX(100%)'}} className={classnames(styles.updateBtn_select)}></View>
                </View>
            </View>
            <Popup show={showAddressList} showTitle={false} onClose={() => setShowAddressList(false)}>
                <View className={styles.order_address_list}>
                    <View className={styles.order_address_title}>请选择收货地址</View>
                    <AddressList onSelect={getAddress}/>
                </View>
            </Popup>
        </View>
    )
}))