import { 
    GetSaleOrderDetailApi, 
    EditSaleOrderRemarkApi, 
} from "@/api/order";
import { GetOrderPayApi } from "@/api/orderPay";
import { SaleOrderOrderDetailApi } from "@/api/salesAfterOrder";
import { alert, goLink } from "@/common/common";
import { ORDER_STATUS } from "@/common/enum";
import { formatDateTime, formatImgUrl, formatPriceDiv } from "@/common/fotmat";
import AfterOrderBtns from "@/components/afterOrderBtns";
import OrderBtns from "@/components/orderBtns";
import SearchInput from "@/components/searchInput";
import { Image, Text, Textarea, View } from "@tarojs/components"
import Taro, {useDidShow, usePullDownRefresh, useRouter } from "@tarojs/taro";
import classnames from "classnames";
import { useCallback, useEffect, useMemo, useRef, useState, memo } from "react";
import AddressInfoDetail from "./components/addressInfoDetail";
import ApplyRecord from "./components/applyRecord";
import ContentBox from "./components/contentBox";
import KindList from "./components/kindList";
import OrderState from "./components/orderState";
import ReturnLogistics from "./components/returnLogistics";
import styles  from './index.module.scss'
 
 export default () => {

    const router = useRouter()
    const orderId = useRef<number>(Number(router.params.id))
    useDidShow(() => {
        getSaleOrderPreView()
    })

    //获取订单详情
    const [orderDetail, setOrderDetail] = useState<any>() //获取到的原始数据
    const {fetchData: saleOrderOrderDetailData} = SaleOrderOrderDetailApi()
    const getSaleOrderPreView = async () => {
        if(orderId.current) {
            let res = await saleOrderOrderDetailData({id: orderId.current})
            setOrderDetail(res.data)
        }
        Taro.stopPullDownRefresh()       
    }

    //监听获取到的数据
    useEffect(() => {
        if(orderDetail)
            formatData()
    }, [orderDetail])

    //格式化数据格式
    const [formatDetailOrder, setFormatDetailOrder] = useState<any>() //格式化后的数据
    const formatData = () => {  
        setFormatDetailOrder({
            estimate_amount: orderDetail.estimate_amount, //预估金额
            sale_mode: orderDetail.sale_mode,
            sale_mode_name: orderDetail.sale_mode_name, 
            total_colors: orderDetail.total_colors, //总颜色数量
            total_number: orderDetail.total_number, //总数量
            total_fabrics: orderDetail.total_fabrics, //面料数量
            unit: orderDetail.sale_mode == 0?'条':'m', //单位
            list: orderDetail.product_list,
            stage: orderDetail.stage, //订单状态
            type: orderDetail.type, //退货or退款
            total_sale_price: orderDetail.total_sale_price, //销售金额
            total_should_collect_money: orderDetail.total_should_collect_money, //应收金额
            total_weight_error_discount: orderDetail.total_weight_error_discount, //空差优惠
            actual_amount: orderDetail.actual_amount, //实付金额
            the_previous_status: orderDetail.the_previous_status, //取消订单时的订单状态
        })
    }
    const formatPreViewOrderMemo = useMemo(() => {
        return formatDetailOrder
    }, [formatDetailOrder])


    //获取底部按钮点击, 获取按钮状态
    const orderStateClick = useCallback((val) => {
        
    }, [orderDetail])

    //页面下拉刷新
    usePullDownRefresh(() => {
        getSaleOrderPreView()
    })


    //按钮所需数据
    const orderInfo = useMemo(() => {
        return {
            stage: orderDetail?.stage, //售后订单状态
            orderId: orderDetail?.id,
            settle_mode: orderDetail?.settle_mode,
            type: orderDetail?.type, //退货or退款
            sale_mode: orderDetail?.sale_model, //订单类型
        }
    }, [orderDetail])

    //订单状态枚举
    const {SaleOrderStatusCancel} = ORDER_STATUS

    //物流显示
    const [logisticsShow, setLogisticsShow] = useState(false)
    const onShowLogistics = useCallback((val) => {
        if(val == 1) {
            setLogisticsShow(true)
        } else {
            const list = orderDetail?.fabric_piece_accessory_url.map(item => {
                return formatImgUrl(item)
            })
            Taro.previewImage({
                current: list[0], // 当前显示
                urls: list // 需要预览的图片http链接列表
            })
        }
    }, [orderDetail])
    const onCloseLogistics = useCallback(() => setLogisticsShow(false), [])
    //物流成功上传
    const logisticsSuccess = useCallback(() => {
        getSaleOrderPreView()
    }, [])

    //显示生气记录
    const [applyRecord, setApplyRecord] = useState(false)

    return (
        <View className={styles.order_main}>
            <OrderState orderInfo={orderDetail}/>
            <AddressInfoDetail return_address={orderDetail?.return_address} return_phone={orderDetail?.return_phone} stage={orderDetail?.stage} onLogistics={onShowLogistics}/>
            <KindList order={formatPreViewOrderMemo}/>
            <OrderDes orderInfo={orderDetail}/>
            {(orderDetail?.status != SaleOrderStatusCancel.value)&&<View className={styles.submit_order}>
                <AfterOrderBtns orderInfo={orderInfo} onClick={orderStateClick}/>
            </View>}       
            <AfterSalePricture urls={orderDetail?.fabric_piece_accessory_url}/>
            <ReturnLogistics show={logisticsShow} id={orderDetail?.return_apply_order_id} onClose={onCloseLogistics} onSubmit={logisticsSuccess}/>
            <ApplyRecord show={applyRecord} id={orderDetail?.id} onClose={() => setApplyRecord(false)}/>
            <View className="common_safe_area_y"></View>
        </View>
    )
 }

 const OrderDes = memo(({orderInfo}:{orderInfo?:any}) => {
    //复制功能
    const clipboardData = (val) => {
        Taro.setClipboardData({
            data: val,
            success: function (res) {
                Taro.showToast({
                    icon: 'none',
                    title: '复制成功'
                })
            }
        })
    }
    return (
        <View className={styles.order_info} >
            <View className={styles.order_info_title}>订单信息</View>
            <SearchInput showBorder={false} title='售后单号' height={50}>
                <View className={styles.order_num}>
                    <Text>{orderInfo?.return_order_no}</Text>
                    <View className={styles.order_num_btn} onClick={() => clipboardData(orderInfo?.return_order_no)}>复制</View>
                </View>
            </SearchInput>
            <SearchInput showBorder={false} title='订单号' height={50}>
                <View className={styles.order_num}>
                    <Text>{orderInfo?.order_no}</Text>
                    <View className={styles.order_num_btn} onClick={() => clipboardData(orderInfo?.order_no)}>复制</View>
                </View>
            </SearchInput>
            <SearchInput showBorder={false} title='退货原因' height={50}>
                <Text>{orderInfo?.return_reason_name}</Text>
            </SearchInput>
            <SearchInput showBorder={false} title='退货说明' height={50}>
                <Text>{orderInfo?.return_explain_name}</Text>
            </SearchInput>
            <SearchInput showBorder={false} title='其它说明' height={50}>
                <Text>{orderInfo?.return_remark}</Text>
            </SearchInput>
            <SearchInput showBorder={false} title='货物状况' height={50}>
                <Text>{orderInfo?.goods_status_name}</Text>
            </SearchInput>
            <SearchInput showBorder={false} title='申请时间' height={50}>
                <Text>{formatDateTime(orderInfo?.apply_time)}</Text>
            </SearchInput>
        </View>
    )
 })

 const AfterSalePricture = memo(({urls = []}:{urls: string[]}) => {

    const showList = useMemo(() => {
        let res = urls.map(item => {
            return formatImgUrl(item)
        })
        return res
    }, [urls])

     //预览图片
    const showImage = () => {
        Taro.previewImage({
            current: showList[0], // 当前显示
            urls: showList // 需要预览的图片http链接列表
        })
    }
    return (
        <ContentBox title="售后图片">
            <View className={styles.after_sale_picture_list}>
                {urls?.map(item=> <View className={styles.after_sale_picture_item} onClick={showImage}>
                    <Image src={formatImgUrl(item)} />
                </View>)}
            </View>
        </ContentBox>
    )
 })
