import { EditSaleOrderAddressApi, EditSaleOrderShipmentModeApi } from "@/api/order";
import { alert } from "@/common/common";
import { ORDER_STATUS } from "@/common/enum";
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, 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, //选择地址
    disabled?: false|true, //true禁用后只用于展示
    onChangeShipmentMode?: (val: number) => void, //返回收货方式
    onLogistics?: () => void, //查看物流
    status?: 1|2, //1确认订单时使用， 2订单流程
    orderInfo?: {
        id?: number //订单id
        shipment_mode?: 1|2, //1自提 2物流
        status?: number //订单状态
        province_name: string,
        city_name: string,
        district_name: string,
        address_detail: string,
        take_goods_address: string,
        take_goods_phone: string
    }
}

export default memo(forwardRef(({onSelect, onChangeShipmentMode, orderInfo, status = 2, disabled = false, onLogistics}: Param, ref) => {
    
    const [addressInfo, setAddressInfo] = useState<any>()
    useEffect(() => {
        if(orderInfo) {
            setReceivingStatus(() => orderInfo.shipment_mode||2)
            setAddressInfo(() => orderInfo)
        }
    }, [orderInfo])


    

    //打开地址列表
    const [showAddressList, setShowAddressList] = useState(false)
    const changeShow = () => {
        if(receivingStatus == 2 && !logisticsShow)
            setShowAddressList(() => true)
    }

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

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

    //修改地址
    const [addressId, setAddressId] = useState(0)
    const {fetchData: addressFetchData} = EditSaleOrderAddressApi()
    const getAddress = async (value) => {
        if(!orderInfo) return false
        if(status == 1) {
            setShowAddressList(() => false)
            setAddressId(value.id)
            setAddressInfo(() => value)
            onSelect?.(value)
            return false
        }
        alert.loading('正在修改')
        const res = await addressFetchData({id: orderInfo.id, address_id: value.id})
        if(res.success) {
            alert.success('地址修改成功')
            onSelect?.(value)
            setShowAddressList(() => false)
            setAddressId(value.id)
            setAddressInfo(() => value)
        } else {
            alert.none(res.msg)
        }
    }

    //订单状态 
    const {
        SaleOrderStatusWaitingReceipt,
        SaleOrderStatusAlreadyReceipt,
        SaleOrderStatusComplete,
        SaleOrderStatusRefund,
        SaleOrderStatusCancel,
    } = ORDER_STATUS


    //根据订单状态判断是否显示物流
    const logisticsShowList = [SaleOrderStatusWaitingReceipt.value, SaleOrderStatusAlreadyReceipt.value, SaleOrderStatusComplete.value, SaleOrderStatusRefund.value, SaleOrderStatusCancel.value]
    const logisticsShow = useMemo(() => {
        console.log('aa:',orderInfo?.status)
        return logisticsShowList.includes(orderInfo?.status as number) 
    }, [orderInfo])

    //地址格式
    const formatAddress = useMemo(() => {
        if(receivingStatus == 2) {
            return addressInfo?.province_name?addressInfo.province_name + addressInfo.city_name + addressInfo.district_name + addressInfo.address_detail:''
        } else {
            return addressInfo?.take_goods_address
        }
    }, [addressInfo, receivingStatus])

    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 className={classnames(styles.address_text, styles.address_text_no)}>{formatAddress||'请选择收货地址及信息'}</Text>
                        {(receivingStatus == 2 && !logisticsShow)&&<Text className={classnames(styles.moreIconfont,'iconfont icon-a-moreback')}></Text>}
                    </View>
                    <View className={styles.order_address_text_name}>
                        <Text>{receivingStatus == 1?'管理员':addressInfo?.name}</Text>
                        <Text>{receivingStatus == 1?addressInfo?.take_goods_phone: addressInfo?.phone}</Text>
                    </View>
                </View>
                {!logisticsShow&&<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 className={styles.logisticsBtn} onClick={onLogistics}>
                    查看物流
                </View>}
            </View>
            <Popup show={showAddressList} showTitle={false} onClose={() => setShowAddressList(false)}>
                <View className={styles.order_address_list}>
                    <View className={styles.order_address_title}>请选择收货地址</View>
                    <View className={styles.addressList_con}>
                        <AddressList onSelect={getAddress} id={addressId}/>
                    </View>
                </View>
            </Popup>
        </View>
    )
}))