import { GetAddressListApi } from "@/api/addressList";
import { addressListApi } from "@/api/addressManager";
import { EditSaleOrderAddressApi, EditSaleOrderShipmentModeApi } from "@/api/order";
import { alert, goLink } from "@/common/common";
import { ORDER_STATUS } from "@/common/enum";
import { debounce, throttle } 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, useRef, useState } from "react";
import Taro from "@tarojs/taro";
import styles  from './index.module.scss'


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
    }
}

//订单状态 
const {
    SaleorderstatusWaitingPrePayment,
    SaleOrderStatusBooking,
    SaleOrderStatusArranging,
    SaleOrderStatusArranged,
    SaleOrderStatusWaitingPayment,
    SaleOrderStatusWaitingReceipt,
    SaleOrderStatusAlreadyReceipt,
    SaleOrderStatusComplete,
    SaleOrderStatusRefund,
    SaleOrderStatusCancel,
} = ORDER_STATUS

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 && limitEdit())
            setShowAddressList(() => true)
    }

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

    //收货方法,1:自提，2物流
    const [receivingStatus, setReceivingStatus] = useState(2)
    const {fetchData: shipmentModeFetchData} = EditSaleOrderShipmentModeApi()
    const onReceivingStatus = async (value, e) => {
        e.stopPropagation()
        if(limitEdit()) changeReceivingStatus(value)
        
    }

    //当没有地址时获取地址列表中的第一个数据
    const {fetchData: addressListFetchData} = addressListApi()
    const getAddressListOne = async () => {
        if(orderInfo?.address_detail) return true
        let res = await addressListFetchData()
        if( res.data.list && res.data.list?.length > 0 ) {
            let info = res.data.list[0]
            await addressFetchData({id: orderInfo?.id, address_id: info.id})
            setAddressInfo((e) => ({...e, ...info, target_user_name: info.name, target_user_phone: info.phone}))
            return true
        } else {
            Taro.showModal({
                content: '您还没有地址，请前去新增地址',
                success: function (res) {
                    if (res.confirm) {
                        goLink('/pages/addressManager/index')
                    } else if (res.cancel) {
                        console.log('用户点击取消')
                    }
                }
            })
            return false
        }
      
        
    }
    
    const changeReceivingStatus = debounce(async (value) => {
        if(!orderInfo || value == receivingStatus) return false
        if(status == 1) {
            onChangeShipmentMode?.(value)
            setReceivingStatus(value)
            return false
        }
        if(value == 2) {
           let res = await getAddressListOne()
           if(!res) 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)
        }
    }, 300)

    //修改地址
    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((e) => ({...e, ...value, target_user_name: value.name, target_user_phone: value.phone}))
            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((e) => ({...e, ...value, target_user_name: value.name, target_user_phone: value.phone}))
        } else {
            alert.none(res.msg)
        }
    }

    //根据订单状态判断是否可修改
    const limitEdit = () => {
        let res = [
            SaleorderstatusWaitingPrePayment.value,
            SaleOrderStatusBooking.value,
            SaleOrderStatusArranging.value,
            SaleOrderStatusArranged.value,
            SaleOrderStatusWaitingPayment.value,
        ].includes(orderInfo?.status as number)
        if(!res && status != 1) alert.none('该订单状态不能修改地址！')
        return status == 1? true : res
    }


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

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

    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?.target_user_name}</Text>
                        <Text>{receivingStatus == 1?addressInfo?.take_goods_phone: addressInfo?.target_user_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>||
               (orderInfo?.status != SaleOrderStatusRefund.value)&&<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>
    )
}))