import { View } from '@tarojs/components'
import React, { useCallback, memo, useEffect, useMemo, useRef, useState, ReactNode } from 'react'
import styles from "./index.module.scss"
import classnames from "classnames";
import Taro, { usePullDownRefresh, useRouter, useDidShow } from '@tarojs/taro';
import AddressDetailBox from '../orderDetails/components/addressDetailBox'
import Remark from '../orderDetails/components//remark'
import Popup from '@/components/popup'
import { debounce } from '@/common/util'
import {
    mpsaleOrderpreView,
    mpsaleOrderput,
    mpsaleOrderaddress
} from '@/api/order'
import { alert } from '@/common/common'
import { formatPriceDiv, formatDateTime, formatWeightDiv } from '@/common/format'

export default () => {
    const router: any = useRouter()

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


    //收货方法,1:自提，2物流
    const [receivingStatus, setReceivingStatus] = useState(null)
    //切换自提或者物流
    const { fetchData: selectFetch } = mpsaleOrderaddress()
    const onReceivingStatus = debounce(async (e, value) => {
        if (infoObj.status === 8 || infoObj.status === 9 || infoObj.status === 4 || infoObj.status === 5) {
            alert.error('不允许更改')
            return false
        }
        e.stopPropagation()
        if (receivingStatus === value) {
            alert.error('不能选择相同的方式')
            return false
        }
        Taro.showLoading({
            title: '请稍等...',
            mask: true
        })
        const res = await selectFetch({ id: Number(infoObj.id), shipment_mode: value })
        if (res.msg === 'success') {
            Taro.hideLoading()
            Taro.showToast({
                title: '成功',
                icon: 'success'
            })
            setReceivingStatus(value)
        } else {
            Taro.hideLoading()
            Taro.showToast({
                title: res.msg,
                icon: 'error'
            })
        }
    }, 300)

    const { fetchData: infoFetch } = mpsaleOrderpreView()
    const [infoObj, setInfoObj] = useState<any>({})
    //获取订单详情
    const getDetail = async () => {
        let list: any[] = []
        router.params?.shopping_cart_product_color_list?.forEach(item => {
            list.push({
                shopping_cart_product_color_id: item.shopping_cart_product_color_id,
                sale_price: 0
            })
        })
        const query = {
            purchaser_id: router.params.purchaser_id,
            sale_mode: router.params.sale_mode,
            shopping_cart_product_color_list: list
        }
        const res = await infoFetch(query)
        setInfoObj(res.data)
        setReceivingStatus(res.data.shipment_mode)
    }

    //备注操作
    const [showDesc, setShowDesc] = useState(false)
    const { fetchData: remarkFetch } = mpsaleOrderput()
    const getRemark = useCallback(async (e) => {
        const res = await remarkFetch({ remark: e, id: Number(router.params.id) })
        if (res.msg === 'success') {
            Taro.showToast({
                title: '成功',
                icon: 'success'
            })
            setShowDesc(false)
            getDetail()
        }
    }, [])




    const handSelect = (obj) => {
        Taro.navigateTo({
            url: '/pages/addressManager/index?orderId=' + obj.id + '&purchaser_id=' + obj.purchaser_id
        })
    }

    return (
        <View className={styles.mainBox}>
            <AddressDetailBox
                navSelect={(obj) => handSelect(obj)}
                obj={infoObj}
                receivingStatus={receivingStatus}
                onReceivingStatus={(e, value) => onReceivingStatus(e, value)}
            ></AddressDetailBox>
            <DefaultBox
                showMode={true}
                title={'客户信息'}
                modeName={infoObj.sale_mode_name}
            >
                <View className={styles.pussBox}>
                    <View className={styles.pussName}>{infoObj.purchaser_name}</View>
                    <View className={styles.pussPhone}>{infoObj.purchaser_phone}</View>
                </View>
            </DefaultBox>
            <View className={styles.total}> {infoObj.total_fabrics} 种面料，{infoObj.total_colors} 个颜色，共 {infoObj.sale_mode === 0 ? infoObj.total_number : infoObj.total_number / 100} {infoObj.sale_mode === 0 ? '条' : 'm'}</View>
            <View className={styles.productBox}>
                <GoodsItem list={infoObj?.product_list} obj={infoObj}></GoodsItem>
                <View className={styles.flexMoney}>
                    <View className={styles.flexTotalBox}>
                        <View className={styles.totalFont}>合计金额</View>
                        <View className={classnames('iconfont', 'icon-tishi', styles.tishi)}></View>
                    </View>
                    <View className={styles.shoudPay}>{formatPriceDiv(infoObj.total_should_collect_money)}</View>
                </View>
            </View>
            <DefaultBox title={'备注信息'} showMode={true} modeName={`${'填写/修改备注'} >`} clickNode={() => setShowDesc(true)}>
                <View className={styles.remarkFont}>{infoObj.remark === '' ? '暂无' : infoObj.remark}</View>
            </DefaultBox>
            <Popup show={showDesc} showTitle={false} onClose={() => setShowDesc(false)}>
                <Remark onSave={(e) => getRemark(e)} defaultValue={infoObj.remark} />
            </Popup>
            <View className={styles.safeBottom}></View>
            <View className={styles.bottomBox}>
                <View className={styles.leftBottom}>
                    <View className={styles.topFlex}>
                        <View className={styles.topFont}>预估金额:</View>
                        <View className={styles.topTotal}>¥3564.00</View>
                    </View>
                    <View className={styles.bottomFlex}>3 种面料，3 种颜色，共 3 M</View>
                </View>
                <View className={styles.rightBottom}>提交订单</View>
            </View>
        </View>
    )
}



//卡片盒子元素
interface Obs {
    title?: string,
    modeName?: string,
    showMode?: boolean,
    children?: ReactNode,
    clickNode?: () => void
}

const DefaultBox = memo((props: Obs) => {
    const {
        title = '标题',
        modeName = '大货',
        showMode = false,
        children,
        clickNode
    } = props

    return (
        <View className={styles.defaltBox}>
            <View className={styles.titleBox}>
                <View className={styles.title}>{title}</View>
                {
                    showMode && <View className={styles.modeName} onClick={() => clickNode?.()}>{modeName}</View>
                }
            </View>
            <View className={styles.modeLine}></View>
            {children}
        </View>
    )
})


//产品商品元素
interface PropGoods {
    // item?: {
    //     code?: string | number
    // }
    list: any[],
    obj: {
        sale_mode?: number | string
    },
}
const GoodsItem = memo((porps: PropGoods) => {
    const { list = [], obj = {} } = porps
    return (
        <>
            {
                list.map((item, index) => {
                    return (
                        <View className={styles.goodsBox} key={index}>
                            <View className={styles.goodsProduct}>{item.code}# {item.name}</View>
                            <View className={styles.goodsLine}></View>
                            {
                                item.product_colors.map((it, inx) => {
                                    return (
                                        <View className={styles.itemGoods}>
                                            <View className={styles.itemPic} style={{ backgroundColor: `rgb(${it?.rgb?.r} ${it?.rgb?.g} ${it?.rgb?.b})` }}></View>
                                            <View className={styles.itemRight}>
                                                <View className={styles.item_right_top}>
                                                    <View className={styles.itemName}>{it.code}# {it.name}</View>
                                                    <View className={styles.itemNums}>x{obj?.sale_mode === 0 ? it.roll : it.length / 100}{obj?.sale_mode === 0 ? '条' : 'm'}</View>
                                                </View>
                                                <View className={styles.item_right_Bottom}>
                                                    <View className={styles.itemMoney}>¥{it.sale_price / 100}/{obj?.sale_mode === 0 ? '条' : 'm'}</View>
                                                    <View className={styles.itemMoneyOne}>¥{formatPriceDiv(it.total_sale_price)}</View>
                                                </View>
                                            </View>
                                        </View>
                                    )
                                })
                            }
                        </View>
                    )
                })
            }
        </>

    )
})

