import { 
    GetSaleOrderDetailApi, 
    EditSaleOrderRemarkApi, 
    CancelOrderApi
} from "@/api/order";
import { GetOrderPayApi } from "@/api/orderPay";
import { alert, goLink } from "@/common/common";
import { formatDateTime, formatPriceDiv } from "@/common/fotmat";
import OrderBtns from "@/components/orderBtns";
import Popup from "@/components/popup";
import SearchInput from "@/components/searchInput";
import { Text, Textarea, View } from "@tarojs/components"
import Taro, { useDidShow, usePullDownRefresh, useRouter } from "@tarojs/taro";
import classnames from "classnames";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import order from "../orderList/components/order";
import AddressInfoDetail from "./components/addressInfoDetail";
import KindList from "./components/kindList";
import orderState from "./components/orderState";
import OrderState from "./components/orderState";
import Payment from "./components/payment";
import Remark from "./components/remark";
import styles  from './index.module.scss'
 
 export default () => {
    const [showDesc, setShowDesc] = useState(false)
    
    const router = useRouter()
    const orderId = useRef<number>(Number(router.params.id))

    useDidShow(() => {
        getSaleOrderPreView()
    })

    //获取订单详情
    const [orderDetail, setOrderDetail] = useState<any>() //获取到的原始数据
    const {fetchData: getOrderFetchData} = GetSaleOrderDetailApi()
    const getSaleOrderPreView = async () => {
        if(orderId.current) {
            let res = await getOrderFetchData({id: orderId.current})
            setOrderDetail(res.data)
            setOrderRemark(res.data.remark)
        }
        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,
            status: orderDetail.status, //订单状态
            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, //空差优惠
        })
    }
    const formatPreViewOrderMemo = useMemo(() => {
        return formatDetailOrder
    }, [formatDetailOrder])

    //复制功能
    const clipboardData = () => {
        Taro.setClipboardData({
            data: orderDetail?.order_no||'',
            success: function (res) {
                Taro.showToast({
                    icon: 'none',
                    title: '复制成功'
                })
            }
        })
    }

    //格式化初始地址
    const defaultAddress = useMemo(() => {
        return  {
            province_name: orderDetail?.province_name,
            city_name: orderDetail?.city_name,
            district_name: orderDetail?.district_name,
            address_detail: orderDetail?.address_detail,
            // id: address.id,
            name: orderDetail?.target_user_name,
            phone: orderDetail?.target_user_phone
        }
       
    }, [orderDetail])

    //订单备注
    const {fetchData: remarkFetchData} = EditSaleOrderRemarkApi()
    const [orderRemark, setOrderRemark] = useState('')
    const getRemark = useCallback(async (e) => {
        setOrderRemark(() => e)
        let res = await remarkFetchData({remark:e, id: orderId.current})
        if(res.success) {
            getSaleOrderPreView()
            alert.success('提交成功')
        } else {
            alert.error(res.msg)
        }
        setShowDesc(() => false)
    }, [])

    //去付款
    const [payMentShow, setPayMentShow] = useState(false)
    const toPay = () => {
        setPayMentShow(true)
    }

    //打开地址修改
    const addressRef = useRef<any>(null)

    //修改收货方式
    const getShipmentMode = useCallback(() => {
        getSaleOrderPreView()
    }, [orderDetail])

    //修改地址
    const getAddress = useCallback(() => {
        getSaleOrderPreView()
    }, [orderDetail])

    //获取底部按钮点击, 获取按钮状态
    const orderStateClick = useCallback((val) => {
        console.log('val::', val)
        if(val == 1) {
            //取消订单
            getSaleOrderPreView()
        }
        if(val == 2) {
            //待付款
            toPay()
        }
    }, [orderDetail])

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

    return (
        <View className={styles.order_main}>
            {/* <View className={styles.weight_memo_con}>
                <WeightMemo/>
            </View> */}
            <OrderState list={orderDetail?.logistics_details}/>
            <View >
                <AddressInfoDetail orderId={orderDetail?.id} onSelect={getAddress} onChangeShipmentMode={getShipmentMode} ref={addressRef} defaultValue={defaultAddress} shipment_mode={orderDetail?.shipment_mode}/>
            </View>
            <KindList value={formatPreViewOrderMemo}/>
            <View className={styles.order_info} >
                <View className={styles.order_info_title}>订单信息</View>
                <SearchInput showBorder={false} title='单号' height={50}>
                    <View className={styles.order_num}>
                        <Text>{orderDetail?.order_no}</Text>
                        <View className={styles.order_num_btn} onClick={() => clipboardData()}>复制</View>
                    </View>
                </SearchInput>
                <SearchInput showBorder={false} title='下单时间' height={50}>
                    <Text>{formatDateTime(orderDetail?.create_time)}</Text>
                </SearchInput>
                <SearchInput showBorder={false} title='付款时间' height={50}>
                    <Text>{formatDateTime(orderDetail?.create_time)}</Text>
                </SearchInput>
            </View>
            <View className={styles.order_desc} onClick={() => setShowDesc(true)}>
                <View className={styles.order_desc_con}>订单备注</View>
                {
                    orderRemark&&<View className={styles.order_desc_text}>{orderDetail?.remark}</View>||
                    <View className={styles.order_desc_text_hint}>填写备注</View>
                }
                <View className={classnames(styles.miconfont, 'iconfont icon-a-moreback')}></View>
            </View>
            <View className={styles.submit_order}>
                <OrderBtns status={orderDetail?.status} orderId={orderDetail?.id} onClick={orderStateClick}/>
                {/* <View className={styles.order_btn} onClick={() => toPay()}>去支付</View>     */}
            </View>        
            <Popup show={showDesc} showTitle={false} onClose={() => setShowDesc(false)} >
                <Remark onSave={(e) => getRemark(e)}/>
            </Popup>
            <Payment show={payMentShow} onClose={() => setPayMentShow(false)} orderId={orderDetail?.should_collect_order_id}/>
            <View className="common_safe_area_y"></View>
        </View>
    )
 }
