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 {
    mpcashManagementOrderlist
} from "@/api/newCollection"
import TimePicker from "@/components/timePicker"
import dayjs from 'dayjs'
import IconFont from '@/components/iconfont/iconfont'

export default () => {
    let myDate = new Date();
    const [searchField, setSearchField] = useState<
        {
            page: number;
            size: number;
            search_name: string;
            start_time: number | string;
            end_time: number | string;
        }>({
            page: 1,
            size: 10,
            search_name: '',
            start_time: `${dayjs(new Date(myDate?.toLocaleDateString() + ' ' + '00:00:00',)).format('YYYY-MM-DD')} 00:00:00`,
            end_time: `${dayjs(new Date(myDate?.toLocaleDateString() + ' ' + '00:00:00',)).add(14, 'day').format('YYYY-MM-DD')} 00:00:00`,
        })
    const pageNum = useRef({ size: searchField.size, page: searchField.page })

    useDidShow(() => {
        getOrderList()
    })

    //监听筛选条件变化
    useEffect(() => {
        getOrderList()
    }, [searchField.size, searchField.search_name])
    //输入了搜索关键字
    const getSearchData = useCallback((e) => {
        pageNum.current.page = 1
        setOrderData(() => ({ list: [], total: 0 }))
        setSearchField((val) => ({ ...val, search_name: e, size: 10 }))
    }, [])


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

    //列表下拉刷新
    const [refresherTriggeredStatus, setRefresherTriggeredStatus] = useState(false)
    const getRefresherRefresh = async () => {
        pageNum.current.page = 1
        // pageNum.current.size = 10
        setRefresherTriggeredStatus(true)
        getOrderList()
        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
            console.log(pageNum.current.page, 'pageNum.current.page')
            console.log(size, 123123)
            setSearchField({ ...searchField, size })
        }
    }, [orderData])

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

    //新建收款
    const handAdd = () => {
        Taro.navigateTo({
            url: '/pages/addCollection/index'
        })
    }

    //筛选弹出

    const [SelectPopup, setSelectPopup] = useState(false)

    //时间数组
    const [TimeList, setTimeList] = useState<any[]>(
        [
            {
                id: 1,
                name: '默认14天内',
                start_time: `${dayjs(new Date(myDate?.toLocaleDateString() + ' ' + '00:00:00',)).format('YYYY-MM-DD')} 00:00:00`,
                end_time: `${dayjs(new Date(myDate?.toLocaleDateString() + ' ' + '00:00:00',)).add(14, 'day').format('YYYY-MM-DD')} 00:00:00`,
                checked: true
            },
            {
                id: 2,
                name: '展示全部日期',
                start_time: '',
                end_time: '',
                checked: false
            }
        ]
    )

    //选择时间item
    const handSelect = (it) => {

        TimeList.map(item => {
            if (item.id == it.id) {
                item.checked = true
            } else {
                item.checked = false
            }
            return item
        })
        setTimeList([...TimeList])
        pageNum.current.size = 10
        setSearchField({ ...searchField, start_time: it.start_time, end_time: it.end_time, size: 10 })
        setEnd('')
    }

    //重置
    const handReset = () => {
        TimeList.map(item => {
            if (item.id == 1) {
                item.checked = true
            } else {
                item.checked = false
            }
            return item
        })
        setTimeList([...TimeList])
        pageNum.current.size = 10
        setSearchField({
            ...searchField,
            start_time: `${dayjs(new Date(myDate?.toLocaleDateString() + ' ' + '00:00:00',)).format('YYYY-MM-DD')} 00:00:00`,
            end_time: `${dayjs(new Date(myDate?.toLocaleDateString() + ' ' + '00:00:00',)).add(14, 'day').format('YYYY-MM-DD')} 00:00:00`,
            size: 10
        })
        setStart(myDate.toLocaleDateString())
        setEnd('')
    }



    //弹窗确认选择
    const handSureSelect = () => {
        pageNum.current.size = 10
        setSearchField({ ...searchField, size: 10 })
        getOrderList()
        setSelectPopup(false)
    }

    //展示时间筛选
    const [showTime, setShowTime] = useState(false)
    //关闭时间筛选
    const handClose = () => {
        setShowTime(false)
    }

    const [start, setStart] = useState<any>(myDate.toLocaleDateString())
    const [end, setEnd] = useState<any>('')
    //选择时间
    const handTime = (eq) => {
        //直接进来点确定的时候做处理
        if (Object.keys(eq).length === 0) {
            let obj = {
                start: '',
                end: ''
            }
            obj.start = `${dayjs(new Date(myDate?.toLocaleDateString() + ' ' + '00:00:00',)).format('YYYY-MM-DD')} 00:00:00`,
                obj.end = `${dayjs(new Date(obj?.start)).add(1, 'day').format('YYYY-MM-DD')} 00:00:00`
            eq.value = obj
        }
        setSearchField((val) => ({ ...val, start_time: eq?.value?.start, end_time: eq?.value?.end }))
        setStart(eq?.value?.start)
        setEnd(eq?.value?.end)
        setShowTime(false)
        pageNum.current.size = 10
    }


    const timeArea = useMemo(() => {
        // const res = TimeList.filter(item => {
        //     return item.checked
        // })
        // && res.length > 0
        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={() => { setSelectPopup(true) }}>
                        <IconFont name='icon-shaixuan' size={35} color={!isDisabled ? '#0D7CFF' : ''} customClassName={styles['activeshaixuan']} />
                        {/* <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>
            <View className={styles.pageTop}>
                <View className={styles.pageTopLeft}>时间默认14天内</View>
                <View className={styles.pageTopRight}>金额汇总：{formatPriceDiv(orderData.summary.receipt_amount)}</View>
            </View>
            <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 className={styles.fixedBox}>
                    <View className={styles.addBtn} onClick={() => handAdd()}>新建收款</View>
                </View>
            </View>
            <Popup title={'选择日期'} show={SelectPopup} onClose={() => { setSelectPopup(false) }}>
                <View className={styles.popupBox}>
                    <View className={styles.timeFlex}>
                        {
                            TimeList.map((item, index) => {
                                return (
                                    <View onClick={() => handSelect(item)} className={classnames((item.checked && timeArea == '自定义起始时间') ? styles.activetimeOne : styles.timeOne)} key={index}>{item.name}</View>
                                )
                            })
                        }
                    </View>
                    <View className={classnames(timeArea == '自定义起始时间' ? styles.timeBox2 : styles.activetimeBox2)} onClick={() => { setShowTime(true) }}>{timeArea}
                        <View className={styles.more}>
                            {
                                timeArea == '自定义起始时间' &&
                                <IconFont name={'icon-chakanquanbukehu'} color={'#000000'} size={40} customClassName={styles['more']}></IconFont>
                            }
                        </View>
                        {/* {
                            timeArea == '自定义起始时间' && <View className={classnames('iconfont', 'icon-chakanquanbukehu', styles.more)}></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={() => handSureSelect()}> 确认</Button >
                    </View>
                </View>
            </Popup>
            <TimePicker
                start={start}
                end={end}
                showTime={showTime}
                closePopup={handClose}
                onSelectDate={(e) => handTime(e)}
            ></TimePicker>
        </>
    )
}