import { View, Input, Button, Image } from '@tarojs/components'
import { useCallback, useEffect, useMemo, useRef, useState, ReactNode, memo } from 'react'
import styles from "./index.module.scss"
import classnames from "classnames";
import Taro, { faceVerifyForPay, useDidShow, useRouter, usePullDownRefresh } from '@tarojs/taro'
import ItemList from './components/itemList'
import { formatDateTime, formatHashTag, formatImgUrl, formatPriceDiv, formatWeightDiv } from '@/common/format'
import {
    mpreturnApplyOrder,
    returnApplyOrdercancel,
    returnApplyOrderuploadAccessory
} from "@/api/refound"
import OrderState from './components/orderState'
import AddressDetailBox from './components/addressDetailBox'
import { IMG_CND_Prefix } from "@/common/constant";
import Popup from '@/components/popup';
import UploadImage from '@/components/uploadImage'
import { alert } from '@/common/common';
export default () => {
    //页面下拉刷新
    usePullDownRefresh(() => {
        getDetail()
    })
    const router = useRouter()
    useEffect(() => {
        getDetail()
    }, [])
    //获取详情
    const { fetchData: detailFetch } = mpreturnApplyOrder()
    const [DeatailObj, setDeatailObj] = useState<any>({})
    const getDetail = async () => {
        Taro.showLoading({
            title: '加载中...',
            mask: true
        })
        const res = await detailFetch({ id: Number(router.params.id) })
        if (res.data) {
            setDeatailObj(res.data)
            orderMsg.map(it => {
                if (it.leftTitle === '售后编号：') {
                    it.rightTitle = res.data.return_order_no
                }
                if (it.leftTitle === '订单号：') {
                    it.rightTitle = res.data.order_no
                }
                if (it.leftTitle === '退货原因：') {
                    it.rightTitle = res.data.return_reason_name
                }
                if (it.leftTitle === '退货说明：') {
                    it.rightTitle = res.data.return_explain_name
                }
                if (it.leftTitle === '其他什么：') {
                    it.rightTitle = res.data.reason_describe
                }
                if (it.leftTitle === '货物状况：') {
                    it.rightTitle = res.data.goods_status_name
                }
                if (it.leftTitle === '申请时间：') {
                    it.rightTitle = formatDateTime(res.data.apply_time)
                }
            })
            setOrderMsg([...orderMsg])
            setPicList([...res.data?.accessory_url !== null ? res.data?.accessory_url : []])
            Taro.hideLoading()
            // 小程序提供的api，通知页面停止下拉刷新效果
            Taro.stopPullDownRefresh();
        }
    }

    //分辨用质检中还是质检前的数组
    const productList = useMemo(() => {
        if (DeatailObj.stage === 0 ||
            (DeatailObj.sale_mode == 1 && DeatailObj.type == 1) || DeatailObj.stage === 1 || DeatailObj.stage === 2) {
            return DeatailObj.product_list
        } else {
            return DeatailObj.quality_check_pass_product
        }
    }, [DeatailObj])


    //订单信息文字数组
    const [orderMsg, setOrderMsg] = useState<any[]>([
        {
            leftTitle: '售后编号：',
            rightTitle: '------',
            showBtn: true
        },
        {
            leftTitle: '订单号：',
            rightTitle: '------',
            showBtn: true
        },
        {
            leftTitle: '退货原因：',
            rightTitle: '------',
        },
        {
            leftTitle: '退货说明：',
            rightTitle: '------',
        },
        {
            leftTitle: '其他什么：',
            rightTitle: '------',
        },
        {
            leftTitle: '货物状况：',
            rightTitle: '------',
        },
        {
            leftTitle: '申请时间：',
            rightTitle: '------',
        }
    ])

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

    //取消退货
    const { fetchData: cancelFetch } = returnApplyOrdercancel()
    const handCancle = async () => {
        Taro.showModal({
            content: "确定要取消吗？",
            confirmText: "确认",
            cancelText: "取消",
            success: async function (res) {
                if (res.confirm) {
                    const res = await cancelFetch({ id: Number(DeatailObj.id) })
                    Taro.showLoading({
                        title: '请稍等...',
                        mask: true
                    })
                    if (res.msg === 'success') {
                        Taro.showToast({
                            title: '取消成功'
                        })
                        Taro.hideLoading()
                        getDetail()
                    } else {
                        Taro.showToast({
                            title: res.msg,
                            icon: 'error'
                        })
                    }
                }
            }
        })


    }
    //查看图片
    const [ShowPic, setShowPic] = useState(false)


    const [PicList, setPicList] = useState<any[]>([])

    const handUp = (value) => {
        setShowPic(true)
    }

    const onlyRead = useMemo(() => {
        if (DeatailObj.stage == 1) {
            return false
        } else {
            return true
        }
    }, [DeatailObj])

    //获取图片列表 
    const picUrl = useRef([])
    const getImageList = useCallback((list) => {
        picUrl.current = list
    }, [])

    //提交附件
    const { fetchData: sureFetch } = returnApplyOrderuploadAccessory()
    const handSure = () => {
        let arr: any = []
        arr = [...picUrl.current]
        if (arr == 0) {
            return alert.error('请先添加附件')
        }
        Taro.showModal({
            content: "确定要提交吗？",
            confirmText: "确认",
            cancelText: "取消",
            success: async function (res) {
                if (res.confirm) {
                    const res = await sureFetch({ id: Number(DeatailObj.id), accessory_url: arr, })
                    Taro.showLoading({
                        title: '请稍等...',
                        mask: true
                    })
                    if (res.msg === 'success') {
                        Taro.showToast({
                            title: '成功'
                        })
                        setShowPic(false)
                        Taro.hideLoading()
                        getDetail()
                    } else {
                        Taro.showToast({
                            title: res.msg,
                            icon: 'error'
                        })
                    }
                }
            }
        })
    }
    const proview = (item) => {
        Taro.previewImage({
            current: IMG_CND_Prefix + item, // 当前显示图片的 http 链接
            urls: DeatailObj.fabric_piece_accessory_url.map((item) => {
                item = IMG_CND_Prefix + item;
                return item;
            }), // 需要预览的图片 http 链接列表
        });
    };


    return (
        <View className={styles.main}>
            <OrderState orderInfo={DeatailObj} />
            <AddressDetailBox
                obj={DeatailObj}
                handUp={() => handUp(DeatailObj)}
            ></AddressDetailBox>
            <DefaultBox
                showMode={true}
                title={'客户信息'}
                modeName={DeatailObj.sale_mode_name}
            >
                <View className={styles.pussBox}>
                    <View className={styles.pussName}>{DeatailObj.purchaser_name}</View>
                    <View className={styles.pussPhone}>{DeatailObj.purchaser_phone}</View>
                </View>
            </DefaultBox>
            <DefaultBox title={'退款信息'}>
                <GoodsItem list={productList} obj={DeatailObj}></GoodsItem>
                <View className={styles.totalBox}>
                    <View className={styles.totalLeft}>总计</View>
                    <View className={styles.totalRight}>{DeatailObj.total_fabrics} 种面料，{DeatailObj?.total_colors} 种颜色，共 {
                        DeatailObj?.sale_mode == 0 ? DeatailObj?.return_roll : DeatailObj?.total_number / 100
                    } {DeatailObj?.sale_mode == 0 ? "条" : "米"}</View>
                </View>
            </DefaultBox>
            <DefaultBox title={'订单信息'}>
                {
                    orderMsg.map((item, index) => {
                        return (
                            <View className={styles.detailBox} key={index}>
                                <View className={styles.detailFont}>
                                    {item.leftTitle}
                                </View>
                                <View className={styles.detailRightFlex}>
                                    <View className={styles.detailRight}>{item.rightTitle}</View>
                                    {item.showBtn && <View className={styles.detailBtn} onClick={() => clipboardData(item.rightTitle)}>复制</View>}
                                </View>

                            </View>
                        )
                    })
                }

            </DefaultBox>
            <DefaultBox title={'售后图片'}>
                <View className={styles.picBox}>
                    {
                        DeatailObj?.fabric_piece_accessory_url?.length > 0 && DeatailObj?.fabric_piece_accessory_url.map((item, index) => {
                            return (
                                <Image className={styles.pic} lazyLoad key={index} onClick={() => proview(item)}
                                    mode="aspectFill" src={IMG_CND_Prefix + item}></Image>
                            )
                        })
                    }
                    {
                        DeatailObj?.fabric_piece_accessory_url?.length === 0 && <View className={styles.noPic}>暂无图片</View>
                    }
                </View>
            </DefaultBox>
            <View className={styles.safeBox}></View>
            {
                (DeatailObj.stage === 0 || DeatailObj.stage === 1) && <View className={styles.bottomMuck}>
                    <View className={styles.cancleBtn} onClick={() => handCancle()}>取消退货</View>
                </View>
            }
            <Popup title={'查看/修改物流回单'} show={ShowPic} onClose={() => setShowPic(false)}>
                <>
                    <UploadImage onChange={getImageList} defaultList={PicList} onlyRead={onlyRead} />
                    {

                        !onlyRead && <View className={styles.picBtn} onClick={() => handSure()}>确认修改</View>
                    }
                </>
            </Popup>
        </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: any
}
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>
                            {
                                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.clear}> </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> */}
                                                    {
                                                        obj.sale_mode == 0 && <View className={styles.itemNums}>x{obj.stage == 0 || obj.stage == 1 || obj.stage == 2
                                                            ? it.roll
                                                            : obj.stage == 5 || obj.stage == 6 || obj.stage == 3
                                                                ? it.return_roll
                                                                : it.roll}{obj?.sale_mode == 0 ? '条' : 'm'}</View>
                                                    }
                                                    {
                                                        obj.sale_mode != 0 && <View className={styles.itemNums}>x{it.length / 100}m</View>
                                                    }
                                                </View>
                                                <View className={styles.item_right_Bottom}>
                                                    <View className={styles.itemMoney}>¥{it.sale_price / 100}/{obj?.sale_mode == 0 ? 'kg' : 'm'}</View>
                                                    {/* <View className={styles.itemMoneyOne}>¥{formatPriceDiv(it.total_sale_price)}</View> */}
                                                </View>
                                            </View>
                                        </View>
                                    )
                                })
                            }
                        </View>
                    )
                })
            }
        </>

    )
})