import { View, Input, Button } from '@tarojs/components'
import { useCallback, useEffect, useMemo, useRef, useState, } from 'react'
import Search from '@/components/search'
import { dataLoadingStatus, getFilterData } from '@/common/util'
import styles from "./index.module.scss"
import classnames from "classnames";
import Popup from '@/components/popup'
import InfiniteScroll from '@/components/infiniteScroll'
import Taro, { faceVerifyForPay, useDidShow } from '@tarojs/taro'
import ItemList from './components/itemList'
import { formatDateTime, formatHashTag, formatImgUrl, formatPriceDiv, formatWeightDiv } from '@/common/format'
import {
    mpreturnApplyOrderlist,
    mpenumreturnStage,
    mpenumreturnType
} from "@/api/refound"
import Tabs from "./components/tabs"
import TimePicker from "@/components/timePicker"
export default () => {



    //获取订单列表
    const { fetchData: listFetchData, state: orderState } = mpreturnApplyOrderlist()
    const [orderData, setOrderData] = useState<{ list: any[]; total: number }>({ list: [], total: 0 })
    const getOrderList = async () => {
        let res = await listFetchData({
            ...searchField
            // ...getFilterData(searchField),
            // ...getFilterData(searchObj)
        })
        setOrderData((e) => ({ ...e, list: res.data?.list, total: res.data?.total }))
        // setshowPopup(false)
        setRefresherTriggeredStatus(() => false)
    }

    //页码和页数

    const [searchField, setSearchField] = useState<
        {
            status: number | unknown;
            page: number;
            size: number;
            name: string;
            sale_mode: number | string;
            stage: number | string;
            return_type: number | string;
            saleStartTime: number | string;
            saleEndTime: number | string;
        }>({
            status: 1,
            page: 1,
            size: 10,
            name: '',
            sale_mode: '不限',
            stage: '不限',
            return_type: '不限',
            saleStartTime: '',
            saleEndTime: ''
        })
    const pageNum = useRef({ size: searchField.size, page: searchField.page })

    //监听筛选条件变化
    useEffect(() => {
        getOrderList()
    }, [searchField])

    //输入了搜索关键字
    const getSearchData = useCallback((e) => {
        pageNum.current.page = 1
        setOrderData(() => ({ list: [], total: 0 }))
        setSearchField((val) => ({ ...val, name: e, size: 10 }))
    }, [])

    //列表下拉刷新
    const [refresherTriggeredStatus, setRefresherTriggeredStatus] = useState(false)
    const getRefresherRefresh = async () => {
        pageNum.current.size = 1
        setRefresherTriggeredStatus(true)
        setSearchField((val) => ({ ...val, size: 10 }))
    }
    //数据加载状态
    const statusMore = useMemo(() => {
        return dataLoadingStatus({ list: orderData.list, total: orderData.total, status: orderState.loading })
    }, [orderData, orderState])

    //上拉加载数据
    const getScrolltolower = useCallback(() => {
        if (orderData.list.length < orderData.total) {
            pageNum.current.page++
            const size = pageNum.current.size * pageNum.current.page
            setSearchField({ ...searchField, size })
        }
    }, [orderData])


    //顶部栏
    const [TarBarList, setTarBarList] = useState<any[]>([{ id: 1, name: '售后申请', showBorder: true }, { id: 2, name: '申请记录', showBorder: false }])
    const handChose = (item) => {
        if (item.id === searchField.status) return
        TarBarList.map(it => {
            if (it.id === item.id) {
                it.showBorder = true
            } else {
                it.showBorder = false
            }
            setTarBarList([...TarBarList])
            pageNum.current.page = 1
            setOrderData(() => ({ list: [], total: 0 }))
            setSearchField((val) => ({ ...val, size: 10, status: item.id }))
        })
    }

    //筛选内容展示
    const [showPopup, setshowPopup] = useState(false)
    const showSelctPopup = () => {
        setshowPopup(true)
    }

    //关闭筛选内容展示
    const closePopup = () => {
        setshowPopup(false)
    }

    //订单类型
    const [modeList, setModeList] = useState<any[]>([{ id: -1, name: '不限' }, { id: 0, name: '大货' }, { id: 1, name: '剪版' }, { id: 2, name: '散剪' }])
    //选择订单类型
    const handCheckMode = (item) => {
        modeList.map(it => {
            if (it.id === item.id) {
                it.checked = true
            } else {
                it.checked = false
            }
            return it
        })
        setModeList([...modeList])
        setSearchField((e) => ({ ...e, sale_mode: item.id }))
    }
    useEffect(() => {
        getStagelist()
        getTypeList()
    }, [])



    //售后状态
    const [stageList, setStageList] = useState<any[]>([])
    const { fetchData: stageFetch } = mpenumreturnStage()
    const getStagelist = async () => {
        const res = await stageFetch()
        if (res.data) {
            res.data.list.unshift({ id: '', name: '不限', checked: false })
            res.data.list.map(it => {
                it.checked = false
                return it
            })
            setStageList([...res.data.list])

        }
    }

    //选择售后状态
    const handCheckStange = (item) => {
        stageList.map(it => {
            if (it.id === item.id) {
                it.checked = true
            } else {
                it.checked = false
            }
            return it
        })
        setStageList([...stageList])
        setSearchField((val) => ({ ...val, size: 10, stage: item.id }))
    }



    //退款类型
    const [typeList, setTypeList] = useState<any[]>([])
    const { fetchData: typeFetch } = mpenumreturnType()
    const getTypeList = async () => {
        const res = await typeFetch()
        if (res.data) {
            res.data.list.unshift({ id: '', name: '不限', checked: false })
            res.data.list.map(it => {
                it.checked = false
                return it
            })
            setTypeList([...res.data.list])
        }
    }

    //选择售后类型
    const handType = (item) => {
        typeList.map(it => {
            if (it.id === item.id) {
                it.checked = true
            } else {
                it.checked = false
            }
            return it
        })
        setTypeList([...typeList])
        setSearchField((val) => ({ ...val, size: 10, return_type: item.id }))
    }

    //是否不允许确认筛选
    const isDisabled = useMemo(() => {
        if (searchField.stage !== '不限' ||
            searchField.sale_mode !== '不限' ||
            searchField.return_type !== '不限' ||
            searchField.saleStartTime !== '' ||
            searchField.saleEndTime !== ''
        ) {
            return false
        } else {
            return true
        }
    }, [searchField])


    //重置
    const handReset = () => {
        const arrOne = resetArr(modeList)
        setModeList([...arrOne])
        const arrTwo = resetArr(typeList)
        setTypeList([...arrTwo])
        const arrThree = resetArr(stageList)
        setStageList([...arrThree])
        setSearchField((e) => ({
            ...e,
            sale_mode: '不限',
            stage: '不限',
            return_type: '不限',
            saleStartTime: '',
            saleEndTime: '',
        }))
        setStart(myDate.toLocaleDateString())
        setEnd('')
    }

    //数组重置
    const resetArr = (arr) => {
        arr.map(it => {
            it.checked = false
            return it
        })
        return arr
    }

    //展示时间筛选
    const [showTime, setShowTime] = useState(false)
    //关闭时间筛选
    const handClose = () => {
        setShowTime(false)
    }
    let myDate = new Date();
    const [start, setStart] = useState(myDate.toLocaleDateString())
    const [end, setEnd] = useState('')
    //选择时间
    const handTime = (eq) => {
        console.log(eq?.value?.start, 'eq?.value?.start')
        setSearchField((val) => ({ ...val, saleStartTime: eq?.value?.start, saleEndTime: eq?.value?.start }))
        setStart(eq?.value?.start)
        setEnd(eq?.value?.end)
        setShowTime(false)
        console.log(searchField, 8888)
    }

    const timeArea = useMemo(() => {
        if (end !== '') {
            return start + '   ' + '-' + '  ' + end
        } else {
            return '自定义起始时间'
        }
    }, [end])

    useEffect(() => {
        setSearchField(searchField)
    }, [searchField])

    return (
        <>
            <View style={{ background: '#FFFFFF', paddingLeft: '20rpx', paddingBottom: '20rpx', position: 'sticky', top: '0', zIndex: '99' }}>
                <Search placeholder='搜索商品/名称/颜色/订单号' showBtn={false} changeOnSearch={getSearchData} debounceTime={300} >
                    <View className={styles.flexBox} onClick={() => showSelctPopup()}>
                        <View className={classnames('iconfont', 'icon-shaixuan', !isDisabled ? styles.icon_shaixuan : styles.activeshaixuan)}></View>
                        <View className={classnames(isDisabled ? styles.shaixuan : styles.activeshai)}>筛选</View>
                    </View>
                </Search>
            </View>
            <Tabs list={TarBarList} handChose={(item) => handChose?.(item)}></Tabs>
            <View className={styles.order_list}>
                <InfiniteScroll
                    statusMore={statusMore}
                    selfonScrollToLower={getScrolltolower}
                    refresherEnabled={true}
                    refresherTriggered={refresherTriggeredStatus}
                    selfOnRefresherRefresh={getRefresherRefresh}>
                    {orderData?.list?.map((item, index) => {
                        return (
                            <View key={item.id} className={styles.order_item_con}>
                                <ItemList
                                    obj={item}
                                    key={index}
                                ></ItemList>
                            </View>
                        )
                    })}
                </InfiniteScroll>
                <View className={styles.kongboxTwo}></View>
            </View>
            <Popup title={'筛选订单'} show={showPopup} onClose={() => closePopup()}>
                <View className={styles.popupBox}>
                    <View className={styles.thirdBox}>
                        <View className={styles.thirdTopfont}>售后状态</View>
                        <View className={styles.flexModebox}>
                            {
                                stageList.map((item, index) => {
                                    return (
                                        <View onClick={() => { handCheckStange(item) }} className={classnames(item.checked ? styles.activemodeBox : styles.modeBox)} key={index}>{item.name}</View>
                                    )
                                })
                            }
                        </View>
                    </View>
                    <View className={styles.thirdBox}>
                        <View className={styles.thirdTopfont}>订单类型</View>
                        <View className={styles.flexModebox}>
                            {
                                modeList.map((item, index) => {
                                    return (
                                        <View onClick={() => { handCheckMode(item) }} className={classnames(item.checked ? styles.activemodeBox : styles.modeBox)} key={index}>{item.name}</View>
                                    )
                                })
                            }
                        </View>
                    </View>
                    <View className={styles.thirdBox}>
                        <View className={styles.thirdTopfont}>退款类型</View>
                        <View className={styles.flexModebox}>
                            {
                                typeList.map((item, index) => {
                                    return (
                                        <View onClick={() => { handType(item) }} className={classnames(item.checked ? styles.activemodeBox : styles.modeBox)} key={index}>{item.name}</View>
                                    )
                                })
                            }
                        </View>
                    </View>
                    <View className={styles.thirdBox}>
                        <View className={styles.thirdTopfont}>售后时间</View>
                        <View className={styles.timeBox2} onClick={() => { setShowTime(true) }}>{timeArea}
                            <View className={classnames('iconfont', 'icon-chakanquanbukehu', styles.more)}></View>
                        </View>
                    </View>
                    <View style={{ height: '100rpx' }}></View>

                    <View className={styles.bottomBox}>

                        <Button className={styles.resetBox} onClick={() => { handReset() }}> 重置</Button >
                        <Button className={classnames(isDisabled ? styles.button : styles.activeButton)} disabled={isDisabled} onClick={() => { setshowPopup?.(false) }}> 确认</Button >
                    </View>

                    {/* <View className={styles.areaBox}></View> */}
                </View>
            </Popup>
            <TimePicker
                start={start}
                end={end}
                showTime={showTime}
                closePopup={handClose}
                onSelectDate={(e) => handTime(e)}
            ></TimePicker>
        </>
    )
}
